PageSourceSearch

http://crazytools.ai/assets/index-DzdXWaC2.js

js crazytools.ai collected 2026-10-05 12:12:03 UTC 702,770 bytes, 43 lines download raw bytes

1function p(r){if(!r)throw new Error("Assertion failed.")}const ps=Math.PI/180,gs=180/Math.PI,or=r=>{const e=(r%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${r}.`)},hi=[1,0,0,0,1,0,0,0,1],yc=(r,e,t)=>{const[i,n,,s,a]=r,o=Math.abs(i)*e+Math.abs(s)*t,c=Math.abs(n)*e+Math.abs(a)*t;return Mr(Mr(Oa(-e/2,-t/2),r),Oa(o/2,c/2))},ii=r=>{const[e,t]=r,i=Math.atan2(t,bc(r)?-e:e);return or(ws(i*gs,90))},bc=r=>{const[e,t,,i,n]=r;return e*n-t*i<0},Ys=r=>{const e=r*ps,t=Math.round(Math.cos(e)),i=Math.round(Math.sin(e));return[t,i,0,-i,t,0,0,0,1]},Oa=(r,e)=>[1,0,0,0,1,0,r,e,1],kc=(r,e)=>[r,0,0,0,e,0,0,0,1],Mr=(r,e)=>{const t=new Array(9);for(let i=0;i<3;i++)for(let n=0;n<3;n++)t[3*i+n]=r[3*i]*e[n]+r[3*i+1]*e[3+n]+r[3*i+2]*e[6+n];return t},Tc=(r,e,t,i)=>({rotation:or(r+(e?-t:t)),flip:e!==i}),ue=r=>r&&r[r.length-1],_t=r=>r>=0&&r<2**32,Pu=r=>r>=-2147483648&&r<2**31,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)},wr=(r,e)=>{const t=e+1,i=Math.floor(Math.log2(t));r.writeBits(i,0),r.writeBits(1,1),r.writeBits(i,t-2**i)},Ct=r=>{const e=M(r);return(e&1)===0?-(e>>1):e+1>>1},Cu=(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}},se=r=>r.constructor===Uint8Array?r:ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength):new Uint8Array(r),q=r=>r.constructor===DataView?r:ArrayBuffer.isView(r)?new DataView(r.buffer,r.byteOffset,r.byteLength):new DataView(r),_u=typeof globalThis.TextEncoder<"u"?globalThis.TextEncoder:class{constructor(){this.encoding="utf-8"}encode(e=""){const t=new Uint8Array(3*e.length);let i=0;for(let n=0;n<e.length;n++){let s=e.charCodeAt(n);if(s<128)t[i++]=s;else if(s<2048)t[i++]=192|s>>6,t[i++]=128|s&63;else if(s<55296||s>57343)t[i++]=224|s>>12,t[i++]=128|s>>6&63,t[i++]=128|s&63;else{const a=n+1<e.length?e.charCodeAt(n+1):0;s<56320&&a>=56320&&a<=57343?(s=65536+(s-55296<<10)+(a-56320),n++,t[i++]=240|s>>18,t[i++]=128|s>>12&63,t[i++]=128|s>>6&63,t[i++]=128|s&63):(t[i++]=239,t[i++]=191,t[i++]=189)}}return t.slice(0,i)}},ci=typeof globalThis.TextDecoder<"u"?globalThis.TextDecoder:class{constructor(e="utf-8"){const t=e.trim().toLowerCase();if(t==="utf-8"||t==="utf8"||t==="unicode-1-1-utf-8")this.encoding="utf-8";else if(t==="utf-16le"||t==="utf-16")this.encoding="utf-16le";else if(t==="utf-16be")this.encoding="utf-16be";else throw new RangeError(`The encoding label provided ('${e}') is invalid.`)}decode(e){const t=e?se(e):new Uint8Array(0),i=[];if(this.encoding==="utf-8"){let s=t.length>=3&&t[0]===239&&t[1]===187&&t[2]===191?3:0;for(;s<t.length;){const a=t[s];if(a<128){i.push(a),s++;continue}let o,c;if(a>=194&&a<224)o=1,c=a&31;else if(a>=224&&a<240)o=2,c=a&15;else if(a>=240&&a<245)o=3,c=a&7;else{i.push(65533),s++;continue}let l=a===224?160:a===240?144:128,u=a===237?159:a===244?143:191,d=1;for(;d<=o;d++){const f=s+d<t.length?t[s+d]:0;if(f<l||f>u)break;c=c<<6|f&63,l=128,u=191}s+=d,d<=o?i.push(65533):c>=65536?(c-=65536,i.push(55296|c>>10,56320|c&1023)):i.push(c)}}else{const s=this.encoding==="utf-16le",a=s?255:254,o=s?254:255;let c=t.length>=2&&t[0]===a&&t[1]===o?2:0;for(;c+1<t.length;){const l=s?t[c]|t[c+1]<<8:t[c]<<8|t[c+1];if(c+=2,l>=55296&&l<=56319){const u=c+1<t.length?s?t[c]|t[c+1]<<8:t[c]<<8|t[c+1]:-1;u>=56320&&u<=57343?(i.push(l,u),c+=2):i.push(65533)}else l>=56320&&l<=57343?i.push(65533):i.push(l)}c<t.length&&i.push(65533)}let n="";for(let s=0;s<i.length;s+=8192)n+=String.fromCharCode(...i.slice(s,s+8192));return n}},Ue=new ci,Z=new _u,gt=r=>{for(let e=0;e<r.length;e++)if(r.charCodeAt(e)>255)return!1;return!0},Zs=r=>Object.fromEntries(Object.entries(r).map(([e,t])=>[t,e])),fr={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},St=Zs(fr),hr={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},At=Zs(hr),mr={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},xt=Zs(mr),Js=r=>!!r&&!!r.primaries&&!!r.transfer&&!!r.matrix&&r.fullRange!==void 0,Sc=r=>!r||r.primaries==null&&r.transfer==null&&r.matrix==null&&r.fullRange==null,A
1c={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Nr=r=>r instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&r instanceof SharedArrayBuffer||ArrayBuffer.isView(r);class pr{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 Iu=/^[0-9a-fA-F]+$/,mi=r=>[...r].map(e=>e.toString(16).padStart(2,"0")).join(""),Eu=r=>{p(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},Ua=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),Ei=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+n>>1,o=t(r[a]);o===e?(s=a,n=a-1):o<e?i=a+1:n=a-1}return s},X=(r,e,t)=>{let i=0,n=r.length-1,s=-1;for(;i<=n;){const a=i+(n-i+1)/2|0;t(r[a])<=e?(s=a,i=a+1):n=a-1}return s},Na=(r,e,t)=>{const i=X(r,t(e),t);r.splice(i+1,0,e)},ne=()=>{let r,e;return{promise:new Promise((i,n)=>{r=i,e=n}),resolve:r,reject:e}},Ji=(r,e)=>{const t=r.indexOf(e);t!==-1&&r.splice(t,1)},xc=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return r[t]},wn=(r,e)=>{for(let t=r.length-1;t>=0;t--)if(e(r[t]))return t;return-1},vu=async function*(r){Symbol.iterator in r?yield*r[Symbol.iterator]():yield*r[Symbol.asyncIterator]()},Bu=r=>{if(!(Symbol.iterator in r)&&!(Symbol.asyncIterator in r))throw new TypeError("Argument must be an iterable or async iterable.")},Ae=r=>{throw new Error(`Unexpected value: ${r}`)},yn=(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},Fu=(r,e,t)=>yn(r,e,t)<<8>>8,bn=(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))},Ru=(r,e,t,i)=>{t=le(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),bn(r,e,t,i)},Mu=(r,e,t,i)=>{r.setUint32(e+0,t,!0),r.setInt32(e+4,Math.floor(t/2**32),!0)},en=(r,e)=>({async next(){const t=await r.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return r.return()},throw(t){return r.throw(t)},[Symbol.asyncIterator](){return this}}),le=(r,e,t)=>Math.max(e,Math.min(t,r)),Du=(r,e,t)=>r+(e-r)*t,Va=(r,e)=>r-Math.floor(r/e)*e,Ie="und",pi=r=>{const e=Math.round(r);return Math.abs(r/e-1)<10*Number.EPSILON?e:r},ws=(r,e)=>Math.round(r/e)*e,Dr=(r,e)=>Math.round(r*e)/e,On=(r,e)=>Math.floor(r/e)*e,Wa=(r,e)=>Math.floor(r*e)/e,zu=r=>{let e=0;for(;r;)e++,r>>=1;return e},ys=r=>{let e=0;for(;r!==0;)r&=r-1,e++;return e},Ou=/^[a-z]{3}$/,gi=r=>Ou.test(r),Wt=1e6*(1+Number.EPSILON),La=(r,e)=>{const t={...r,...e};if(r.headers||e.headers){const i=r.headers?bs(r.headers):{},n=e.headers?bs(e.headers):{},s={...i};Object.entries(n).forEach(([a,o])=>{const c=Object.keys(s).find(l=>l.toLowerCase()===a.toLowerCase());c&&delete s[c],s[a]=o}),t.headers=s}return t},bs=r=>{if(r instanceof Headers){const e={};return r.forEach((t,i)=>{e[i]=t}),e}if(Array.isArray(r)){const e={};return r.forEach(([t,i])=>{e[t]=i}),e}return r},qa=async(r,e,t,i,n)=>{let s=0;for(;;)try{return await r(e,t)}catch(a){if(n())throw a;s++;const o=i(s,a,e);if(o===null)throw a;if(O._error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await wi(1e3*o),n())throw a}},Uu=(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 kn{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Un=null;const vr=()=>Un!==null?Un:Un=!!(typeof navigator<"u"&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let Nn=null;const tn=()=>Nn!==null?Nn:Nn=typeof navigator<"u"&&navigator.userAgent?.includes("Firefox");let Vn=null;
1const ks=()=>Vn!==null?Vn:Vn=!!(typeof navigator<"u"&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),Tn=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.`,Nu=(async()=>{})().constructor,v=r=>r instanceof Nu||r instanceof Promise?!0:typeof r?.then=="function",Tr=(r,e)=>r!==-1?r:e,Ts=(r,e,t,i)=>r<=i&&t<=e,Vr=function*(r){for(const e in r){const t=r[e];t!==void 0&&(yield{key:e,value:t})}},Vu=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}},rn=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},Wu=r=>{let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)},Pc=(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},ea=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},Ke=r=>typeof r=="number"&&!Number.isNaN(r),Be=(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("/")},ni=(r,e)=>{let t=0;for(let i=0;i<r.length;i++)e(r[i])&&t++;return t},ta=(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},Lu=(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},zr=r=>{p(Number.isInteger(r.num)),p(Number.isInteger(r.den)),p(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}},Wn=(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.`)};let Hr,qu=1;const Ha=new Map,ra=new Map,Cc=()=>typeof window>"u",Hu=()=>{const r=new Map,e=new Map;self.onmessage=t=>{const i=t.data;switch(i.type){case"set-timeout":{const n=setTimeout(()=>{r.delete(i.timerId),self.postMessage({type:"fire",timerId:i.timerId})},i.delay);r.set(i.timerId,n)}break;case"set-interval":{const n=setInterval(()=>{self.postMessage({type:"fire",timerId:i.timerId})},i.delay);e.set(i.timerId,n)}break;case"clear-timeout":{const n=r.get(i.timerId);n!==void 0&&(clearTimeout(n),r.delete(i.timerId))}break;case"clear-interval":{const n=e.get(i.timerId);n!==void 0&&(clearInterval(n),e.delete(i.timerId))}break}}},_c=()=>{if(Hr)return Hr;const r=`(${Hu.toString()})();`,e=URL.createObjectURL(new Blob([r],{type:"text/javascript"}));return Hr=new Worker(e),URL.revokeObjectURL(e),Hr.onmessage=t=>{const i=t.data,n=Ha.get(i.timerId);if(n){Ha.delete(i.timerId),n();return}const s=ra.get(i.timerId);s&&s()},Hr},ju=(r,e)=>{if(Cc())return{id:setInterval(r,e)};const t=qu++;return ra.set(t,()=>{r()}),_c().postMessage({type:"set-interval",timerId:t,delay:e}),{id:t}},Ku=r=>{if(Cc()){clearInterval(r.id);return}p(typeof r.id=="number"),ra.delete(r.id),_c().postMessage({type:"clear-interval",timerId:r.id})},wi=r=>new Promise(e=>setTimeout(e,r)),rr=r=>Array.isArray(r)?r:[r];class vi{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 yr=r=>Math.ceil(r/2)*2;class jp{constructor(e){this._queue=[],this._errored=!1,this.parallelism=e}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(e){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);const t=e();this._queue.push(t),t.then(()=>Ji(this._queue,t)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}}const Ic=r=>r!==null&&typeof r=="object"&&Object.getPrototypeOf(r)===Object.prototype&&Object.values(r).every(e=>typeof e=="string");var lt;(function(r){r[r.Silent=0]="Silent",r[r.Errors=1]="Errors",r[r.Warnings=2]="Warnings",r[r.Info=3]="Info"})(lt||(lt={}));class O{constructor(){}static get level(){return O._level}static set level(e){if(e!==lt.Silent&&e!==lt.Errors&&e!==lt.Warnings&&e!==lt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");O._level=e}static get _emitter(){return O._emitterInstance??=new vi}static on(e,t,i){return O._emitter.on(e,t,i)}
1static _error(...e){O._emitter._emit("error",e),O._level>=lt.Errors&&console.error(...e)}static _warn(...e){O._emitter._emit("warn",e),O._level>=lt.Warnings&&console.warn(...e)}static _info(...e){O._emitter._emit("info",e),O._level>=lt.Info&&console.info(...e)}}O._level=lt.Info;O._emitterInstance=null;class Br{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 ia{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 Ss=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.beatsPerMinute!==void 0&&(!Number.isInteger(r.beatsPerMinute)||r.beatsPerMinute<=0))throw new TypeError("tags.beatsPerMinute, when provided, must be a positive integer.");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"&&!(Array.isArray(e)&&e.every(t=>typeof t=="string"))&&!(e instanceof Uint8Array)&&!(e instanceof Br)&&!(e instanceof ia)&&!Ic(e))throw new TypeError("Each value in tags.raw must be a string, string array, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},yi=r=>r.title===void 0&&r.description===void 0&&r.artist===void 0&&r.album===void 0&&r.albumArtist===void 0&&r.trackNumber===void 0&&r.tracksTotal===void 0&&r.discNumber===void 0&&r.discsTotal===void 0&&r.genre===void 0&&r.beatsPerMinute===void 0&&r.date===void 0&&r.lyrics===void 0&&(!r.images||r.images.length===0)&&r.comment===void 0&&(r.raw===void 0||Object.keys(r.raw).length===0),Ft={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},Qu=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 H{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}copyBits(e,t){let i=0;for(i;i<e-7;i+=8)this.writeBits(8,t.readBits(8));const n=e-i;n>0&&this.writeBits(n,t.readBits(n))}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 H(this.bytes);return e.pos=this.pos,e}}const Qt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Wr=[-1,1,2,3,4,5,6,8],Bi=r=>{if(!r||r.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new H(r),t=Ln(e),{frequencyIndex:i,sampleRate:n}=qn(e),s=e.readBits(4);let a=null;s>=1&&s<=7&&(a=Wr[s]);let o=t,c=!1,l=n;if(t===5||t===29)c=t===29,l=qn(e).sampleRate,o=Ln(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}Ln(e)===5&&e.readBits(1)&&(l=qn(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}},Ln=r=>{const e=r.readBits(5);return e===31?32+r.readBits(6):e},qn=r=>{const e=r.readBits(4);return e===15?{frequencyIndex:e,sampleRate:r.readBits(24)}:{frequencyIndex:e,sampleRate:e<Qt.length?Qt[e]:null}},na=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=Wr.indexOf(n);if(s===-1)throw new TypeError(`Unsupported number of channels: ${r.outputNumberOfChannels}`);let a=16;r.objectType>=32&&(a+=6),As(i)===15&&(a+=24),e&&(a+=9,As(r.outputSampleRate)===15&&(a+=24));const o=Math.ceil(a/8),c=new Uint8Array(o),l=new H(c);return ja(l,r.objectType),Ka(l,i),l.writeBits(4,s),e&&(Ka(l,r.outputSampleRate),ja(l,2)),l.writeBits(3,0),c},ja=(r,e)=>{e<32?r.writeBits(5,e):(r.writeBits(5,31),r.writeBits(6,e-32))},Ka=(r,e)=>{const t=As(e);r.writeBits(4,t),t===15&&r.writeBits(24,e)},As=r=>{const e=Qt.indexOf(r);return e===-1?15:e},Ec=r=>{const e=new Uint8Array(7),t=new H(e),{coreObjectType:i,frequencyIndex:n,channelConfiguration:s}=r,a=i-1;return t.writeBits(12,4095),t.writeBits(1,0),t.writeBits(2,0),t.writeBits(1,1),t.writeBits(2,a),t.writeBits(4,n),t.writeBits(1,0),t.writeBits(3,s),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.skipBits(13),t.writeBits(11,2047),t.writeBits(2,0),{header:e,bitstream:t}},vc=(r,e)=>{r.pos=30,r.writeBits(13,e)};const Sn=[48e3,44100,32e3],Bc=[24e3,22050,16e3];var ye;(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"})(ye||(ye={}));var ae;(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"})(ae||(ae={}));const Lr=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})},sa=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=yn(i,t,!1):(p(e===4),n=i.getUint32(t,!1)),t+=e,yield{offset:t,length:n},t+=n}},Fc=(r,e)=>{if(e.description){const n=(se(e.description)[4]&3)+1;return sa(r,n)}else return Lr(r)},dr=r=>r&31,An=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)},Gu=r=>{const e=[];let t=0;for(const i of r)t===2&&i<=3&&(e.push(3),t=0),e.push(i),t=i===0?t+1:0;return new Uint8Array(e)},Hn=new Uint8Array([0,0,0,1]),nn=r=>{const e=r.reduce((n,s)=>n+Hn.byteLength+s.byteLength,0),t=new Uint8Array(e);let i=0;for(const n of r)t.set(Hn,i),i+=Hn.byteLength,t.set(n,i),i+=n.byteLength;return t},aa=(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:bn(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},$u=(r,e)=>{if(e.description){const n=(se(e.description)[4]&3)+1;return aa(r,n)}else return nn(r)},xn=r=>{try{const e=[],t=[],i=[];for(const o of Lr(r)){const c=r.subarray(o.offset,o.offset+o.length),l=dr(c[0]);l===ye.SPS?e.push(c):l===ye.PPS?t.push(c):l===ye.SPS_EXT&&i.push(c)}if(e.length===0||t.length===0)return null;const n=e[0],s=bi(n);p(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 O._error("Error building AVC Decoder Configuration Record:",e),null}},Rc=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)&&r.chromaFormat!==null){p(r.bitDepthLumaMinus8!==null),p(r.bitDepthChromaMinus8!==null),p(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)},oa=r=>{try{const e=q(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 g=e.getUint16(t,!1);t+=2,l.push(r.subarray(t,t+g)),t+=g}const u=e.getUint8(t++),d=[];for(let h=0;h<u;h++){const g=e.getUint16(t,!1);t+=2,d.push(r.subarray(t,t+g)),t+=g}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,g=e.getUint8(t++)&7,m=e.getUint8(t++)&7,w=e.getUint8(t++);f.chromaFormat=h,f.bitDepthLumaMinus8=g,f.bitDepthChromaMinus8=m;const y=[];for(let b=0;b<w;b++){const k=e.getUint16(t,!1);t+=2,y.push(r.subarray(t,t+k)),t+=k}f.sequenceParameterSetExt=y}return f}catch(e){return O._error("Error deserializing AVC Decoder Configuration Record:",e),null}},Mc={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}},bi=r=>{try{const e=An(r),t=new H(e);if(t.skipBits(1),t.skipBits(2),t.readBits(5)!==7)return null;const n=t.readAlignedByte(),s=t.readAlignedByte(),a=t.readAlignedByte();M(t);let o=1,c=0,l=0,u=0;if((n===100||n===110||n===122||n===244||n===44||n===83||n===86||n===118||n===128)&&(o=M(t),o===3&&(u=t.readBits(1)),c=M(t),l=M(t),t.skipBits(1),t.readBits(1))){for(let j=0;j<(o!==3?8:12);j++)if(t.readBits(1)){const re=j<6?16:64;let $=8,G=8;for(let J=0;J<re;J++){if(G!==0){const me=Ct(t);G=($+me+256)%256}$=G===0?$:G}}}M(t);const d=M(t);if(d===0)M(t);else if(d===1){t.skipBits(1),Ct(t),Ct(t);const V=M(t);for(let j=0;j<V;j++)Ct(t)}M(t),t.skipBits(1);const f=M(t),h=M(t),g=16*(f+1),m=16*(h+1);let w=g,y=m;const b=t.readBits(1);if(b||t.skipBits(1),t.skipBits(1),t.readBits(1)){const V=M(t),j=M(t),oe=M(t),re=M(t);let $,G;if((u===0?o:0)===0)$=1,G=2-b;else{const me=o===3?1:2,Te=o===1?2:1;$=me,G=Te*(2-b)}w-=$*(V+j),y-=G*(oe+re)}let S=2,T=2,A=2,P=0,C={num:1,den:1},x=null,I=null,E=null,F=null;const D=t.pos;if(t.readBits(1)){if(t.readBits(1)){const me=t.readBits(8);if(me===255)C={num:t.readBits(16),den:t.readBits(16)};else{const Te=Mc[me];Te&&(C=Te)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),P=t.readBits(1),t.readBits(1)&&(S=t.readBits(8),T=t.readBits(8),A=t.readBits(8))),t.readBits(1)&&(M(t),M(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const G=t.readBits(1);G&&Qa(t);const J=t.readBits(1);J&&Qa(t),(G||J)&&t.skipBits(1),t.skipBits(1),E=t.pos,F=t.readBits(1),F&&(t.skipBits(1),M(t),M(t),M(t),M(t),x=M(t),I=M(t))}if(x===null){p(I===null);const V=s&16;if((n===44||n===86||n===100||n===110||n===122||n===244)&&V)x=0,I=0;else{const j=f+1,oe=h+1,re=(2-b)*oe,$=on.find(J=>J.level>=a)??ue(on),G=Math.min(Math.floor($.maxDpbMbs/(j*re)),16);x=G,I=G}}return p(I!==null),{emulationUnpreventedBytes:e,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:b,chromaFormatIdc:o,bitDepthLumaMinus8:c,bitDepthChromaMinus8:l,codedWidth:g,codedHeight:m,displayWidth:w,displayHeight:y,pixelAspectRatio:C,colourPrimaries:S,matrixCoefficients:A,transferCharacteristics:T,fullRangeFlag:P,numReorderFrames:x,maxDecFrameBuffering:I,vuiParametersFlagBitOffset:D,bitstreamRestrictionFlagBitOffset:E,bitstreamRestrictionFlag:F}}catch(e){return O._error("Error parsing AVC SPS:",e),null}},Qa=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)},Ga=r=>{p(r.bitstreamRestrictionFlag!==1);const e=new Uint8Array(r.emulationUnpreventedBytes.byteLength+64),t=new H(r.emulationUnpreventedBytes),i=new H(e);r.bitstreamRestrictionFlag===null?(i.copyBits(r.vuiParametersFlagBitOffset,t),i.writeBits(1,1),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0)):(p(r.bitstreamRestrictionFlagBitOffset!==null),i.copyBits(r.bitstreamRestrictionFlagBitOffset,t)),i.writeBits(1,1),i.writeBits(1,1),wr(i,2),wr(i,1),wr(i,16),wr(i,16),wr(i,r.numReorderFrames),wr(i,r.maxDecFrameBuffering),i.writeBits(1,1),i.writeBits((8-i.pos%8)%8,0);const n=i.pos/8;return p(Number.isInteger(n)),Gu(e.subarray(0,n))},Xu=(r,e)=>{if(e.description){const n=(se(e.description)[21]&3)+1;return aa(r,n)}else return nn(r)},sn=(r,e)=>{if(e.description){const n=(se(e.description)[21]&3)+1;return sa(r,n)}else return Lr(r)},Gt=r=>r>>1&63,ca=r=>{try{const e=new H(An(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}=Yu(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 g=f,m=h;if(e.readBits(1)){const F=M(e),D=M(e),z=M(e),V=M(e);let j=1,oe=1;const re=d===0?u:0;re===1?(j=2,oe=2):re===2&&(j=2,oe=1),g-=(F+D)*j,m-=(z+V)*oe}const w=M(e),y=M(e);M(e);const k=e.readBits(1)?0:t;let S=0;for(let F=k;F<=t;F++)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)&&Zu(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(Ju(e,T),e.readBits(1)){const F=M(e);for(let D=0;D<F;D++)M(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let A=2,P=2,C=2,x=0,I=0,E={num:1,den:1};if(e.readBits(1)){const F=td(e,t);E=F.pixelAspectRatio,A=F.colourPrimaries,P=F.transferCharacteristics,C=F.matrixCoefficients,x=F.fullRangeFlag,I=F.minSpatialSegmentationIdc}return{displayWidth:g,displayHeight:m,pixelAspectRatio:E,colourPrimaries:A,transferCharacteristics:P,matrixCoefficients:C,fullRangeFlag:x,maxDecFrameBuffering:S+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:i,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:w,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:I}}catch(e){return O._error("Error parsing HEVC SPS:",e),null}},Pn=r=>{try{const e=[],t=[],i=[],n=[];for(const l of Lr(r)){const u=r.subarray(l.offset,l.offset+l.length),d=Gt(u[0]);d===ae.VPS_NUT?e.push(u):d===ae.SPS_NUT?t.push(u):d===ae.PPS_NUT?i.push(u):(d===ae.PREFIX_SEI_NUT||d===ae.SUFFIX_SEI_NUT)&&n.push(u)}if(t.length===0||i.length===0)return null;const s=ca(t[0]);if(!s)return null;let a=0;if(i.length>0){const l=i[0],u=new H(An(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),Ct(u),u.skipBits(1),u.skipBits(1),u.readBits(1)&&M(u),Ct(u),Ct(u),u.skipBits(1),u.skipBits(1),u.skipBits(1),u.skipBits(1);const d=u.readBits(1),f=u.readBits(1);!d&&!f?a=0:d&&!f?a=2:!d&&f?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:ae.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:ae.SPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ae.PPS_NUT,nalUnits:i}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Gt(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 O._error("Error building HEVC Decoder Configuration Record:",e),null}},Yu=(r,e)=>{const t=r.readBits(2),i=r.readBits(1),n=r.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|r.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=r.readBits(8);const o=r.readBits(8),c=[],l=[];for(let u=0;u<e;u++)c.push(r.readBits(1)),l.push(r.readBits(1));if(e>0)for(let u=e;u<8;u++)r.skipBits(2);for(let u=0;u<e;
1u++)c[u]&&r.skipBits(88),l[u]&&r.skipBits(8);return{general_profile_space:t,general_tier_flag:i,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},Zu=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&&Ct(r);for(let s=0;s<n;s++)Ct(r)}},Ju=(r,e)=>{const t=[];for(let i=0;i<e;i++)t[i]=ed(r,i,e,t)},ed=(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},td=(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=Mc[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)&&rd(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}},rd=(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&&$a(r,u,s),n&&$a(r,u,s)}},$a=(r,e,t)=>{for(let i=0;i<e;i++)M(r),M(r),t&&(M(r),M(r)),r.readBits(1)},id=r=>{const e=[];e.push(r.configurationVersion),e.push((r.generalProfileSpace&3)<<6|(r.generalTierFlag&1)<<5|r.generalProfileIdc&31),e.push(r.generalProfileCompatibilityFlags>>>24&255),e.push(r.generalProfileCompatibilityFlags>>>16&255),e.push(r.generalProfileCompatibilityFlags>>>8&255),e.push(r.generalProfileCompatibilityFlags&255),e.push(...r.generalConstraintIndicatorFlags),e.push(r.generalLevelIdc&255),e.push(240|r.minSpatialSegmentationIdc>>8&15),e.push(r.minSpatialSegmentationIdc&255),e.push(252|r.parallelismType&3),e.push(252|r.chromaFormatIdc&3),e.push(248|r.bitDepthLumaMinus8&7),e.push(248|r.bitDepthChromaMinus8&7),e.push(r.avgFrameRate>>8&255),e.push(r.avgFrameRate&255),e.push((r.constantFrameRate&3)<<6|(r.numTemporalLayers&7)<<3|(r.temporalIdNested&1)<<2|r.lengthSizeMinusOne&3),e.push(r.arrays.length&255);for(const t of r.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const i of t.nalUnits){e.push(i.length>>8&255),e.push(i.length&255);for(let n=0;n<i.length;n++)e.push(i[n])}}return new Uint8Array(e)},Dc=r=>{try{const e=q(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,g=e.getUint8(t++)&7,m=e.getUint8(t++)&7,w=e.getUint16(t,!1);t+=2;const y=e.getUint8(t++),b=y>>6&3,k=y>>3&7,S=y>>2&1,T=y&3,A=e.getUint8(t++),P=[];for(let C=0;C<A;C++){const x=e.getUint8(t++),I=x>>7&1,E=x&63,F=e.getUint16(t,!1);t+=2;const D=[];for(let z=0;z<F;z++){const V=e.getUint16(t,!1);t+=2,D.push(r.subarray(t,t+V)),t+=V}P.push({arrayCompleteness:I,nalUnitType:E,nalUnits:D})}return{configurationVersion:i,generalProfileSpace:s,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:f,chromaFormatIdc:h,bitDepthLumaMinus8:g,bitDepthChromaMinus8:m,avgFrameRate:w,constantFrameRate:b,numTemporalLayers:k,temporalIdNested:S,lengthSizeMinusOne:T,arrays:P}}catch(e){return O._error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var Re;
1(function(r){r[r.audAllowed=0]="audAllowed",r[r.beforeFirstVcl=1]="beforeFirstVcl",r[r.afterFirstVcl=2]="afterFirstVcl",r[r.eoBitstreamAllowed=3]="eoBitstreamAllowed",r[r.noMoreDataAllowed=4]="noMoreDataAllowed"})(Re||(Re={}));const nd=(r,e)=>{const t=new Set;let i=Re.audAllowed;for(const s of sn(r,e)){if(i===Re.noMoreDataAllowed){t.add(s.offset);continue}const a=Gt(r[s.offset]);if(i===Re.eoBitstreamAllowed&&a!==37){t.add(s.offset);continue}let o=!1;a===35?i>Re.audAllowed?o=!0:i=Re.beforeFirstVcl:a<=31?i>Re.afterFirstVcl?o=!0:i=Re.afterFirstVcl:a===36?i!==Re.afterFirstVcl?o=!0:i=Re.eoBitstreamAllowed:a===37?i<Re.afterFirstVcl?o=!0:i=Re.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?i>Re.beforeFirstVcl?o=!0:i=Re.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&i<Re.afterFirstVcl&&(o=!0),o&&t.add(s.offset)}if(t.size===0)return null;const n=[];for(const s of sn(r,e))t.has(s.offset)||n.push(r.subarray(s.offset,s.offset+s.length));return Xu(n,e)},sd={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}},zc=r=>{const e=new H(r);if(e.readBits(2)!==2)return null;const i=e.readBits(1),s=(e.readBits(1)<<1)+i;if(s===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let l=8;s>=2&&(l=e.readBits(1)?12:10);const u=e.readBits(3);let d=0,f=0;if(u!==7)if(f=e.readBits(1),s===1||s===3){const C=e.readBits(1),x=e.readBits(1);d=!C&&!x?3:C&&!x?2:1,e.skipBits(1)}else d=1;else d=3,f=1;const h=e.readBits(16),g=e.readBits(16),m=h+1,w=g+1,y=m*w;let b=ue(qt).level;for(const P of qt)if(y<=P.maxPictureSize){b=P.level;break}const k=sd[u],S=k?.colourPrimaries??2,T=k?.transferCharacteristics??2,A=k?.matrixCoefficients??2;return{profile:s,level:b,bitDepth:l,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:S,transferCharacteristics:T,matrixCoefficients:A}},ad=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,Oc=function*(r){const e=new H(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);p(e.pos%8===0),yield{type:i,data:r.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},la=r=>{for(const{type:e,data:t}of Oc(r)){if(e!==1)continue;const i=new H(t),n=i.readBits(3);i.readBits(1);const s=i.readBits(1);let a=0,o=0,c=0;if(s)a=i.readBits(5);else{const x=i.readBits(1);let I=0;if(x){if(i.skipBits(32),i.skipBits(32),i.readBits(1)){let z=0;for(;z<32&&!i.readBits(1);)z++;z<32&&i.skipBits(z)}I=i.readBits(1),I&&(c=i.readBits(5),i.skipBits(32),i.skipBits(5),i.skipBits(5))}const E=i.readBits(1),F=i.readBits(5);for(let D=0;D<=F;D++){i.skipBits(12);const z=i.readBits(5);if(D===0&&(a=z),z>7){const V=i.readBits(1);D===0&&(o=V)}if(I&&i.readBits(1)){const j=c+1;i.skipBits(j),i.skipBits(j),i.skipBits(1)}E&&i.readBits(1)&&i.skipBits(4)}}const l=i.readBits(4),u=i.readBits(4),d=l+1;i.skipBits(d);const f=u+1;i.skipBits(f);let h=0;if(s?h=0:h=i.readBits(1),h&&(i.skipBits(4),i.skipBits(3)),i.skipBits(1),i.skipBits(1),i.skipBits(1),!s){i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);const x=i.readBits(1);x&&(i.skipBits(1),i.skipBits(1));const I=i.readBits(1);let E=0;I?E=2:E=i.readBits(1),E>0&&(i.readBits(1)||i.skipBits(1)),x&&i.skipBits(3)}i.skipBits(1),i.skipBits(1),i.skipBits(1);const g=i.readBits(1);let m=8;n===2&&g?m=i.readBits(1)?12:10:n<=2&&(m=g?10:8);let w=0;n!==1&&(w=i.readBits(1));let y=2,b=2,k=2;i.readBits(1)&&(y=i.readBits(8),b=i.readBits(8),k=i.readBits(8));let T=0,A=1,P=1,C=0;return w?T=i.readBits(1):y===1&&b===13&&k===0?(T=1,A=0,P=0):(T=i.readBits(1),n===0?(A=1,P=1):n===1?(A=0,P=0):m===12?(A=i.readBits(1),P=A?i.readBits(1):0):(A=1,P=0),A&&P&&(C=i.readBits(2))),{profile:n,level:a,tier:o,bitDepth:m,monochrome:w,chromaSubsamplingX:A,chromaSubsamplingY:P,chromaSamplePosition:C,videoFullRangeFlag:T,colourPrimaries:y,transferCharacteristics:b,matrixCoefficients:k}}return null},od=r=>r.colourPrimaries!==2||r.transferCharacteristics!==2||r.matrixCoefficients!==2,Uc=r=>{if(r.length<36)return null;const t=q(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)}},Cn=r=>{const e=q(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}},cd=[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],ld=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:cd[e]*i}},Nc=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 H(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),g=n.readBits(16);if(f>63||h!==0||g!==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}},_n=(r,e,t)=>{switch(r){case"avc":{for(const i of Fc(t,e)){const n=t[i.offset],s=dr(n);if(s>=ye.NON_IDR_SLICE&&s<=ye.SLICE_DPC)return"delta";if(s===ye.IDR)return"key";if(s===ye.SEI&&!ks()){const a=t.subarray(i.offset,i.offset+i.length),o=An(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 H(o);f.pos=8*c;const h=M(f),g=f.readBits(1);if(h===0&&g===1)return"key"}c+=u}while(c<o.length-1)}}return"delta"}case"hevc":{for(const i of sn(t,e)){const n=Gt(t[i.offset]);if(n<ae.BLA_W_LP)return"delta";if(n<=ae.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const i=new H(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 Oc(t))if(n===1){const a=new H(s);a.skipBits(4),i=!!a.readBits(1)}else if(n===3||n===6||n===7){if(i)return"key";const a=new H(s);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}case"prores":return"key";default:Ae(r),p(!1)}};var It;(function(r){r[r.STREAMINFO=0]="STREAMINFO",r[r.VORBIS_COMMENT=4]="VORBIS_COMMENT",r[r.PICTURE=6]="PICTURE"})(It||(It={}));const xs=(r,e)=>{const t=q(r);let i=0;const n=t.getUint32(i,!0);i+=4;const s=Ue.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=Ue.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??={},Array.isArray(e.raw[d])?e.raw[d]=[...e.raw[d],f]:typeof e.raw[d]=="string"?e.raw[d]=[e.raw[d],f]: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("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(e.trackNumber??=g),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("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(e.discNumber??=g),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"BPM":{const h=Number.parseInt(f,10);Number.isInteger(h)&&h>0&&(e.beatsPerMinute??=h)}break;case"GENRE":e.genre??=f;break;case"METADATA_BLOCK_PICTURE":{const h=rn(f),g=q(h),m=g.getUint32(0,!1),w=g.getUint32(4,!1),y=String.fromCharCode(...h.subarray(8,8+w)),b=g.getUint32(8+w,!1),k=Ue.decode(h.subarray(12+w,12+w+b)),S=g.getUint32(w+b+28),T=h.subarray(w+b+32,w+b+32+S);e.images??=[],e.images.push({data:T,mimeType:y,kind:m===3?"coverFront":m===4?"coverBack":"unknown",name:void 0,description:k||void 0})}break}}},Ps=(r,e,t)=>{const i=[r],s=Z.encode("Mediabunny");let a=new Uint8Array(4+s.length),o=new DataView(a.buffer);o.setUint32(0,s.length,!0),a.set(s,4),i.push(a);const c=[],l=(g,m)=>{const w=`${g}=${m}`,y=Z.encode(w);a=new Uint8Array(4+y.length),o=new DataView(a.buffer),o.setUint32(0,y.length,!0),a.set(y,4),i.push(a),c.push(g)};for(const{key:g,value:m}of Vr(e))switch(g){case"title":l("TITLE",m);break;
1case"description":l("DESCRIPTION",m);break;case"artist":l("ARTIST",m);break;case"album":l("ALBUM",m);break;case"albumArtist":l("ALBUMARTIST",m);break;case"genre":l("GENRE",m);break;case"date":l("DATE",m.toISOString().slice(0,10));break;case"comment":l("COMMENT",m);break;case"lyrics":l("LYRICS",m);break;case"trackNumber":l("TRACKNUMBER",m.toString());break;case"tracksTotal":l("TRACKTOTAL",m.toString());break;case"discNumber":l("DISCNUMBER",m.toString());break;case"discsTotal":l("DISCTOTAL",m.toString());break;case"beatsPerMinute":l("BPM",m.toString());break;case"images":{if(!t)break;for(const w of m){const y=w.kind==="coverFront"?3:w.kind==="coverBack"?4:0,b=new Uint8Array(w.mimeType.length);for(let P=0;P<w.mimeType.length;P++)b[P]=w.mimeType.charCodeAt(P);const k=Z.encode(w.description??""),S=new Uint8Array(8+b.length+4+k.length+16+4+w.data.length),T=q(S);T.setUint32(0,y,!1),T.setUint32(4,b.length,!1),S.set(b,8),T.setUint32(8+b.length,k.length,!1),S.set(k,12+b.length),T.setUint32(28+b.length+k.length,w.data.length,!1),S.set(w.data,32+b.length+k.length);const A=Wu(S);l("METADATA_BLOCK_PICTURE",A)}}break;case"raw":break;default:Ae(g)}if(e.raw)for(const g in e.raw){const m=e.raw[g]??e.raw[g.toLowerCase()];if(!(g==="vendor"||m==null||c.includes(g))){if(typeof m=="string")l(g,m);else if(Array.isArray(m)&&m.every(y=>typeof y=="string"))for(const y of m)l(g,y)}}const u=new Uint8Array(4);q(u).setUint32(0,c.length,!0),i.splice(2,0,u);const d=i.reduce((g,m)=>g+m.length,0),f=new Uint8Array(d);let h=0;for(const g of i)f.set(g,h),h+=g.length;return f},ua=[2,1,2,3,3,4,4,5],Vc=r=>{if(r.length<7||r[0]!==11||r[1]!==119)return null;const e=new H(r);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const i=e.readBits(6),n=e.readBits(5);if(n>8)return null;const s=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(i/2);return{fscod:t,bsid:n,bsmod:s,acmod:a,lfeon:o,bitRateCode:c}},ud=[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],dd=1536,Ui=new Uint8Array([5,4,65,67,45,51]),Ni=new Uint8Array([5,4,69,65,67,51]),Wc=[1,2,3,6],Lc=r=>{if(r.length<6||r[0]!==11||r[1]!==119)return null;const e=new H(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=Wc[a];let d;return n<3?d=Sn[n]/1e3:d=Bc[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}]}},fd=r=>{if(r.length<2)return null;const e=new H(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}},qc=r=>{const e=r.substreams[0];return p(e),e.fscod<3?Sn[e.fscod]:e.fscod2!==null&&e.fscod2<3?Bc[e.fscod2]:null},Hc=r=>{const e=r.substreams[0];p(e);let t=ua[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},hd=1683496997,Gi=18,Cs=10,md=4096,Xa=32,da=20,pd=8,gd=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],wd=[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],yd=[16,16,20,20,0,24,24,0],an=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],bd=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],kd=8,Td=44646,Sd=[32e3,44100,48e3,0],Ad=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],jc=[512,1024,2048,4096],fa=r=>{const e=Qc(r),t=q(r);let i=e?Math.ceil(e.frameSize/4)*4:0,n=null;for(;i+4<=r.length&&t.getUint32(i)===hd;){const a=$i(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.sampleC
1ount,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}},Kc=r=>{const e=fa(r);return e?.core?e.hasExtensions?"dtsh":"dtsc":null},Qc=r=>{if(r.length<Gi||r[0]!==127||r[1]!==254||r[2]!==128||r[3]!==1)return null;const e=new H(r);if(e.skipBits(32),e.skipBits(1),e.readBits(5)!==Xa-1)return null;const t=e.readBits(1),i=e.readBits(7)+1;if(i%pd!==0)return null;const n=e.readBits(14)+1;if(n<96)return null;const s=e.readBits(6);if(s>=an.length)return null;const a=gd[e.readBits(4)];if(a===0)return null;const o=wd[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=yd[e.readBits(3)];if(l===0)return null;const u=c!==0;return{frameSize:n,sampleRate:a,numberOfChannels:an[s]+(u?1:0),sampleCount:i*Xa,channelLayout:bd[s]|(u?kd:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},$i=r=>{if(r.length<Cs||r[0]!==100||r[1]!==88||r[2]!==32||r[3]!==37)return null;const e=new H(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=Sd[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*ys(y));if(e.readBits(1)){e.skipBits(2);const y=e.readBits(2)+1<<2,b=e.readBits(2)+1;e.skipBits(b*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,g=Ad[e.readBits(4)],m=e.readBits(8)+1;let w=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;w=e.readBits(y)}return c===0||e.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:g,numberOfChannels:m,sampleCount:Math.round(l*g/c),channelLayout:w,pcmResolution:h}}},xd=r=>{if(r.length<da)return null;const e=q(r),t=e.getUint32(0);if(t===0)return null;const i=new H(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=Cd(o):a<an.length&&(c=an[a]+s),{sampleRate:t,maxBitrate:e.getUint32(4),avgBitrate:e.getUint32(8),pcmSampleDepth:r[12],sampleCount:jc[n],channelLayout:o,numberOfChannels:c}},Pd=r=>{const e=new Uint8Array(da),t=q(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 H(e);return n.seekToByte(13),n.writeBits(2,Math.max(jc.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},Cd=r=>ys(r)+ys(r&Td);const we=["avc","hevc","vp9","av1","vp8","prores"],ke=["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"],Lt=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],xe=[...Lt,...ke],mt=["webvtt"],on=[{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}],Ya=[{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}],qt=[{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}],Za=[{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}],Ja=".01.01.01.01.00",eo=".0.110.01.01.01.0",cr=["ap4x","ap4h","apch","apcn","apcs","apco"],cn=["dtsc","dtsh","dtsl","dtse"],_d=[{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}],Gc=(r,e,t,i,n)=>{if(r==="avc"){const a=Math.ceil(e/16)*Math.ceil(t/16),o=on.find(f=>a<=f.maxMacroblocks&&i<=f.maxBitrate)??ue(on),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=Ya.find(d=>c<=d.maxPictureSize&&i<=d.maxBitrate)??ue(Ya);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.${(qt.find(l=>a<=l.maxPictureSize&&i<=l.maxBitrate)??ue(qt)).level.toString().padStart(2,"0")}.08`}else if(r==="av1"){const a=e*t,o=Za.find(u=>a<=u.maxPictureSize&&i<=u.maxBitrate)??ue(Za);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=_d.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 Ae(r)}throw new TypeError(`Unhandled codec '${String(r)}'.`)},Id=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]},$c=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,g=e[5]?Number(e[5][0]):1,m=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,y=(l<<7)+(d<<6)+(f<<5)+(h<<4)+(g<<3)+(m<<2)+w;return[n,c,y,0]},ha=r=>{const{codec:e,codecDescription:t,colorSpace:i,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:c}=r;if(e==="avc"){if(p(r.avcType!==null),n){const l=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${r.avcType}.${mi(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}.${mi(t.subarray(1,4))}`}else if(e==="hevc"){let l,u,d,f,h,g;if(s)l=s.generalProfileSpace,u=s.generalProfileIdc,d=Ua(s.generalProfileCompatibilityFlags),f=s.generalTierFlag,h=s.generalLevelIdc,g=[...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 w=q(t),y=w.getUint8(1);l=y>>6&3,u=y&31,d=Ua(w.getUint32(2)),f=y>>5&1,h=w.getUint8(12),g=[];for(let b=0;b<6;b++)g.push(w.getUint8(6+b))}let m="hev1.";for(m+=["","A","B","C"][l]+u,m+=".",m+=d.toString(16).toUpperCase(),m+=".",m+=f===0?"L":"H",m+=h;g.length>0&&g[g.length-1]===0;)g.pop();return g.length>0&&(m+=".",m+=g.map(w=>w.toString(16).toUpperCase()).join(".")),m}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const b=r.width*r.height;let k=ue(qt).level;for(const S of qt)if(b<=S.maxPictureSize){k=S.level;break}return`vp09.00.${k.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"),g=a.transferCharacteristics.toString().padStart(2,"0"),m=a.matrixCoefficients.toString().padStart(2,"0"),w=a.videoFullRangeFlag.toString().padStart(2,"0");let y=`vp09.${l}.${u}.${d}.${f}`;return y+=`.${h}.${g}.${m}.${w}`,y.endsWith(Ja)&&(y=y.slice(0,-Ja.length)),y}else if(e==="av1"){if(!o){const S=r.width*r.height;let T=ue(qt).level;for(const A of qt)if(S<=A.maxPictureSize){T=A.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",g=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),m=i?.primaries?fr[i.primaries]:1,w=i?.transfer?hr[i.transfer]:1,y=i?.matrix?mr[i.matrix]:1,b=i?.fullRange?1:0;let k=`av01.${l}.${u}${d}.${f}`;return k+=`.${h}.${g.toString().padStart(3,"0")}`,k+=`.${m.toString().padStart(2,"0")}`,k+=`.${w.toString().padStart(2,"0")}`,k+=`.${y.toString().padStart(2,"0")}`,k+=`.${b}`,k.endsWith(eo)&&(k=k.slice(0,-eo.length)),k}else{if(e==="prores")return c??"apch";e!==null&&Ae(e)}}throw new TypeError(`Unhandled codec '${e}'.`)},Xc=r=>{switch(r.codec){case"avc":{let e=r.avcCodecInfo?.sequenceParameterSets[0];if(!e&&r.codecDescription&&(e=oa(r.codecDescription)?.sequenceParameterSets[0]),e){const t=bi(e);if(t)return{primaries:St[t.colourPrimaries],transfer:At[t.transferCharacteristics],matrix:xt[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"hevc":{let e=r.hevcCodecInfo?.arrays.find(t=>t.nalUnitType===ae.SPS_NUT)?.nalUnits[0];if(!e&&r.codecDescription&&(e=Dc(r.codecDescription)?.arrays.find(t=>t.nalUnitType===ae.SPS_NUT)?.nalUnits[0]),e){const t=ca(e);if(t)return{primaries:St[t.colourPrimaries],transfer:At[t.transferCharacteristics],matrix:xt[t.matrixCoefficients],fullRange:!!t.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(r.vp9CodecInfo)return{primaries:St[r.vp9CodecInfo.colourPrimaries],transfer:At[r.vp9CodecInfo.transferCharacteristics],matrix:xt[r.vp9CodecInfo.matrixCoefficients],fullRange:!!r.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(r.av1CodecInfo)return{primaries:St[r.av1CodecInfo.colourPrimaries],transfer:At[r.av1CodecInfo.transferCharacteristics],matrix:xt[r.av1CodecInfo.matrixCoefficients],fullRange:!!r.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(r.proresCodecInfo)return{primaries:St[r.proresCodecInfo.colourPrimaries],transfer:At[r.proresCodecInfo.transferCharacteristics],matrix:xt[r.proresCodecInfo.matrixCoefficients],fullRange:r.proresCodecInfo.fullRange};break}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Yc=(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(ke.includes(r))return r;throw new TypeError(`Unhandled codec '${r}'.`)},ma=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=Bi(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&&ke.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},Ed=r=>{},vd=r=>{switch(r.codec){case"flac":{const e=rn("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");
1return r.sampleRate>=1<<20||r.numberOfChannels>8?!1:(e[18]=r.sampleRate>>>12,e[19]=r.sampleRate>>>4,e[20]=(r.sampleRate&15)<<4|r.numberOfChannels-1<<1,e)}case"vorbis":{const e=rn("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54mia
1aqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),t=q(e);return t.setUint8(15,r.numberOfChannels),t.setUint32(16,r.sampleRate,!0),e}default:return}},qr=48e3,Zc=/^pcm-([usf])(\d+)(be)?$/,rt=r=>{if(p(ke.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=Zc.exec(r);p(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}},tt=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":cr.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":cn.includes(r)?"dts":r==="ulaw"?"ulaw":r==="alaw"?"alaw":Zc.test(r)?r:r==="webvtt"?"webvtt":null,Bd=r=>r==="avc"?{avc:{format:"avc"}}:r==="hevc"?{hevc:{format:"hevc"}}:{},Fd=r=>r==="aac"?{aac:{format:"aac"}}:r==="opus"?{opus:{format:"opus"}}:{},Rd=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...cr],Md=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Dd=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,zd=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Od=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,Fi=(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(!Rd.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&&!Nr(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(fr);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(hr);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(mr);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(", ")}.`);
vendor: 5,060 bytes, line 1
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(!Md.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(!Dd.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(!zd.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(!Od.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(cr.some(t=>r.decoderConfig.codec.startsWith(t))&&!cr.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: ${cr.join(", ")}.`);if(e!==null&&tt(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}'.`)},Ud=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],it=(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(!Ud.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&&!Nr(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(!cn.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: ${cn.join(", ")}.`)}else if((r.decoderConfig.codec.startsWith("pcm")||r.decoderConfig.codec.startsWith("ulaw")||r.decoderConfig.codec.startsWith("alaw"))&&!ke.includes(r.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${ke.join(", ")}).`);if(e!==null&&tt(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}'.`)},Jc=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 lr=4,el=[44100,48e3,32e3],_s=[-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],In=1483304551,pa=1231971951,Is=(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,Nd=(r,e,t,i)=>e===0?0:e===1?144*t/(i<<r):e===2?144*t/i:12*t/i*4,En=(r,e)=>r===3?e===3?21:36:e===3?13:21,ki=(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,g=s>>4&3,m=s>>3&1,w=s>>2&1,y=s&3,b=_s[a*16*4+l*16+u];if(b===-1)return{header:null,bytesAdvanced:1};const k=b*1e3,S=el[d]>>a+o,T=Is(a,l,k,S,f);if(e!==null&&e<T)return{header:null,bytesAdvanced:1};let A;return c===3?A=l===3?384:1152:l===3?A=384:l===2?A=1152:A=576,{header:{totalSize:T,mpegVersionId:c,lowSamplingFrequency:a,layer:l,bitrate:k,frequencyIndex:d,sampleRate:S,channel:h,modeExtension:g,copyright:m,original:w,emphasis:y,audioSamplesInFrame:A},bytesAdvanced:1}},Vd=r=>{let e=127,t=0,i=r;for(;(e^2147483647)!==0;)t=i&~e,t<<=1,t|=i&e,e=(e+1<<8)-1,i=t;return t},Es=r=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=r&e,e>>=8;return t};var ur;(function(r){r[r.FrameCount=1]="FrameCount",r[r.FileSize=2]="FileSize",r[r.Toc=4]="Toc"})(ur||(ur={}));const Ti=r=>r===3?1:2;class Rt{constructor(e){this.input=e}dispose(){}}const Qe=new Uint8Array(0);class te{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===Qe&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");
vendor: 1,418 bytes, line 1
1if(t!=="key"&&t!=="delta")throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(n)||n<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(s))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if(o?.alpha!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(o?.alphaByteLength!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Qe}get microsecondTimestamp(){return Math.trunc(Wt*this.timestamp)}get microsecondDuration(){return Math.trunc(Wt*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");
1return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if(typeof EncodedAudioChunk>"u")throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new te(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 te(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 tl=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},rl=r=>{const e=q(r);let t=0;const i=e.getUint8(t);t+=1,t+=3;const n=mi(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(mi(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)}},il=(r,e)=>r.systemId===e.systemId&&Pc(r.data,e.data);const Pt=8,ir=16,Nt=r=>{let e=R(r);const t=fe(r,4);let i=8;e===1&&(e=We(r),i=16);const s=e-i;return s<0?null:{name:t,totalSize:e,headerSize:i,contentSize:s}},Yt=r=>sr(r)/65536,jn=r=>sr(r)/1073741824,Kn=r=>{let e=0;for(let t=0;t<4;t++){e<<=7;const i=U(r);if(e|=i&127,(i&128)===0)break}return e},at=r=>{let e=ge(r);return r.skip(2),e=Math.min(e,r.remainingLength),Ue.decode(N(r,e))},Wd=r=>{const e=Nt(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 Ue.decode(i);case 2:return new ci("utf-16be").decode(i);case 13:return new Br(i,"image/jpeg");case 14:return new Br(i,"image/png");case 27:return new Br(i,"image/bmp");default:return i}};const ut=16,wt=new Uint32Array(256),Sr=new Uint32Array(256),Ar=new Uint32Array(256),xr=new Uint32Array(256),Pr=new Uint32Array(256),ve=new Uint32Array(256),nl=new Uint32Array(10);let sl=!1;const Ld=()=>{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);wt[s]=a<<24|a<<16|a<<8|a,ve[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;Sr[s]=f,Ar[s]=f>>>8|f<<24,xr[s]=f>>>16|f<<16,Pr[s]=f>>>24|f<<8}let n=1;for(let s=0;s<10;s++)nl[s]=n<<24,n=n<<1^(n&128?283:0);sl=!0};class al{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(ut/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(ut),this.out=new Uint8Array(ut),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){p(e.byteLength===16),p(t.byteLength===16),sl||Ld();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]^wt[a>>>16&255]&4278190080^wt[a>>>8&255]&16711680^wt[a>>>0&255]&65280^wt[a>>>
124&255]&255^nl[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]=Sr[wt[o>>>24&255]&255]^Ar[wt[o>>>16&255]&255]^xr[wt[o>>>8&255]&255]^Pr[wt[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 b=y*4;l=Sr[e>>>24]^Ar[n>>>16&255]^xr[i>>>8&255]^Pr[t&255]^this.roundkey[b],u=Sr[t>>>24]^Ar[e>>>16&255]^xr[n>>>8&255]^Pr[i&255]^this.roundkey[b+1],d=Sr[i>>>24]^Ar[t>>>16&255]^xr[e>>>8&255]^Pr[n&255]^this.roundkey[b+2],f=Sr[n>>>24]^Ar[i>>>16&255]^xr[t>>>8&255]^Pr[e&255]^this.roundkey[b+3],e=l,t=u,i=d,n=f}const h=ve[e>>>24&255]&4278190080^ve[n>>>16&255]&16711680^ve[i>>>8&255]&65280^ve[t>>>0&255]&255^this.roundkey[40],g=ve[t>>>24&255]&4278190080^ve[e>>>16&255]&16711680^ve[n>>>8&255]&65280^ve[i>>>0&255]&255^this.roundkey[41],m=ve[i>>>24&255]&4278190080^ve[t>>>16&255]&16711680^ve[e>>>8&255]&65280^ve[n>>>0&255]&255^this.roundkey[42],w=ve[n>>>24&255]&4278190080^ve[i>>>16&255]&16711680^ve[t>>>8&255]&65280^ve[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,g^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,w^this.iv[3],!1),this.iv[0]=s,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const qd=(r,e,t)=>{let i=!1,n=0;const s=2**16,a=16,o=new al;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(v(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),g=new Uint8Array(f);for(let m=0;m<f;m+=16)o.in.set(h.subarray(m,m+16)),o.decrypt(),g.set(o.out,m);if(f<d)c.enqueue(g),n+=f;else{const m=g[f-1];if(m===0||m>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const w=g.subarray(0,f-m);c.enqueue(w),c.close(),t()}},cancel:()=>{t()}})};class ga extends Rt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.movieMatrix=hi,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],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 tl({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,Pt,ir);if(v(n)&&(n=await n),!n)break;const s=e,a=Nt(n);if(!a)break;if(a.name==="ftyp"||a.name==="styp"){const o=fe(n,4);this.isQuickTime=o==="qt  "}else if(a.name==="moov"){let o=this.reader.requestSlice(n.filePos,a.contentSize);if(v(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;
1 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){p(this.reader.fileSize!==null);let n=this.reader.requestSlice(this.reader.fileSize-4,4);v(n)&&(n=await n),p(n);const s=R(n),a=this.reader.fileSize-s;if(a>=0&&a<=this.reader.fileSize-ir){let o=this.reader.requestSliceRange(a,Pt,ir);if(v(o)&&(o=await o),o){const c=Nt(o);if(c&&c.name==="mfra"){let l=this.reader.requestSlice(o.filePos,c.contentSize);v(l)&&(l=await l),l&&this.readContiguousBoxes(l)}}}}})()}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==ga)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.movieMatrix=t.movieMatrix,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,matrix:i.matrix,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,maxBitrate:i.maxBitrate,avgBitrate:i.avgBitrate,info:i.info};if(i.trackBacking){if(p(n.info),n.info.type==="video"&&n.info.width!==-1){const s=n;n.trackBacking=new to(s),this.tracks.push(n)}else if(n.info.type==="audio"&&n.info.numberOfChannels!==-1){const s=n;n.trackBacking=new ro(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;p(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&&ke.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){p(e.info?.type==="audio");const s=rt(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,g=h+l.samplesPerChunk,m=X(t.sampleTimingEntries,h,C=>C.startIndex),w=t.sampleTimingEntries[m],y=X(t.sampleTimingEntries,g,C=>C.startIndex),b=t.sampleTimingEntries[y],k=w.startDecodeTimestamp+(h-w.startIndex)*w.delta,T=b.startDecodeTimestamp+(g-b.startIndex)*b.delta-k,A=ue(a);A&&A.delta===T?A.count++:a.push({startIndex:l.startChunkIndex+f,startDecodeTimestamp:k,count:1,delta:T});const P=l.samplesPerChunk*s.sampleSize*e.info.numberOfChannels;o.push(P)}l.startSampleIndex=l.startChunkIndex,l.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=o}if(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,Pt,ir);v(t)&&(t=await t),p(t);const i=Nt(t);p(i?.name==="moof");let n=this.reader.requestSlice(e,i.totalSize);v(n)&&(n=await n),p(n),this.traverseBox(n);const s=this.lastReadFragment;
1p(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=>d.moofOffset===s.moofOffset);if(u)Qn(a,u.timestamp);else{const d=X(c,s.moofOffset-1,f=>f.moofOffset);if(d!==-1){const f=c[d];Qn(a,f.endTimestamp)}}a.startTimestampIsFinal=!0}const l=X(c,a.startTimestamp,u=>u.startTimestamp);if((l===-1||c[l].moofOffset!==s.moofOffset)&&c.splice(l+1,0,{moofOffset:s.moofOffset,startTimestamp:a.startTimestamp,endTimestamp:a.endTimestamp}),a.encryptionAuxInfo&&o.encryptionInfo){const u=await cl(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-Pt&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-Pt;){const i=e.filePos,n=Nt(e);if(!n)break;yield{boxInfo:n,slice:e},e.filePos=i+n.totalSize}}traverseBox(e){const t=e.filePos,i=Nt(e);if(!i)return!1;const n=e.filePos,s=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mvhd":{const a=U(e);e.skip(3),a===1?(e.skip(16),this.movieTimescale=R(e),this.movieDurationInTimescale=We(e)):(e.skip(8),this.movieTimescale=R(e),this.movieDurationInTimescale=R(e)),e.skip(16),this.movieMatrix=io(e)}break;case"trak":{const a={id:-1,demuxer:this,trackBacking:null,disposition:{...Ft,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,matrix:hi,internalCodecId:null,name:null,languageCode:Ie,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null,maxBitrate:null,avgBitrate: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 to(o),this.tracks.push(a)}else if(a.info.type==="audio"&&a.info.numberOfChannels!==-1){const o=a;a.trackBacking=new ro(o),this.tracks.push(a)}}this.currentTrack=null}break;case"tkhd":{const a=this.currentTrack;if(!a)break;const o=U(e),l=!!(bt(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=We(e);else throw new Error(`Incorrect track header version ${o}.`);e.skip(16);const u=io(e);a.matrix=Mr(u,this.movieMatrix)}break;case"elst":{const a=this.currentTrack;if(!a)break;const o=U(e);e.skip(3);let c=!1,l=0;const u=R(e);for(let d=0;d<u;d++){const f=o===1?We(e):R(e),h=o===1?zh(e):sr(e),g=Yt(e);if(c){O._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(h===-1){l+=f;continue}if(g!==1){O._warn("Unsupported edit list entry: media rate must be 1.");break}a.editListPreviousSegmentDurations=l,a.editListOffset=h,c=!0}}break;case"mdhd":{const a=this.currentTrack;if(!a)break;const o=U(e);e.skip(3),o===0?(e.skip(8),a.timescale=R(e),a.durationInMediaTimescale=R(e)):o===1&&(e.skip(16),a.timescale=R(e),a.durationInMediaTimescale=We(e));let c=ge(e);if(c>0){a.languageCode="";for(let l=0;l<3;l++)a.languageCode=String.fromCharCode(96+(c&31))+a.languageCode,c>>=5;gi(a.languageCode)||(a.languageCode=Ie)}}break;case"hdlr":{const a=this.currentTrack;if(!a)break;e.skip(8);const o=fe(e,4);o==="vide"?a.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...Ac},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:o==="soun"&&(a.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(n,i.contentSize))}break;case"stsd":{const a=this.currentTrack;if(!a||a.info===null||a.sampleTable)break;const o=U(e);e.skip(3);const c=R(e);for(let l=0;l<c;l++){const u=e.filePos,d=Nt(e);if(!d)break;a.internalCodecId=d.name;const f=d.name.toLowerCase();if(a.info.type==="video"){e.skip(24),a.info.width=ge(e),a.info.height=ge(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":cr.includes(f)?(a.info.codec="prores",a.info.proresFormat=f):h===null?O._warn("Unknown encrypted video codec due to missing frma box."):O._warn(`Unsupported video codec (sample entry type '${d.name}').`)}else{e.skip(8);const h=ge(e);e.skip(6);let g=ge(e),m=ge(e);e.skip(4);let w=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),w=su(e),g=R(e),e.skip(4),m=R(e),y=R(e),e.skip(8))),a.info.numberOfChannels=g,a.info.sampleRate=w,a.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,u+d.totalSize-e.filePos));const b=f==="enca"?a.frmaCodecString:f;if(a.frmaCodecString=null,b!=="mp4a")if(b==="opus")a.info.codec="opus",a.info.sampleRate=qr;else if(b==="flac")a.info.codec="flac";else if(b==="ulaw")a.info.codec="ulaw";else if(b==="alaw")a.info.codec="alaw";else if(b==="ac-3")a.info.codec="ac3";else if(b==="ec-3")a.info.codec="eac3";else if(cn.includes(b))a.info.codec="dts",a.info.dtsFormat=b;else if(b==="twos")m===8?a.info.codec="pcm-s8":m===16?a.info.codec=a.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(O._warn(`Unsupported sample size ${m}
1 for codec 'twos'.`),a.info.codec=null);else if(b==="sowt")m===8?a.info.codec="pcm-s8":m===16?a.info.codec="pcm-s16":(O._warn(`Unsupported sample size ${m} for codec 'sowt'.`),a.info.codec=null);else if(b==="raw ")a.info.codec="pcm-u8";else if(b==="in24")a.info.codec=a.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if(b==="in32")a.info.codec=a.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if(b==="fl32")a.info.codec=a.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if(b==="fl64")a.info.codec=a.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if(b==="ipcm"){const k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===16?a.info.codec="pcm-s16":k===24?a.info.codec="pcm-s24":k===32?a.info.codec="pcm-s32":(O._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null):k===16?a.info.codec="pcm-s16be":k===24?a.info.codec="pcm-s24be":k===32?a.info.codec="pcm-s32be":(O._warn(`Invalid ipcm sample size ${k}.`),a.info.codec=null)}else if(b==="fpcm"){const k=a.info.pcmSampleSize;a.info.pcmLittleEndian?k===32?a.info.codec="pcm-f32":k===64?a.info.codec="pcm-f64":(O._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null):k===32?a.info.codec="pcm-f32be":k===64?a.info.codec="pcm-f64be":(O._warn(`Invalid fpcm sample size ${k}.`),a.info.codec=null)}else if(b==="lpcm"&&y!==null){const k=m+7>>3,S=!!(y&1),T=!!(y&2),A=y&4?-1:0;m>0&&m<=64&&(S?m===32&&(a.info.codec=T?"pcm-f32be":"pcm-f32"):A&1<<k-1?k===1?a.info.codec="pcm-s8":k===2?a.info.codec=T?"pcm-s16be":"pcm-s16":k===3?a.info.codec=T?"pcm-s24be":"pcm-s24":k===4&&(a.info.codec=T?"pcm-s32be":"pcm-s32"):k===1&&(a.info.codec="pcm-u8")),a.info.codec===null&&O._warn("Unsupported PCM format.")}else b===null?O._warn("Unknown encrypted audio codec due to missing frma box."):O._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=fe(e,4).toLowerCase();a.frmaCodecString=c}break;case"schm":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=fe(e,4);o==="cenc"||o==="cens"||o==="cbcs"?a.encryptionInfo={scheme:o,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:O._warn(`Unsupported encryption scheme '${o}'.`)}break;case"tenc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=U(e);e.skip(3),e.skip(1);const c=U(e);if(o>0?(a.encryptionInfo.defaultCryptByteBlock=c>>4,a.encryptionInfo.defaultSkipByteBlock=c&15):(a.encryptionInfo.defaultCryptByteBlock=0,a.encryptionInfo.defaultSkipByteBlock=0),a.encryptionInfo.defaultIsProtected=U(e)!==0,a.encryptionInfo.defaultPerSampleIvSize=U(e),a.encryptionInfo.defaultKid=mi(N(e,16)),a.encryptionInfo.defaultIsProtected&&a.encryptionInfo.defaultPerSampleIvSize===0){const l=U(e),u=new Uint8Array(16);u.set(N(e,l),0),a.encryptionInfo.defaultConstantIv=u}}break;case"avcC":{const a=this.currentTrack;if(!a||(p(a.info),i.contentSize===0))break;a.info.codecDescription=N(e,i.contentSize)}break;case"hvcC":{const a=this.currentTrack;if(!a||(p(a.info),i.contentSize===0))break;a.info.codecDescription=N(e,i.contentSize)}break;case"vpcC":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="video"),e.skip(4);const o=U(e),c=U(e),l=U(e),u=l>>4,d=l>>1&7,f=l&1,h=U(e),g=U(e),m=U(e);a.info.vp9CodecInfo={profile:o,level:c,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:f,colourPrimaries:h,transferCharacteristics:g,matrixCoefficients:m}}break;case"av1C":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="video"),e.skip(1);const o=U(e),c=o>>5,l=o&31,u=U(e),d=u>>7,f=u>>6&1,h=u>>5&1,g=u>>4&1,m=u>>3&1,w=u>>2&1,y=u&3,b=c===2&&f?h?12:10:f?10:8;e.skip(1);const k=N(e,i.contentSize-4),S=la(k);a.info.av1CodecInfo={profile:c,level:l,tier:d,bitDepth:b,monochrome:g,chromaSubsamplingX:m,chromaSubsamplingY:w,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;p(a.info?.type==="video");const o=fe(e,4);
1if(o!=="nclx"&&o!=="nclc")break;const c=ge(e),l=ge(e),u=ge(e);let d;o==="nclx"&&(d=!!(U(e)&128)),a.info.colorSpace={primaries:St[c],transfer:At[l],matrix:xt[u],fullRange:d}}break;case"pasp":{const a=this.currentTrack;if(!a)break;p(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"btrt":{const a=this.currentTrack;if(!a)break;e.skip(4);const o=R(e),c=R(e);a.maxBitrate=o>0?o:null,a.avgBitrate=c>0?c:null}break;case"wave":this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"esds":{const a=this.currentTrack;if(!a||a.info?.type!=="audio")break;e.skip(4);const o=U(e);p(o===3),Kn(e),e.skip(2);const c=U(e),l=(c&128)!==0,u=(c&64)!==0,d=(c&32)!==0;if(l&&e.skip(2),u){const w=U(e);e.skip(w)}d&&e.skip(2);const f=U(e);p(f===4);const h=Kn(e),g=e.filePos,m=U(e);if(m===64||m===103?(a.info.codec="aac",a.info.aacCodecInfo={isMpeg2:m===103,objectType:null}):m===105||m===107?a.info.codec="mp3":m===221?a.info.codec="vorbis":m===169?a.info.codec="dts":O._warn(`Unsupported audio codec (objectTypeIndication ${m}) - discarding track.`),e.skip(12),h>e.filePos-g){const w=U(e);p(w===5);const y=Kn(e);if(a.info.codecDescription=N(e,y),a.info.codec==="aac"){const b=Bi(a.info.codecDescription);b.outputNumberOfChannels!==null&&(a.info.numberOfChannels=b.outputNumberOfChannels),b.outputSampleRate!==null&&(a.info.sampleRate=b.outputSampleRate)}}}break;case"enda":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),a.info.pcmLittleEndian=!!(ge(e)&255)}break;case"pcmC":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(4);const o=U(e);a.info.pcmLittleEndian=!!(o&1),a.info.pcmSampleSize=U(e)}break;case"dOps":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio"),e.skip(1);const o=U(e),c=ge(e),l=R(e),u=Ks(e),d=U(e);let f;d!==0?f=N(e,2+o):f=new Uint8Array(0);const h=new Uint8Array(19+f.byteLength),g=new DataView(h.buffer);g.setUint32(0,1332770163,!1),g.setUint32(4,1214603620,!1),g.setUint8(8,1),g.setUint8(9,o),g.setUint16(10,c,!0),g.setUint32(12,l,!0),g.setInt16(16,u,!0),g.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;p(a.info?.type==="audio"),e.skip(4);const o=127,c=128,l=e.filePos;for(;e.filePos<s;){const g=U(e),m=bt(e);if((g&o)===It.STREAMINFO){e.skip(10);const y=R(e),b=y>>>12,k=(y>>9&7)+1;a.info.sampleRate=b,a.info.numberOfChannels=k,e.skip(20)}else e.skip(m);if(g&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;p(a.info?.type==="audio");const o=N(e,3),c=new H(o),l=c.readBits(2);c.skipBits(8);const u=c.readBits(3),d=c.readBits(1);l<3&&(a.info.sampleRate=Sn[l]),a.info.numberOfChannels=ua[u]+d}break;case"dec3":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio");const o=N(e,i.contentSize),c=fd(o);if(!c){O._warn("Invalid dec3 box contents, ignoring.");break}const l=qc(c);l!==null&&(a.info.sampleRate=l),a.info.numberOfChannels=Hc(c)}break;case"ddts":{const a=this.currentTrack;if(!a)break;p(a.info?.type==="audio");const o=N(e,Math.min(i.contentSize,da)),c=xd(o);if(!c){O._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=sr(e);a.sampleTable.sampleCompositionTimeOffsets.push({startIndex:c,count:u,offset:d}),c+=u}}break;case"stsz":{const a=this.currentTrack;if(!a||!a.sampleTable)break;e.skip(4);const o=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=U(e),c=R(e),l=N(e,Math.ceil(c*o/8)),u=new H(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=We(e);a.sampleTable.chunkOffsets.push(l)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,i.contentSize));break;case"mehd":{const a=U(e);e.skip(3);const o=a===1?We(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=U(e);e.skip(3);const o=R(e),c=this.tracks.find(b=>b.id===o);if(!c)break;const l=R(e),u=(l&48)>>4,d=(l&12)>>2,f=l&3,h=[U,ge,bt,R],g=h[u],m=h[d],w=h[f],y=R(e);for(let b=0;b<y;b++){const k=a===1?We(e):R(e),S=a===1?We(e):R(e);
1g(e),m(e),w(e),c.fragmentLookupTable.push({timestamp:k,moofOffset:S})}c.fragmentLookupTable.sort((b,k)=>b.timestamp-k.timestamp);for(let b=0;b<c.fragmentLookupTable.length-1;b++){const k=c.fragmentLookupTable[b],S=c.fragmentLookupTable[b+1];k.timestamp===S.timestamp&&(c.fragmentLookupTable.splice(b+1,1),b--)}}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(p(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 g=a.presentationTimestamps[u+1].presentationTimestamp-d.presentationTimestamp;f.duration=g}}const o=a.samples[a.presentationTimestamps[0].sampleIndex],c=a.samples[ue(a.presentationTimestamps).sampleIndex];a.startTimestamp=o.presentationTimestamp,a.endTimestamp=c.presentationTimestamp+c.duration;const{currentFragmentState:l}=this.currentTrack;p(l),l.startTimestamp!==null&&(Qn(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=rl(N(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(a):this.currentTrack||this.psshBoxes.push(a)}break;case"tfhd":{p(this.currentFragment),e.skip(1);const a=bt(e),o=!!(a&1),c=!!(a&2),l=!!(a&8),u=!!(a&16),d=!!(a&32),f=!!(a&65536),h=!!(a&131072),g=R(e),m=this.tracks.find(y=>y.id===g);if(!m)break;const w=this.fragmentTrackDefaults.find(y=>y.trackId===g);this.currentTrack=m,m.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:w?.defaultSampleDescriptionIndex??null,defaultSampleDuration:w?.defaultSampleDuration??null,defaultSampleSize:w?.defaultSampleSize??null,defaultSampleFlags:w?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},o?m.currentFragmentState.baseDataOffset=We(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;p(a.currentFragmentState);const o=U(e);e.skip(3);const c=o===0?R(e):We(e);a.currentFragmentState.startTimestamp=c}break;case"trun":{const a=this.currentTrack;if(!a)break;p(this.currentFragment),p(a.currentFragmentState);const o=U(e),c=bt(e),l=!!(c&1),u=!!(c&4),d=!!(c&256),f=!!(c&512),h=!!(c&1024),g=!!(c&2048),m=R(e);let w=null;l&&(w=sr(e));let y=null;u&&(y=R(e));let b;this.currentFragment.trackData.has(a.id)?(b=this.currentFragment.trackData.get(a.id),w!==null&&(b.currentOffset=a.currentFragmentState.baseDataOffset+w)):(b={track:a,currentTimestamp:0,currentOffset:a.currentFragmentState.baseDataOffset+(w??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(a.id,b));for(let k=0;k<m;k++){let S;d?S=R(e):(p(a.currentFragmentState.defaultSampleDuration!==null),S=a.currentFragmentState.defaultSampleDuration);let T;f?T=R(e):(p(a.currentFragmentState.defaultSampleSize!==null),T=a.currentFragmentState.defaultSampleSize);let A;h?A=R(e):(p(a.currentFragmentState.defaultSampleFlags!==null),A=a.currentFragmentState.defaultSampleFlags),k===0&&y!==null&&(A=y);let P=0;g&&(o===0?P=R(e):P=sr(e));const C=!(A&65536);b.samples.push({presentationTimestamp:b.currentTimestamp+P,duration:S,byteOffset:b.currentOffset,byteSize:T,isKeyFrame:C,encryption:null}),b.currentOffset+=T,b.currentTimestamp+=S}this.currentFragment.implicitBaseDataOffset=b.currentOffset}break;case"saiz":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;if(e.skip(1),bt(e)&1){const f=fe(e,4),h=R(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const c=U(e),l=R(e);let u=null;c===0&&l>0&&(u=N(e,l));const d=so(a);d.defaultSampleInfoSize=c,d.sampleSizes=u,d.sampleCount=l}break;case"saio":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;const o=U(e);if(bt(e)&1){const f=fe(e,4),h=R(e);if(f!==a.encryptionInfo.scheme||h!==0)break}const l=R(e);if(l===0)break;l>1&&O._warn("Multiple saio entries are not supported; using the first offset only.");let u=o===0?R(e):Number(We(e));this.currentFragment&&(u+=this.currentFragment.moofOffset);const d=so(a);d.offset=u}break;case"senc":{const a=this.currentTrack;if(!a||!a.encryptionInfo)break;p(this.currentFragment);const o=this.currentFragment.trackData.get(a.id);if(!o)break;e.skip(1);const l=!!(bt(e)&2),u=R(e),d=a.encryptionInfo.defaultPerSampleIvSize;p(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 g=null;if(l){const w=ge(e);g=[];for(let y=0;y<w;y++){const b=ge(e),k=R(e);g.push({clearLen:b,protectedLen:k})}}const m=o.samples[f];m.encryption={iv:h,subsamples:g}}}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]??=at(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=Ue.decode(N(c,o.contentSize)):this.metadataTags.title??=at(c);break;case"©des":this.currentTrack||(this.metadataTags.description??=at(c));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=at(c));break;case"©alb":this.currentTrack||(this.metadataTags.album??=at(c));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=at(c));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=at(c));break;case"©day":if(!this.currentTrack){const l=new Date(at(c));Number.isNaN(l.getTime())||(this.metadataTags.date??=l)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=at(c));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=at(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=Ue.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=Wd(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"tmpo":if(d instanceof Uint8Array&&d.length>=2){const f=q(d).getInt16(0,!1);f>0&&(this.metadataTags.beatsPerMinute??=f)}break;case"covr":case"com.apple.quicktime.artwork":d instanceof Br?(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),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),g&&Number.isInteger(g)&&g>0&&(this.metadataTags.tracksTotal??=g)}break;case"trkn":if(d instanceof Uint8Array&&d.length>=6){const f=q(d),h=f.getUint16(2,!1),g=f.getUint16(4,!1);h>0&&(this.metadataTags.trackNumber??=h),g>0&&(this.metadataTags.tracksTotal??=g)}break;case"disc":case"disk":if(d instanceof Uint8Array&&d.length>=6){const f=q(d),h=f.getUint16(2,!1),g=f.getUint16(4,!1);h>0&&(this.metadataTags.discNumber??=h),g>0&&(this.metadataTags.discsTotal??=g)}break}}}break}return e.filePos=s,!0}}class ol{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 this.internalTrack.maxBitrate}getAverageBitrate(){return this.internalTrack.avgBitrate}async getDurationFromMetadata(){const e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(p(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 pi(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=vs(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!no(n)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const l=X(c.presentationTimestamps,i,f=>f.presentationTimestamp),u=l!==-1?c.presentationTimestamps[l].sampleIndex:-1,d=l!==-1&&i<c.endTimestamp;return{sampleIndex:u,correctSampleFound:d}},i,i,t)}async getNextPacket(e,t){const i=this.packetToSampleIndex.get(e);if(i!==void 0)return this.fetchPacketForSampleIndex(i+1,t);const n=this.packetToFragmentLocation.get(e);if(n===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(n.fragment,s=>{if(s===n.fragment){const a=s.trackData.get(this.internalTrack.id);if(n.sampleIndex+1<a.samples.length)return{sampleIndex:n.sampleIndex+1,correctSampleFound:!0}}else if(s.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.mapTimestampIntoTimescale(e),n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=Hd(n,i),a=await this.fetchPacketForSampleIndex(s,t);return!no(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=wn(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=Kd(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 p(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=jd(i,e);if(!n)return null;let s;if(t.metadataOnly)s=Qe;else{let l=this.internalTrack.demuxer.reader.requestSlice(n.sampleOffset,n.sampleSize);if(v(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 cl(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<d.length&&(u=d[e])}u??=ao(this.internalTrack.encryptionInfo),u&&(s=await oo(this.internalTrack,u,s,null))}}const a=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=n.duration/this.internalTrack.timescale,c=new te(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];p(s);let a;if(i.metadataOnly)a=Qe;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(v(u)&&(u=await u),!u)return null;if(a=N(u,s.byteSize),this.internalTrack.encryptionInfo){const d=s.encryption??ao(this.internalTrack.encryptionInfo);d&&(a=await oo(this.internalTrack,d,a,e))}}const o=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=s.duration/this.internalTrack.timescale,l=ne
1w te(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:w,correctSampleFound:y}=t(e);if(y)return this.fetchPacketInFragment(e,w,s);w!==-1&&(c=e,l=w)}const u=X(this.internalTrack.fragmentLookupTable,i,w=>w.timestamp),d=u!==-1?this.internalTrack.fragmentLookupTable[u]:null,f=X(this.internalTrack.fragmentPositionCache,i,w=>w.startTimestamp),h=f!==-1?this.internalTrack.fragmentPositionCache[f]:null,g=Math.max(d?.moofOffset??0,h?.moofOffset??0)||null;let m;for(e?g===null||e.moofOffset>=g?(m=e.moofOffset+e.moofSize,o=e):m=g:m=g??0;;){if(o){const k=o.trackData.get(this.internalTrack.id);if(k&&k.startTimestamp>n)break}let w=a.reader.requestSliceRange(m,Pt,ir);if(v(w)&&(w=await w),!w)break;const y=m,b=Nt(w);if(!b)break;if(b.name==="moof"){o=await a.readFragment(y);const{sampleIndex:k,correctSampleFound:S}=t(o);if(S)return this.fetchPacketInFragment(o,k,s);k!==-1&&(c=o,l=k)}m=y+b.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const w=this.internalTrack.fragmentLookupTable[u-1];p(!w||w.timestamp<d.timestamp);const y=w?.timestamp??-1/0;return this.performFragmentedLookup(null,t,y,n,s)}return c?this.fetchPacketInFragment(c,l,s):null}}class to extends ol{constructor(e){super(e),this.decoderConfigPromise=null}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}getTransformationMatrix(){return[...this.internalTrack.matrix]}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&&xn(t.data)}else if(this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription){const t=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=t&&Pn(t.data)}else if(this.internalTrack.info.codec==="vp9"&&(!this.internalTrack.info.vp9CodecInfo||!ad(this.internalTrack.info.vp9CodecInfo))){const t=await this.getFirstPacket({}),i=t&&zc(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||!od(this.internalTrack.info.av1CodecInfo))){const t=await this.getFirstPacket({}),i=t&&la(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&&Uc(t.data)}if(!Js(this.internalTrack.info.colorSpace)){const t=Xc(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:ha(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 ro extends ol{constructor(e){super(e),this.decoderConfigPromise=null}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&&Kc(e.data)}return{codec:ma(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}const vs=(r,e)=>{if(r.presentationTimestamps){const t=X(r.presentationTimestamps,e,i=>i.presentationTimestamp);return t===-1?-1:r.presentationTimestamps[t].sampleIndex}else{const t=X(r.sampleTimingEntries,e,n=>n.startDecodeTimestamp);if(t===-1)return-1;const i=r.sampleTimingEntries[t];return i.startIndex+Math.min(Math.floor((e-i.startDecodeTimestamp)/i.delta),i.count-1)}},Hd=(r,e)=>{if(!r.keySampleIndices)return vs(r,e);if(r.presentationTimestamps){const t=X(r.presentationTimestamps,e,i=>i.presentationTimestamp);if(t===-1)return-1;for(let i=t;i>=0;i--){const n=r.presentationTimestamps[i].sampleIndex;if(Ei(r.keySampleIndices,n,a=>a)!==-1)return n}return-1}else{const t=vs(r,e),i=X(r.keySampleIndices,t,n=>n);return r.keySampleIndices[i]??-1}},jd=(r,e)=>{const t=X(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=X(r.sampleCompositionTimeOffsets,e,y=>y.startIndex),o=r.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(s+=o.offset);
1const c=r.sampleSizes[Math.min(e,r.sampleSizes.length-1)],l=X(r.sampleToChunk,e,y=>y.startSampleIndex),u=r.sampleToChunk[l];p(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 g=0,m=f;if(r.sampleSizes.length===1)m+=c*(e-h),g+=c*u.samplesPerChunk;else for(let y=h;y<h+u.samplesPerChunk;y++){const b=r.sampleSizes[y];y<e&&(m+=b),g+=b}let w=i.delta;if(r.presentationTimestamps){const y=r.presentationTimestampIndexMap[e];p(y!==void 0),y<r.presentationTimestamps.length-1&&(w=r.presentationTimestamps[y+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:w,sampleOffset:m,sampleSize:c,chunkOffset:f,chunkSize:g,isKeyFrame:r.keySampleIndices?Ei(r.keySampleIndices,e,y=>y)!==-1:!0}},Kd=(r,e)=>{if(!r.keySampleIndices)return e+1;const t=X(r.keySampleIndices,e,i=>i);return r.keySampleIndices[t+1]??-1},Qn=(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},io=r=>[Yt(r),Yt(r),jn(r),Yt(r),Yt(r),jn(r),Yt(r),Yt(r),jn(r)],no=r=>r.sampleSizes.length===0,so=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},cl=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{p(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)i+=t.sampleSizes[o]}let n=r.requestSlice(t.offset,i);if(v(n)&&(n=await n),!n)throw new Error("Failed to read auxiliary encryption info.");const s=e.defaultPerSampleIvSize;p(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=ge(n);u=[];for(let f=0;f<d;f++){const h=ge(n),g=R(n);u.push({clearLen:h,protectedLen:g})}}a.push({iv:l,subsamples:u})}return t.resolved=a,a},ao=r=>r.defaultConstantIv?{iv:r.defaultConstantIv,subsamples:null}:null,oo=async(r,e,t,i)=>{p(r.encryptionInfo);const n=r.encryptionInfo;p(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++)il(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&&Iu.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:Eu(u)})();r.demuxer.decryptionKeyCache.set(s,c),a=await c}return n.scheme==="cenc"||n.scheme==="cens"?Qd(a,n,e,t):Gd(a,n,e,t)},Qd=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 g=>{const m=await crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,g);return new Uint8Array(m)};if(!t.subsamples)return a(i);p(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=ll(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const g of o)for(const m of g.perSubsample)c+=m.length;const l=new Uint8Array(c);let u=0;for(const g of o)for(const m of g.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 g of o)for(const m of g.perSubsample)f.set(d.subarray(h,h+m.length),m.offset),h+=m.length;return f},Gd=(r,e,t,i)=>{const n=new al;n.init({key:r,iv:t.iv});const s=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(p(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=ll(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 g=d.offset+h*16;n.in.set(i.subarray(g,g+16)),n.decrypt(),o.set(n.out,g)}}}return o},ll=(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 si{constructor(e){this.value=e}}class Bs{constructor(e){this.value=e}}class ul{constructor(e){this.value=e}}class Ut{constructor(e){this.value=e}}var _;(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.ProjectionPoseYaw=30323]="ProjectionPoseYaw",r[r.ProjectionPosePitch=30324]="ProjectionPosePitch",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"})(_||(_={}));const $d=[_.EBML,_.Segment],Si=[_.SeekHead,_.Info,_.Cluster,_.Tracks,_.Cues,_.Attachments,_.Chapters,_.Tags],Xi=[...$d,...Si],co=r=>r<256?1:r<65536?2:r<1<<24?3:r<2**32?4:r<2**40?5:6,lo=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,uo=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,Xd=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 Yd{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=co(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=lo(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=uo(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=Xd(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??co(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??lo(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 si)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof Bs)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof ul){const t=e.size??uo(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof Ut){const t=Z.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else Ae(e.data)}}const Fs=8,Le=2,ft=2*Fs,dl=r=>{if(r.remainingLength<1)return null;const e=U(r);if(r.skip(-1),e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;return r.remainingLength<t?null:t},ai=r=>{if(r.remainingLength<1)return null;const e=U(r);if(e===0)return null;let t=1,i=128;for(;(e&i)===0;)t++,i>>=1;if(r.remainingLength<t-1)return null;let n=e&i-1;for(let s=1;s<t;s++)n*=256,n+=U(r);return n},Q=(r,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let i=0;i<e;i++)t*=256,t+=U(r);return t},Zd=(r,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let i=0;i<e;i++)t<<=8n,t+=BigInt(U(r));return t},wa=r=>{const e=dl(r);return e===null||r.remainingLength<e?null:Q(r,e)},fl=r=>{if(r.remainingLength<1)return null;if(U(r)===255)return;r.skip(-1);const t=ai(r);if(t===null)return null;if(t!==72057594037927940)return t},dt=r=>{p(r.remainingLength>=Le);const e=wa(r);if(e===null)return null;const t=fl(r);return t===null?null:{id:e,size:t}},Cr=(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))},jr=(r,e)=>{const t=N(r,e);let i=0;for(;i<e&&t[i]!==0;)i+=1;return Ue.decode(t.subarray(0,i))},Kr=(r,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?Uh(r):su(r)},Rs=async(r,e,t,i)=>{const n=new Set(t);let s=e;for(;i===null||s<i;){let a=r.requestSliceRange(s,Le,ft);if(v(a)&&(a=await a),!a)break;const o=dt(a);if(!o)break;if(n.has(o.id))return{pos:s,found:!0};yt(o.size),s=a.filePos+o.size}return{pos:i!==null&&i>s?i:s,found:!1}},hl=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(v(o)&&(o=await o),!o||o.length<Fs)break;for(let c=0;c<o.length-Fs;c++){o.filePos=a;const l=wa(o);if(l!==null&&s.has(l))return a;a++}}return null},ze={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 yt(r){if(r===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}const ml=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 kt;(function(r){r[r.None=0]="None",r[r.Xiph=1]="Xiph",r[r.FixedSize=2]="FixedSize",r[r.Ebml=3]="Ebml"})(kt||(kt={}));var ln;(function(r){r[r.Block=1]="Block",r[r.Private=2]="Private",r[r.Next=4]="Next"})(ln||(ln={}));var li;
1(function(r){r[r.Zlib=0]="Zlib",r[r.Bzlib=1]="Bzlib",r[r.lzo1x=2]="lzo1x",r[r.HeaderStripping=3]="HeaderStripping"})(li||(li={}));const Gn=[{id:_.SeekHead,flag:"seekHeadSeen"},{id:_.Info,flag:"infoSeen"},{id:_.Tracks,flag:"tracksSeen"},{id:_.Cues,flag:"cuesSeen"}],pl=10*2**20;class Jd extends Rt{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 ml({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,Le,ft);if(v(t)&&(t=await t),!t)break;const i=dt(t);if(!i)break;const n=i.id;let s=i.size;const a=t.filePos;if(n===_.EBML){yt(s);let o=this.reader.requestSlice(a,s);if(v(o)&&(o=await o),!o)break;this.readContiguousElements(o)}else if(n===_.Segment){if(await this.readSegment(a,s),s===void 0||this.reader.fileSize===null)break}else if(n===_.Cluster){if(this.reader.fileSize===null)break;s===void 0&&(s=(await Rs(this.reader,a,Xi,this.reader.fileSize)).pos-a);const o=ue(this.segments);o&&(o.elementEndPos=a+s)}yt(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;const n=new Set;for(;this.currentSegment.elementEndPos===null||i<this.currentSegment.elementEndPos;){let c=this.reader.requestSliceRange(i,Le,ft);if(v(c)&&(c=await c),!c)break;const l=i,u=dt(c);if(!u||!Si.includes(u.id)&&u.id!==_.Void){const m=await hl(this.reader,l,Si,Math.min(this.currentSegment.elementEndPos??1/0,l+pl));if(m){i=m;continue}else break}const{id:d,size:f}=u,h=c.filePos,g=Gn.findIndex(m=>m.id===d);if(g!==-1){const m=Gn[g].flag;this.currentSegment[m]=!0,d===_.SeekHead&&n.add(l-e),yt(f);let w=this.reader.requestSlice(h,f);v(w)&&(w=await w),w&&this.readContiguousElements(w)}else if(d===_.Tags||d===_.Attachments){d===_.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,yt(f);let m=this.reader.requestSlice(h,f);v(m)&&(m=await m),m&&this.readContiguousElements(m)}else if(d===_.Cluster){this.currentSegment.clusterSeekStartPos=l;break}if(f===void 0)break;i=h+f}if(this.reader.fileSize!==null)for(;;){const c=this.currentSegment.seekEntries.find(h=>h.id===_.SeekHead&&!n.has(h.segmentPosition));if(!c)break;n.add(c.segmentPosition);let l=this.reader.requestSliceRange(e+c.segmentPosition,Le,ft);if(v(l)&&(l=await l),!l)continue;const u=dt(l);if(!u||u.id!==_.SeekHead)continue;const{size:d}=u;yt(d);let f=this.reader.requestSlice(l.filePos,d);v(f)&&(f=await f),f&&this.readContiguousElements(f)}if(this.currentSegment.seekEntries.sort((c,l)=>c.segmentPosition-l.segmentPosition),this.reader.fileSize!==null)for(const c of this.currentSegment.seekEntries){const l=Gn.find(m=>m.id===c.id);if(!l||this.currentSegment[l.flag])continue;let u=this.reader.requestSliceRange(e+c.segmentPosition,Le,ft);if(v(u)&&(u=await u),!u)continue;const d=dt(u);if(!d)continue;const{id:f,size:h}=d;if(f!==l.id)continue;yt(h),this.currentSegment[l.flag]=!0;let g=this.reader.requestSlice(u.filePos,h);v(g)&&(g=await g),g&&this.readContiguousElements(g)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const c of this.currentSegment.tracks)c.defaultDurationNs!==null&&(c.defaultDuration=this.currentSegment.timestampFactor*c.defaultDurationNs/1e9);const s=new Map(this.currentSegment.tracks.map(c=>[c.id,c]));for(const c of this.currentSegment.cuePoints){const l=s.get(c.trackId);l&&l.cuePoints.push(c)}for(const c of this.currentSegment.tracks){c.cuePoints.sort((l,u)=>l.time-u.time);for(let l=0;l<c.cuePoints.length-1;l++){const u=c.cuePoints[l],d=c.cuePoints[l+1];u.time===d.time&&(c.cuePoints.splice(l+1,1),l--)}}let a=null,o=-1/0;for(const c of this.currentSegment.tracks)c.cuePoints.length>o&&(o=c.cuePoints.length,a=c);for(const c of this.currentSegment.tracks)c.cuePoints.length===0&&(c.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,Le,ft);v(i)&&(i=await i),p(i);const n=e,s=dt(i);p(s);const a=s.id;p(a===_.Cluster);let o=s.size;const c=i.filePos;o===void 0&&(o=(await Rs(this.reader,c,Xi,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);v(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,Xi);u.elementEndPos=d}for(const[,d]of u.trackData){const f=d.track;p(d.blocks.length>0);let h=!1;for(let y=0;y<d.blocks.length;y++){const b=d.blocks[y];b.timestamp+=u.timestamp,h||=b.lacing!==kt.None}d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp);for(let y=0;y<d.presentationTimestamps.length;y++){const b=d.presentationTimestamps[y],k=d.blocks[b.blockIndex];if(d.firstKeyFrameTimestamp===null&&k.isKeyFrame&&(d.firstKeyFrameTimestamp=k.timestamp),y<d.presentationTimestamps.length-1){const S=d.presentationTimestamps[y+1];k.duration=S.timestamp-k.timestamp}else k.duration===0&&f.defaultDuration!=null&&k.lacing===kt.None&&(k.duration=f.defaultDuration)}h&&(this.expandLacedBlocks(d.blocks,f),d.presentationTimestamps=d.blocks.map((y,b)=>({timestamp:y.timestamp,blockIndex:b})).sort((y,b)=>y.timestamp-b.timestamp));const g=d.blocks[d.presentationTimestamps[0].blockIndex],m=d.blocks[ue(d.presentationTimestamps).blockIndex];d.startTimestamp=g.timestamp,d.endTimestamp=m.timestamp+m.duration;const w=X(f.clusterPositionCache,d.startTimestamp,y=>y.startTimestamp);(w===-1||f.clusterPositionCache[w].elementStartPos!==n)&&f.clusterPositionCache.splice(w+1,0,{elementStartPos:u.elementStartPos,startTimestamp:d.startTimestamp})}return t.lastReadCluster=u,u}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const n=e.segment.tracks.find(s=>s.id===t);if(!n)return null;i={track:n,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}
1expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){const n=e[i];if(n.lacing===kt.None)continue;n.decoded||(n.data=this.decodeBlockData(t,n.data),n.decoded=!0);const s=De.tempFromBytes(n.data),a=[],o=U(s)+1;switch(n.lacing){case kt.Xiph:{let l=0;for(let u=0;u<o-1;u++){let d=0;for(;s.bufferPos<s.length;){const f=U(s);if(d+=f,f<255){a.push(d),l+=d;break}}}a.push(s.length-(s.bufferPos+l))}break;case kt.FixedSize:{const l=s.length-1,u=Math.floor(l/o);for(let d=0;d<o;d++)a.push(u)}break;case kt.Ebml:{const l=ai(s);p(l!==null);let u=l;a.push(u);let d=u;for(let f=1;f<o-1;f++){const h=s.bufferPos,g=ai(s);p(g!==null);const m=g,y=(1<<(s.bufferPos-h)*7-1)-1,b=m-y;u+=b,a.push(u),d+=u}a.push(s.length-(s.bufferPos+d))}break;default:p(!1)}p(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:kt.None,decoded:!0,postProcessed:!1,mainAdditional:n.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===_.Tags&&!e.tagsSeen)){if(!(t.id===_.Attachments&&!e.attachmentsSeen))continue}let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Le,ft);if(v(i)&&(i=await i),!i)continue;const n=dt(i);if(!n||n.id!==t.id)continue;const{size:s}=n;yt(s),p(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(i.filePos,s);v(a)&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===_.Tags?e.tagsSeen=!0:t.id===_.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Le;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=dt(e);if(!i||t&&t.includes(i.id))return!1;const{id:n,size:s}=i,a=e.filePos;switch(yt(s),n){case _.DocType:this.isWebM=Cr(e,s)==="webm";break;case _.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 _.SeekID:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.id=Q(e,s)}break;case _.SeekPosition:{const o=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!o)break;o.segmentPosition=Q(e,s)}break;case _.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=Q(e,s),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case _.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Kr(e,s)}break;case _.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ft,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,s)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(o=>o.data?.type!=="decompress"||o.scope!==ln.Block||o.data.algorithm!==li.HeaderStripping)&&(O._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===ze.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPr
1ivate;else if(this.currentTrack.codecId===ze.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(c===ze.vp8)this.currentTrack.info.codec="vp8";else if(c===ze.vp9)this.currentTrack.info.codec="vp9";else if(c===ze.av1)this.currentTrack.info.codec="av1";else if(c===ze.prores){const u=this.currentTrack.codecPrivate?Ue.decode(this.currentTrack.codecPrivate):"";cr.includes(u)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=u)}const l=this.currentTrack;this.currentTrack.trackBacking=new ef(l),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){c===ze.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===ze.mp3?this.currentTrack.info.codec="mp3":c===ze.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=qr):c===ze.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ze.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ze.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ze.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):c===ze.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 tf(l),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case _.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=Q(e,s)}break;case _.TrackType:{if(!this.currentTrack)break;const o=Q(e,s);o===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,horizontalScale:1,verticalScale:1,rotation:0,codec:null,codecDescription:null,colorSpace:{...Ac},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 _.FlagEnabled:{if(!this.currentTrack)break;Q(e,s)||(this.currentTrack=null)}break;case _.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Q(e,s)}break;case _.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Q(e,s)}break;case _.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Q(e,s)}break;case _.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Q(e,s)}break;case _.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Q(e,s)}break;case _.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Q(e,s)}break;case _.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=Cr(e,s)}break;case _.CodecPrivate:{if(!this.currentTrack)break;
1this.currentTrack.codecPrivate=N(e,s)}break;case _.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Q(e,s)}break;case _.Name:{if(!this.currentTrack)break;this.currentTrack.name=jr(e,s)}break;case _.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Cr(e,s),gi(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Ie)}break;case _.LanguageBCP47:{if(!this.currentTrack)break;const c=Cr(e,s).split("-")[0];c?this.currentTrack.languageCode=c:this.currentTrack.languageCode=Ie,this.currentTrack.hasLanguageBcp47=!0}break;case _.Video:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case _.PixelWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=Q(e,s)}break;case _.PixelHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=Q(e,s)}break;case _.DisplayWidth:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=Q(e,s)}break;case _.DisplayHeight:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=Q(e,s)}break;case _.DisplayUnit:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=Q(e,s)}break;case _.AlphaMode:{if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=Q(e,s)===1}break;case _.Colour:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case _.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video")break;const o=Q(e,s),c=xt[o];this.currentTrack.info.colorSpace.matrix=c}break;case _.Range:{if(this.currentTrack?.info?.type!=="video")break;const o=Q(e,s);this.currentTrack.info.colorSpace.fullRange=o===1||o===2?o===2:void 0}break;case _.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video")break;const o=Q(e,s),c=At[o];this.currentTrack.info.colorSpace.transfer=c}break;case _.Primaries:{if(this.currentTrack?.info?.type!=="video")break;const o=Q(e,s),c=St[o];this.currentTrack.info.colorSpace.primaries=c}break;case _.Projection:{if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(a,s))}break;case _.ProjectionPoseYaw:{if(this.currentTrack?.info?.type!=="video")break;const o=Kr(e,s);try{const c=or(o);this.currentTrack.info.horizontalScale=Math.round(Math.cos(c*ps))}catch{}}break;case _.ProjectionPosePitch:{if(this.currentTrack?.info?.type!=="video")break;const o=Kr(e,s);try{const c=or(o);this.currentTrack.info.verticalScale=Math.round(Math.cos(c*ps))}catch{}}break;case _.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;const c=-Kr(e,s);try{this.currentTrack.info.rotation=or(c)}catch{}}break;case _.Audio:{if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(a,s))}break;case _.SamplingFrequency:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=Kr(e,s)}break;case _.Channels:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=Q(e,s)}break;case _.BitDepth:{if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=Q(e,s)}break;case _.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,s)),this.currentCueTime=null}break;case _.CueTime:this.currentCueTime=Q(e,s);break;case _.CueTrackPositions:{if(this.currentCueTime===null)break;p(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 _.CueTrack:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;o.trackId=Q(e,s)}break;case _.CueClusterPosition:{const o=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!o)break;p(this.currentSegment),o.clusterPosition=this.currentSegment.dataStartPos+Q(e,s)}break;case _.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=Q(e,s)}break;case _.SimpleBlock:{if(!this.currentCluster)break;const o=ai(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=Ks(e),u=U(e),d=u>>1&3;let f=!!(u&128);c.track.info?.type==="audio"&&c.track.info.codec&&(f=!0);
1const h=N(e,s-(e.filePos-a)),g=c.track.decodingInstructions.length>0;c.blocks.push({timestamp:l,duration:0,isKeyFrame:f,data:h,lacing:d,decoded:!g,postProcessed:!1,mainAdditional:null})}break;case _.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,s)),this.currentBlock=null}break;case _.Block:{if(!this.currentCluster)break;const o=ai(e);if(o===null)break;const c=this.getTrackDataInCluster(this.currentCluster,o);if(!c)break;const l=Ks(e),d=U(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 _.BlockAdditions:this.readContiguousElements(e.slice(a,s));break;case _.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 _.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=N(e,s)}break;case _.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Q(e,s)}break;case _.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=Q(e,s)}break;case _.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case _.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,s));break;case _.Targets:this.readContiguousElements(e.slice(a,s));break;case _.TargetTypeValue:Q(e,s)!==50&&(this.currentTagTargetIsMovie=!1);break;case _.TagTrackUID:case _.TagEditionUID:case _.TagChapterUID:case _.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case _.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,s))}break;case _.TagName:this.currentSimpleTagName=jr(e,s);break;case _.TagString:{if(!this.currentSimpleTagName)break;const o=jr(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case _.TagBinary:{if(!this.currentSimpleTagName)break;const o=N(e,s);this.processTagValue(this.currentSimpleTagName,o)}break;case _.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 ia(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 _.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Zd(e,s)}break;case _.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=jr(e,s)}break;
1case _.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Cr(e,s)}break;case _.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=N(e,s)}break;case _.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=jr(e,s)}break;case _.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,s)),this.currentTrack.decodingInstructions.sort((o,c)=>c.order-o.order)}break;case _.ContentEncoding:this.currentDecodingInstruction={order:0,scope:ln.Block,data:null},this.readContiguousElements(e.slice(a,s)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case _.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Q(e,s)}break;case _.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Q(e,s)}break;case _.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:li.Zlib,settings:null},this.readContiguousElements(e.slice(a,s))}break;case _.ContentCompAlgo:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=Q(e,s)}break;case _.ContentCompSettings:{if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=N(e,s)}break;case _.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+s,!0}decodeBlockData(e,t){p(e.decodingInstructions.length>0);let i=t;for(const n of e.decodingInstructions)switch(p(n.data),n.data.type){case"decompress":switch(n.data.algorithm){case li.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"bpm":{const n=Number.parseInt(t,10);Number.isInteger(n)&&n>0&&(i.beatsPerMinute??=n)}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}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(const n of e.tracks){p(n.trackBacking);const s=await n.trackBacking.getFirstPacket({metadataOnly:!0});s&&(t=Math.min(t??1/0,s.timestamp))}let i=e.duration/e.timestampFactor;return i+=t??0,i}}class gl{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(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}
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 pi(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=X(s.presentationTimestamps,i,l=>l.timestamp),o=a!==-1?s.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&i<s.endTimestamp;return{blockIndex:o,correctBlockFound:c}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(i===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,n=>{if(n===i.cluster){const s=n.trackData.get(this.internalTrack.id);if(i.blockIndex+1<s.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(n.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,n=>{const s=n.trackData.get(this.internalTrack.id);if(!s)return{blockIndex:-1,correctBlockFound:!1};const a=wn(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 p(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(p(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);q(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?Qe: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?Qe:s.mainAdditional,l.alphaByteLength=s.mainAdditional.byteLength);const u=new te(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:b}=t(e);if(b)return this.fetchPacketInCluster(e,y,s);y!==-1&&(l=e,u=y)}const d=X(this.internalTrack.cuePoints,i,y=>y.time),f=d!==-1?this.internalTrack.cuePoints[d]:null,h=X(this.internalTrack.clusterPositionCache,i,y=>y.startTimestamp),g=h!==-1?this.internalTrack.clusterPositionCache[h]:null,m=Math.max(f?.clusterPosition??0,g?.elementStartPos??0)||null;let w;for(e?m===null||e.elementStartPos>=m?(w=e.elementEndPos,c=e):w=m:w=m??o.clusterSeekStartPos;o.elementEndPos===null||w<=o.elementEndPos-Le;){if(c){const C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>n)break}let y=a.reader.requestSliceRange(w,Le,ft);if(v(y)&&(y=await y),!y)break;const b=w,k=dt(y);if(!k||!Si.includes(k.id)&&k.id!==_.Void){const C=await hl(a.reader,b,Si,Math.min(o.elementEndPos??1/0,b+pl));
1if(C){w=C;continue}else break}const S=k.id;let T=k.size;const A=y.filePos;if(S===_.Cluster){c=await a.readCluster(b,o),T=c.elementEndPos-A;const{blockIndex:C,correctBlockFound:x}=t(c);if(x)return this.fetchPacketInCluster(c,C,s);C!==-1&&(l=c,u=C)}T===void 0&&(p(S!==_.Cluster),T=(await Rs(a.reader,A,Xi,o.elementEndPos)).pos-A);const P=A+T;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(P,Le,ft);if(v(C)&&(C=await C),!C)break;if(wa(C)===_.Segment){o.elementEndPos=P;break}}w=P}if(f&&(!l||l.elementStartPos<f.clusterPosition)){const y=this.internalTrack.cuePoints[d-1];p(!y||y.time<f.time);const b=y?.time??-1/0;return this.performClusterLookup(null,t,b,n,s)}return l?this.fetchPacketInCluster(l,u,s):null}}class ef extends gl{constructor(e){super(e),this.decoderConfigPromise=null}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}getTransformationMatrix(){const e=this.internalTrack.info,t=Mr(kc(e.horizontalScale,e.verticalScale),Ys(e.rotation));return yc(t,e.width,e.height)}async getColorSpace(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}
vendor: 1,279 bytes, line 1
1async canBeTransparent(){return this.internalTrack.info.alphaMode||this.internalTrack.info.codec==="prores"&&(this.internalTrack.info.proresFormat==="ap4h"||this.internalTrack.info.proresFormat==="ap4x")}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="prores"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const i={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?xn(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Pn(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?zc(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?la(e.data):null,proresCodecInfo:this.internalTrack.info.codec==="prores"&&e?Uc(e.data):null,proresFormat:this.internalTrack.info.proresFormat};
1if(!Js(this.internalTrack.info.colorSpace)){const s=Xc(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:ha(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 tf extends gl{constructor(e){super(e),this.decoderConfigPromise=null}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&&Kc(e.data)}return{codec:ma({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 Ms=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,lr,a);if(v(o)&&(o=await o),!o||o.length<lr)break;for(;o.remainingLength>=lr;){const c=o.filePos,l=R(o),u=r.fileSize!==null?r.fileSize-s:null,d=ki(l,u);if(d.header&&(!i||d.header.sampleRate===i.sampleRate&&d.header.mpegVersionId===i.mpegVersionId&&d.header.layer===i.layer&&Ti(d.header.channel)===Ti(i.channel)))return{header:d.header,startPos:s};o.filePos=c+d.bytesAdvanced,s=o.filePos}}return null};class rf extends Rt{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 pr,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 nf(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,Ye);if(v(o)&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=Bt(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await Ms(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=En(t.mpegVersionId,t.channel);let n=this.reader.requestSlice(e.startPos+i,4);if(v(n)&&(n=await n),n){const o=R(n);if(o===In||o===pa){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let l=this.reader.requestSlice(e.startPos+i+4,12);if(v(l)&&(l=await l),l){const u=N(l,12),d=q(u),f=d.getUint32(0,!1);this.xingData={frameCount:f&ur.FrameCount?d.getUint32(4,!1):null,fileSize:f&ur.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,Ye);
1if(v(n)&&(n=await n),!n)break;const s=Bt(n);if(!s)break;i=!0;let a=this.reader.requestSlice(n.filePos,s.size);if(v(a)&&(a=await a),!a)break;Dn(a,s,this.metadataTags),t=n.filePos+s.size}if(!i&&this.reader.fileSize!==null&&this.reader.fileSize>=Zi){let n=this.reader.requestSlice(this.reader.fileSize-Zi,Zi);v(n)&&(n=await n),p(n),fe(n,3)==="TAG"&&Nh(n,this.metadataTags)}return this.metadataTags}finally{e()}}}class nf{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return p(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(p(e.firstFrameHeader!==null),p(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=Nd(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 Ie}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.firstFrameHeader),Ti(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Ft}}async getDecoderConfig(){return p(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Ti(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=Qe;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(v(s)&&(s=await s),!s)return null;n=N(s,i.dataSize)}return new te(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=Ei(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=X(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ya=1399285583,sf=79764919,wl=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^sf:e<<1;wl[r]=e>>>0&4294967295}const yl=r=>{const e=q(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^wl[i>>>24^s])>>>0}return e.setUint32(22,t,!0),i},bl=(r,e,t)=>{let i=0,n=null;if(r.length>0)if(e.codec==="vorbis"){p(e.vorbisInfo);const s=e.vorbisInfo.modeBlockflags.length,o=(1<<zu(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=ld(r).durationInSamples);return{durationInSamples:i,vorbisBlockSize:n}},kl=r=>{let e="audio/ogg";if(r.codecStrings){const t=[...new Set(r.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};const nr=27,Fr=282,Tl=Fr+65025,ui=r=>{const e=r.filePos;if(Ir(r)!==ya)return null;r.skip(1);const i=U(r),n=Oh(r),s=Ir(r),a=Ir(r),o=Ir(r),c=U(r),l=new Uint8Array(c);for(let h=0;h<c;h++)l[h]=U(r);const u=27+c,d=l.reduce((h,g)=>h+g,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}},af=(r,e)=>{for(;r.filePos<e-3;){const t=Ir(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===ya)return!0;r.skip(1)}}return!1};class of extends Rt{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,nr,Fr);if(v(t)&&(t=await t),!t)break;const i=ui(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 cf(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=q(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:Nc(s.data).modeBlockflags},xs(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=Cn(e.data);t.numberOfChannels=s.outputChannelCount,t.sampleRate=qr,t.codecInfo.opusInfo={preSkip:s.preSkip},xs(n.data.subarray(8),this.metadataTags)}async readPacket(e,t){p(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);v(d)&&(d=await d),p(d);const f=N(d,n.dataSize);for(;;){if(a===n.lacingValues.length){o.push(f.subarray(i,s));break}const g=n.lacingValues[a];if(s+=g,g<255){o.push(f.subarray(i,s));break e}a++}let h=n.headerStartPos+n.totalSize;
1for(;;){let g=this.reader.requestSliceRange(h,nr,Fr);if(v(g)&&(g=await g),!g)return null;const m=ui(g);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,nr,Fr);if(v(n)&&(n=await n),!n)return null;const s=ui(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 kl({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class cf{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new pr,this.internalSampleRate=e.codecInfo.codec==="opus"?qr:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return p(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 p(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return Ie}getDisposition(){return{...Ft,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(p(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:n,vorbisBlockSize:s}=bl(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new te(i.metadataOnly?Qe: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){p(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;this.bitstream.codecInfo.codec==="opus"&&(p(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=pi(e*this.internalSampleRate);if(i===0)return this.getFirstPacket(t);if(i<0)return null;p(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 b=s.headerStartPos,k=Math.floor((b+a)/2);let S=k;for(;;){const T=Math.min(S+Tl,a-nr);let A=this.demuxer.reader.requestSlice(S,T-S);if(v(A)&&(A=await A),p(A),!af(A,T)){a=k+nr;continue e}let C=this.demuxer.reader.requestSliceRange(A.filePos,nr,Fr);v(C)&&(C=await C),p(C);const x=ui(C);p(x);let I=!1;if(x.serialNumber===this.bitstream.serialNumber)I=!0;else{let F=this.demuxer.reader.requestSlice(x.headerStartPos,x.totalSize);v(F)&&(F=await F),p(F);const D=N(F,x.totalSize);I=yl(D)===x.checksum}if(!I){S=x.headerStartPos+4;continue}if(I&&x.serialNumber!==this.bitstream.serialNumber){S=x.headerStartPos+x.totalSize;continue}if(x.granulePosition===-1){S=x.headerStartPos+x.totalSize;continue}this.granulePositionToTimestampInSamples(x.granulePosition)>i?a=x.headerStartPos:(s=x,o.push(x));continue e}}let c=n.startPage;for(const b of o){if(b.granulePosition===s.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let l=c;const u=[l];for(;!(l.serialNumber===this.bitstream.serialNumber&&l.granulePosition===s.granulePosition);){const b=l.headerStartPos+l.totalSize;let k=this.demuxer.reader.requestSliceRange(b,nr,Fr);v(k)&&(k=await k),p(k);const S=ui(k);p(S),l=S,l.serialNumber===this.bitstream.serialNumber&&u.push(l)}p(l.granulePosition!==-1);let d=null,f,h,g=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 b={data:Qe,endPage:g,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(b)){const S=ho(u,l,d);p(S);const T=fo(u,S.page,S.segmentIndex);T&&(l=T.page,d=T.segmentIndex)}else for(;;){const S=ho(u,l,d);if(!S)break;const T=fo(u,S.page,S.segmentIndex);if(!T)break;if(l=T.page,d=T.segmentIndex,S.page.headerStartPos!==g.headerStartPos){g=S.page,m=S.segmentIndex;break}}}let w=null,y=null;for(;l!==null;){p(d!==null);const b=await this.demuxer.readPacket(l,d);if(!b)break;
1if(!(l.headerStartPos===n.startPage.headerStartPos&&d<n.startSegmentIndex)){let T=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f,vorbisLastBlocksize:y?.vorbisBlockSize??null},t);p(T);let A=this.encodedPacketToMetadata.get(T);if(p(A),!h&&b.endPage.headerStartPos===g.headerStartPos&&b.endSegmentIndex===m?(f=this.granulePositionToTimestampInSamples(l.granulePosition),h=!0,T=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:f-A.durationInSamples,vorbisLastBlocksize:y?.vorbisBlockSize??null},t),p(T),A=this.encodedPacketToMetadata.get(T),p(A)):f+=A.durationInSamples,w=T,y=A,h&&(Math.max(f,0)>i||Math.max(A.timestampInSamples,0)===i))break}const S=await this.demuxer.findNextPacketStart(b);if(!S)break;l=S.startPage,d=S.startSegmentIndex}return w}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const n=pi(e*this.internalSampleRate);e=n/this.internalSampleRate;const s=X(this.sequentialScanCache,n,c=>c.timestampInSamples);let a;if(s!==-1){const c=this.sequentialScanCache[s];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const l=this.encodedPacketToMetadata.get(a);p(l),this.sequentialScanCache.length>0&&p(ue(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 fo=(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(p(n===-1),!(i.headerType&1)){n=0;break}const a=xc(r,o=>o.headerStartPos<i.headerStartPos);if(!a)return null;i=a,n=i.lacingValues.length}if(p(n!==-1),n===i.lacingValues.length){const s=r[r.indexOf(i)+1];p(s),i=s,n=0}return{page:i,segmentIndex:n}},ho=(r,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const i=xc(r,n=>n.headerStartPos<e.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};var Se;(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"})(Se||(Se={}));class lf extends Rt{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);v(e)&&(e=await e),p(e);const t=fe(e,4),i=t!=="RIFX",n=t==="RF64",s=jt(e,i);let a=n?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if(fe(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(v(f)&&(f=await f),!f)break;const h=fe(f,4),g=jt(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,g,i);else if(h==="data"){if(l??=g,this.dataStart=f.filePos,this.dataSize=Math.min(l,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(h==="ds64"){let w=this.reader.requestSlice(m,g);if(v(w)&&(w=await w),!w)break;const y=$o(w,i);l=$o(w,i),a=Math.min(y+8,this.reader.fileSize??1/0)}else h==="LIST"?await this.parseListChunk(m,g,i):(h==="ID3 "||h==="id3 ")&&await this.parseId3Chunk(m,g);u=m+g+(g&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 uf(this))})()}async parseFmtChunk(e,t,i){let n=this.reader.requestSlice(e,t);if(v(n)&&(n=await n),!n)return;let s=Jr(n,i);const a=Jr(n,i),o=jt(n,i);n.skip(4);const c=Jr(n,i);let l;if(t===14?l=8:l=Jr(n,i),t>=18&&s!==357){const u=Jr(n,i),d=t-18;if(Math.min(d,u)>=22&&s===Se.EXTENSIBLE){n.skip(6);const h=N(n,16);s=h[0]|h[1]<<8}}if((s===Se.MULAW||s===Se.ALAW)&&(l=8),s!==Se.PCM&&s!==Se.IEEE_FLOAT&&s!==Se.ALAW&&s!==Se.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and μ-law are supported.`);if(s===Se.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===Se.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(v(n)&&(n=await n),!n)return;const s=fe(n,4);if(s!=="INFO"&&s!=="INF0")return;let a=n.filePos;for(;a<=e+t-8;){n.filePos=a;const o=fe(n,4),c=jt(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),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(h)&&h>0&&(this.metadataTags.trackNumber??=h),g&&Number.isInteger(g)&&g>0&&(this.metadataTags.tracksTotal??=g)}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(v(i)&&(i=await i),!i)return;
1const n=Bt(i);if(n){const s=t-Ye;if(n.size=Math.min(n.size,s),n.size>0){const a=i.slice(e+Ye,n.size);Dn(a,n,this.metadataTags)}}}getCodec(){if(p(this.audioInfo),this.audioInfo.format===Se.MULAW)return"ulaw";if(this.audioInfo.format===Se.ALAW)return"alaw";if(this.audioInfo.format===Se.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===Se.IEEE_FLOAT){if(this.audioInfo.sampleSizeInBytes===4)return"pcm-f32";if(this.audioInfo.sampleSizeInBytes===8)return"pcm-f64"}p(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const br=2048;class uf{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(p(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return p(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}
1async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return Ie}getDisposition(){return{...Ft}}async getPacketAtIndex(e,t){p(e>=0),p(this.demuxer.audioInfo);const i=e*br*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const n=Math.min(br*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(v(c)&&(c=await c),!c)return null}let s;if(t.metadataOnly)s=Qe;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,n);v(c)&&(c=await c),p(c),s=N(c,n)}const a=e*br/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 te(s,"key",a,o,e,n)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){p(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/br,(this.demuxer.dataSize-1)/(br*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;p(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){p(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/br);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ai=7,Kt=9,vt=r=>{const e=r.filePos,t=N(r,9),i=new H(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 un=1024;class df extends Rt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new pr,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();p(this.firstFrameHeader),this.trackBackings=[new ff(this)]})()}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,Ye);if(v(a)&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=Bt(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,Ai,Kt);if(v(e)&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=vt(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=Qt[t.samplingFrequencyIndex];p(i!==void 0);const n=un/i,s={timestamp:this.nextTimestampInSamples/i,duration:n,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=un,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,Ye);if(v(i)&&(i=await i),!i)break;const n=Bt(i);if(!n)break;let s=this.reader.requestSlice(i.filePos,n.size);if(v(s)&&(s=await s),!s)break;Dn(s,n,this.metadataTags),t=i.filePos+n.size}return this.metadataTags}finally{e()}}}class ff{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}
1getTimeResolution(){return this.getSampleRate()/un}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 Ie}getCodec(){return"aac"}getInternalCodecId(){return p(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){p(this.demuxer.firstFrameHeader);const e=Wr[this.demuxer.firstFrameHeader.channelConfiguration];return p(e!==void 0),e}getSampleRate(){p(this.demuxer.firstFrameHeader);const e=Qt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return p(e!==void 0),e}getDisposition(){return{...Ft}}async getDecoderConfig(){return p(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=Qe;else{let s=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(v(s)&&(s=await s),!s)return null;n=N(s,i.dataSize)}return new te(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=Ei(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(n===-1)throw new Error("Packet was not created from this track.");const s=n+1;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=X(this.demuxer.loadedSamples,e,s=>s.timestamp);if(n===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(n,t);if(n>=0&&n+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(n,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Sl=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,hf=(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}},Al=r=>{let e=0;const t=new H(N(r,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const i=[],n=e-1,s=new H(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)},xl=(r,e)=>{if(e==="uncommon-u16")return ge(r)+1;if(e==="uncommon-u8")return U(r)+1;if(typeof e=="number")return e;Ae(e),p(!1)},mf=(r,e)=>e==="uncommon-u16"?ge(r):e==="uncommon-u16-10"?ge(r)*10:e==="uncommon-u8"?U(r):typeof e=="number"?e:null,pf=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 gf extends Rt{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 pr,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),p(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,Ye);if(v(t)&&(t=await t),!t){this.lastSampleLoaded=!0;return}const i=Bt(t);if(!i)break;let n=this.reader.requestSlice(t.filePos,i.size);v(n)&&(n=await n),p(n),Dn(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(v(t)&&(t=await t),e+=4,t===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);p(t);const i=U(t),n=bt(t),s=(i&128)!==0;switch(i&127){case It.STREAMINFO:{let o=this.reader.requestSlice(e,n);if(v(o)&&(o=await o),p(o),o===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const c=N(o,34),l=new H(c),u=l.readBits(16),d=l.readBits(16),f=l.readBits(24),h=l.readBits(24),g=l.readBits(20),m=l.readBits(3)+1;l.readBits(5);const w=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:g,totalSamples:w,minimumBlockSize:u,maximumBlockSize:d,minimumFrameSize:f,maximumFrameSize:h,description:y},this.trackBacking=new wf(this);break}case It.VORBIS_COMMENT:{let o=this.reader.requestSlice(e,n);v(o)&&(o=await o),p(o),xs(N(o,n),this.metadataTags);break}case It.PICTURE:{let o=this.reader.requestSlice(e,n);v(o)&&(o=await o),p(o);const c=R(o),l=R(o),u=Ue.decode(N(o,l)),d=R(o),f=Ue.decode(N(o,d));o.skip(16);const h=R(o),g=N(o,h);this.metadataTags.images??=[],this.metadataTags.images.push({data:g,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}){p(this.audioInfo);const i=6,n=16,s=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+n+2,o=this.audioInfo.minimumFrameSize||s,l=(this.audioInfo.maximumFrameSize||a)+n,u=await this.reader.requestSliceRange(e,n,l);if(!u)return null;const d=this.readFlacFrameHeader({slice:u,isFirstPacket:t});if(!d)return null;for(u.filePos=e+o;;){if(u.filePos>u.end-i)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:u.end-e,isLastFrame:!0};if(U(u)===255){const h=u.filePos,g=U(u),m=this.blockingBit===1?249:248;if(g!==m){u.filePos=h;continue}u.skip(-2);const w=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:w,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,n=N(e,4),s=new H(n);if(s.readBits(15)!==32764)return null;if(this.blockingBit===null){p(t);const w=s.readBits(1);this.blockingBit=w}else if(this.blockingBit===1){if(p(!t),s.readBits(1)!==1)return null}else if(this.blockingBit===0){if(p(!t),s.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=Sl(s.readBits(4));if(!o)return null;p(this.audioInfo);const c=hf(s.readBits(4),this.audioInfo.sampleRate);if(!c||(s.readBits(4),s.readBits(3),s.readBits(1)!==0))return null;const u=Al(e),d=xl(e,o),f=mf(e,c);if(f===null||f!==this.audioInfo.sampleRate)return null;const h=e.filePos-i,g=U(e);e.skip(-h),e.skip(-1);const m=pf(N(e,h));return g!==m?null:{num:u,blockSize:d,sampleRate:f}}async advanceReader(){await this.readMetadata(),p(this.lastLoadedPos!==null),p(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 wf{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return p(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Ie}getTimeResolution(){return p(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 p(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Ft}}async getDecoderConfig(){return p(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(p(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const n=X(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(n===-1){await this.demuxer.advanceReader();continue}const s=this.demuxer.loadedSamples[n],a=s.blockOffset/this.demuxer.audioInfo.sampleRate,o=s.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(n,t)}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const n=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&n>=this.demuxer.loadedSamples.length)return null;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let n;if(t.metadataOnly)n=Qe;else{let o=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(v(o)&&(o=await o),!o)return null;n=N(o,i.byteSize)}p(this.demuxer.audioInfo);const s=i.blockOffset/this.demuxer.audioInfo.sampleRate,a=i.blockSize/this.demuxer.audioInfo.sampleRate;return new te(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 He=9e4,di=2**33,Oe=188,Pl=r=>{let e="video/MP2T";const t=[...new Set(r.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};const Cl="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.",mo=5,yf=1212435798,bf=1212436562,kf=1146376960,Tf=new Set([133,134,162]),po=new Set;class Sf extends Rt{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.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{const e=Oe+16+1;let t=this.reader.requestSlice(0,e);v(t)&&(t=await t),p(t);const i=N(t,e);
1if(i[0]===71&&i[Oe]===71)this.packetOffset=0,this.packetStride=Oe;else if(i[0]===71&&i[Oe+16]===71)this.packetOffset=0,this.packetStride=Oe+16;else if(i[4]===71&&i[4+Oe+4]===71)this.packetOffset=4,this.packetStride=Oe+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 w=new H(u.payload),y=w.readAlignedByte();w.skipBits(8*y),h=w.readBits(8)===2}if(u.pid===0&&!o){const m=new H(u.payload),w=m.readAlignedByte();m.skipBits(8*w),m.skipBits(14);const y=m.readBits(10);for(m.skipBits(40);8*(y+d)-m.pos>f;){const b=m.readBits(16);m.skipBits(3);const k=m.readBits(13);if(b!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=k}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((u.pid===a||h)&&!c){const m=new H(u.payload),w=m.readAlignedByte();m.skipBits(8*w),m.skipBits(12);const y=m.readBits(12);m.skipBits(43),m.readBits(13),m.skipBits(6);const b=m.readBits(10),k=m.pos+8*b;let S=!1;for(;m.pos<k;){const T=m.readBits(8),A=m.readBits(8),P=m.pos+8*A;if(T===mo&&A>=4){const C=m.readBits(32);S||=C===yf||C===bf}m.pos=P}for(m.pos=k;8*(y+d)-m.pos>f;){const T=m.readBits(8);m.skipBits(3);const A=m.readBits(13);m.skipBits(6);const P=m.readBits(10),C=m.pos+8*P;let x=!1,I=!1,E=!1;for(;m.pos<C;){const z=m.readBits(8),V=m.readBits(8),j=m.pos+8*V;if(z===106)x=!0;else if(z===122||z===204)I=!0;else if(z===123)E=!0;else if(z===mo&&V>=4){const oe=m.readBits(32);E||=(oe&4294967040)===kf}m.pos=j}let F=null;const D=S&&Tf.has(T)?130:T;switch(D){case 27:case 36:F={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 z;D===3||D===4?z="mp3":D===15?z="aac":D===129?z="ac3":D===135?z="eac3":z="dts",F={type:"audio",codec:z,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:I?F={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:x?F={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:E&&(F={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:po.has(T)||(O._warn(`Note: MPEG-TS streams with stream_type 0x${T.toString(16)} are not currently supported.`),po.add(T))}F&&this.elementaryStreams.push({demuxer:this,pid:A,streamType:T,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:F,referencePesPackets:[]})}c=!0}else{const m=this.elementaryStreams.find(w=>w.pid===u.pid);e:if(m&&!m.initialized){const w=_r(this,u,!0);if(!w)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 k=(await this.input._initInput._getDemuxer()).elementaryStreams.find(S=>S.pid===u.pid&&S.info.codec===m.info.codec);if(k){m.info=k.info,m.initialized=!0;break e}}const y=new oi(m,w);if(m.info.type==="video"){for(;;){const b=y;if(b.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=xn(y.suppliedPacket.data),!m.info.avcCodecInfo)continue;const k=m.info.avcCodecInfo.sequenceParameterSets[0];p(k);const S=bi(k);m.info.width=S.displayWidth,m.info.height=S.displayHeight;const T=S.pixelAspectRatio.num,A=S.pixelAspectRatio.den;T>0&&A>0&&(T>A?(m.info.squarePixelWidth=Math.round(m.info.width*T/A),m.info.squarePixelHeight=m.info.height):(m.info.squarePixelWidth=m.info.width,m.info.squarePixelHeight=Math.round(m.info.height*A/T))),m.info.colorSpace
vendor: 4,558 bytes, line 1
1={primaries:St[S.colourPrimaries],transfer:At[S.transferCharacteristics],matrix:xt[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=Pn(y.suppliedPacket.data),!m.info.hevcCodecInfo)continue;const S=m.info.hevcCodecInfo.arrays.find(A=>A.nalUnitType===ae.SPS_NUT).nalUnits[0];p(S);const T=ca(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:St[T.colourPrimaries],transfer:At[T.transferCharacteristics],matrix:xt[T.matrixCoefficients],fullRange:!!T.fullRangeFlag},m.info.reorderSize=T.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}m.info.decoderConfig={codec:ha({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 b=De.tempFromBytes(y.suppliedPacket.data),k=vt(b);if(!k)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");m.info.aacCodecInfo={isMpeg2:!1,objectType:k.objectType},m.info.numberOfChannels=Wr[k.channelConfiguration],m.info.sampleRate=Qt[k.samplingFrequencyIndex]}else if(m.info.codec==="mp3"){const b=R(De.tempFromBytes(y.suppliedPacket.data)),k=ki(b,y.suppliedPacket.data.byteLength);if(!k.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");m.info.numberOfChannels=Ti(k.header.channel),m.info.sampleRate=k.header.sampleRate}else if(m.info.codec==="ac3"){const b=Vc(y.suppliedPacket.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=ua[b.acmod]+b.lfeon,m.info.sampleRate=Sn[b.fscod]}else if(m.info.codec==="eac3"){const b=Lc(y.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const k=qc(b);if(k===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");m.info.numberOfChannels=Hc(b),m.info.sampleRate=k}else if(m.info.codec==="dts"){const b=fa(y.suppliedPacket.data);if(!b)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");m.info.numberOfChannels=b.numberOfChannels,m.info.sampleRate=b.sampleRate,b.core&&(m.info.dtsFormat=b.hasExtensions?"dtsh":"dtsc")}else throw new Error("Unhandled.");m.info.decoderConfig={codec:ma({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 Af(l)):this.trackBackingEntries.push(new xf(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 Pl(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),g=!!(f.adaptationFieldControl&1);let m=0;if(h&&(m=1+f.body[0],f===c&&m>1&&(u=f.body[1]>>6&1)),g&&(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(Ei(this.sectionEndPositions,n,y=>y)!==-1){l=!1;break}}if(l){const f=X(this.sectionEndPositions,n,h=>h);this.sectionEndPositions.splice(f+1,0,n)}if(!c)return null;let d;if(a.length===1)d=a[0];else{const f=a.reduce((g,m)=>g+m.length,0);d=new Uint8Array(f);let h=0;for(const g of a)d.set(g,h),h+=g.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(v(t)&&(t=await t),!t)return null;if(U(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const n=ge(t),s=n>>14&1,a=n&8191,c=U(t)>>4&3;return{payloadUnitStartIndicator:s,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,Oe);if(v(t)&&(t=await t),!t)return null;const i=N(t,Oe);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)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const n=60*He;this.timestampWrapInfo={reference:e-n,offset:e>=di-n?-di:di}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e<t?e+i:e}}const Zt=(r,e,t)=>{if(e.payload.byteLength<3)return null;const i=new H(e.payload);if(i.readBits(24)!==1)return null;const s=i.readBits(8);if(i.skipBits(16),s===188||s===190||s===191||s===240||s===241||s===255||s===242||s===248)return null;i.skipBits(8);const a=i.readBits(2);i.skipBits(14);let o=null;if(a===2||a===3)o=0,i.skipBits(4),o+=i.readBits(3)*(1<<30),i.skipBits(1),o+=i.readBits(15)*32768,i.skipBits(1),o+=i.readBits(15),o=r.normalizeTimestamp(o);else if(t)throw new Error(Cl);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:o,randomAccessIndicator:e.randomAccessIndicator}},_r=(r,e,t)=>{p(e.endPos!==null);const i=Zt(r,e,t);if(!i)return null;const n=new H(e.payload);n.skipBits(32);const s=n.readBits(16),a=6;n.skipBits(16);const o=n.readBits(8),c=n.pos+8*o;n.pos=c;const l=c/8;p(Number.isInteger(l));const u=e.payload.subarray(l,s>0?a+s:e.payload.byteLength);return{...i,data:u}};class vn{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++,p(n instanceof vn),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 Ie}getDisposition(){return{...Ft,primary:!1}}getTimeResolution(){return He}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 te(i.metadataOnly?Qe:e.data,n,e.pts/He,Math.max(t/He,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;p(t);const i=_r(this.elementaryStream.demuxer,t,!0);p(i);const n=new oi(this.elementaryStream,i),s=new $n(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 s=this.elementaryStream.demuxer,a=await s.readSection(n,!0);p(a);const o=_r(s,a,!0);p(o);const c=new oi(this.elementaryStream,o);i=new $n(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=pi(e*He),s=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=s,c=this.elementaryStream.pid,l=async(S,T,A)=>{let P=S;for(;P<T;){const C=await s.readPacketHeader(P);if(!C)return null;if(C.pid===c&&C.payloadUnitStartIndicator===1){const x=await s.readSection(P,A);if(!x)return null;const I=Zt(s,x,!1);if(I&&I.pts!==null)return{pesPacketHeader:I,section:x}}P+=s.packetStride}return null},u=this.elementaryStream.firstSection;p(u);const d=Zt(s,u,!0);if(p(d),n<d.pts)return null;let f;const h=this.elementaryStream.referencePesPackets,g=X(h,n,S=>S.pts),m=g!==-1?h[g]:null;if(m&&n-m.pts<He/2)f=m.sectionStartPos;else{let S=0;if(a.fileSize!==null){const T=Math.ceil(a.fileSize/o);if(T>1){let A=0,P=T-1;for(S=A;A<=P;){const C=Math.floor((A+P)/2),x=On(C*o,s.packetStride)+d.sectionStartPos,I=x+o,E=await l(x,I,!1);if(!E){P=C-1;continue}E.pesPacketHeader.pts<=n?(S=C,A=C+1):P=C-1}}}f=On(S*o,s.packetStride)+d.sectionStartPos}let y=(await l(f,a.fileSize??1/0,!1))?.pesPacketHeader??null;y||(y=d);const b=this.getReorderSize(),k=async(S,T)=>{const A=await s.readSection(S,!0);p(A);const P=_r(s,A,!0);p(P);const C=new oi(this.elementaryStream,P),x=new $n(this,C);for(;!((ue(x.presentationOrderPackets)?.pts??-1/0)>=n||!await x.readNextPacket()););const I=wn(x.presentationOrderPackets,T);if(I===-1)return null;const E=x.presentationOrderPackets[I],F=I===0?0:E.pts-x.presentationOrderPackets[I-1].pts;for(;x.decodeOrderPackets[0]!==E;)x.decodeOrderPackets.shift();x.lastDuration=F;const D=await x.readNext();p(D);const z=this.createEncodedPacket(D.packet,D.duration,i);return this.packetBuffers.set(z,x),this.packetSectionStarts.set(z,D.packet.sectionStartPos),z};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 A=await s.readSection(S,!1);if(A){const P=Zt(s,A,!1);if(P&&P.pts!==null){if(P.pts>n)break e;y=P,Ds(this.elementaryStream,y);break}}}S+=s.packetStride}}e:for(let S=0;S<b+1;S++){let T=y.sectionStartPos-s.packetStride;for(;T>=s.packetOffset;){const A=await s.readPacketHeader(T);if(!A)break e;if(A.pid===c&&A.payloadUnitStartIndicator===1){const P=await s.readSection(T,!1);if(P){const C=Zt(s,P,!1);if(C&&C.pts!==null){y=C;break}}}T-=s.packetStride}}return k(y.sectionStartPos,S=>S.pts<=n)}else{let S=f,T=null;const A=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let P=null;const C=S<=d.sectionStartPos;let x,I=null;if(C)x=d,I=u;else{const D=await l(S,a.fileSize??1/0,A);x=D?.pesPacketHeader??null,I=D?.section??null}let E=!1,F=0;e:for(;x&&!(T!==null&&x.sectionStartPos>=T);){if(x.pts<=n){let z;if(this.elementaryStream.canBeTrustedWithKeyPackets)z=x.randomAccessIndicator===1;else{p(I);const V=_r(s,I,!0);p(V);const j=new oi(this.elementaryStream,V);await j.markNextPacket(),z=j.suppliedPacket?.randomAccessIndicator===1}z&&(P=x)}if(x.pts>n&&(E=!0),E&&(F++,F>b))break;let D=x.sectionStartPos+s.packetStride;for(;;
1){const z=await s.readPacketHeader(D);if(!z)break e;if(z.pid===c&&z.payloadUnitStartIndicator===1){const V=await s.readSection(D,A);if(V){const j=Zt(s,V,!1);if(j&&j.pts!==null){x=j,I=V,Ds(this.elementaryStream,x);break}}}D+=s.packetStride}}if(P){let D=P;if(F===0)e:for(let V=0;V<b;V++){let j=D.sectionStartPos-s.packetStride;for(;j>=s.packetOffset;){const oe=await s.readPacketHeader(j);if(!oe)break e;if(oe.pid===c&&oe.payloadUnitStartIndicator===1){const re=await s.readSection(j,A);if(re){const $=Zt(s,re,!1);if($&&$.pts!==null){D=$;break}}}j-=s.packetStride}}const z=await k(D.sectionStartPos,V=>V.pts<=n&&V.randomAccessIndicator===1);return p(z),z}if(C)return null;T=S,S=Math.max(On(S-d.sectionStartPos-o,s.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class Af extends vn{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}getTransformationMatrix(){return[...hi]}async getColorSpace(){return this.elementaryStream.info.colorSpace}
1async canBeTransparent(){return!1}async getDecoderConfig(){return p(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class xf extends vn{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return p(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Ds=(r,e)=>{const t=r.referencePesPackets,i=X(t,e.sectionStartPos,n=>n.sectionStartPos);if(i>=0){const n=t[i];if(e.pts<=n.pts)return!1;const s=r.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-n.sectionStartPos<s)return!1;if(i<t.length-1){const a=t[i+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<s)return!1}}return t.splice(i+1,0,e),!0};class oi{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 p(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=ue(this.pesPackets).sectionEndPos;for(p(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=_r(this.demuxer,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(){p(!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(v(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 g=l+f;if(f+3>=d){this.seekTo(g);break}const m=u[f+1],w=u[f+2],y=u[f+3];let b=0;if(m===0&&w===0&&y===1?b=4:m===0&&w===1&&(b=3),b===0){f++;continue}const k=g;s??=k;const S=f+b,T=S+n,A=6;if(T+(t==="avc"?A:1)>d){this.seekTo(g);break}const C=u[S];let x,I,E;if(t==="avc")x=dr(C),I=x===ye.NON_IDR_SLICE||x===ye.SLICE_DPA||x===ye.IDR,E=x===ye.SEI||x===ye.SPS||x===ye.PPS||x===ye.AUD;else{if(x=Gt(C),((C&1)<<5|u[S+1]>>3)>0){f+=b;continue}I=x<=ae.RASL_R||x>=ae.BLA_W_LP&&x<=21,E=x>=ae.VPS_NUT&&x<=37||x===ae.PREFIX_SEI_NUT||x>=41&&x<=44||x>=48&&x<=55}let F=!1;if(I){let D;if(t==="avc"){const z=u.subarray(T,T+A),V=M(new H(z));D=!a||V<=o,o=V}else D=u[T]>>7===1;D&&(a?F=!0:a=!0)}else E&&a&&(F=!0);if(F){const D=k-s;return this.seekTo(s),this.supplyPacket(D,0)}f+=b}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);v(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(Kt);if(v(c)&&(c=await c),c<Kt)return;const l=this.readBytes(Kt),u=vt(De.tempFromBytes(l));if(u){this.seekTo(o);let d=this.ensureBuffered(u.frameLength);
1return v(d)&&(d=await d),this.supplyPacket(d,Math.round(un*He/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(lr);if(v(c)&&(c=await c),c<lr)return;const l=this.readBytes(lr),u=q(l).getUint32(0),d=ki(u,null);if(d.header){this.seekTo(o);let f=this.ensureBuffered(d.header.totalSize);v(f)&&(f=await f);const h=d.header.audioSamplesInFrame*He/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(v(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=ud[3*d+u];p(f!==void 0),this.seekTo(o),c=this.ensureBuffered(f),v(c)&&(c=await c);const h=Math.round(dd*He/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(v(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,g=Wc[h];this.seekTo(o),c=this.ensureBuffered(d),v(c)&&(c=await c);const m=g*256,w=Math.round(m*He/e.info.sampleRate);return this.supplyPacket(c,w)}else if(t==="dts"){if(a!==127&&a!==100)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Gi);if(v(c)&&(c=await c),c<Gi)return;const l=this.readBytes(Gi),u=Qc(l);let d=u?null:$i(l);if(!u&&!d){this.seekTo(o+1);continue}if(d&&!d.asset){this.seekTo(o);const m=Math.min(d.frameSize,md);let w=this.ensureBuffered(m);v(w)&&(w=await w),d=$i(this.readBytes(w))??d}let f=u?u.frameSize:d.frameSize;if(u){let m=Math.ceil(u.frameSize/4)*4;for(;;){this.seekTo(o);const w=m+Cs;let y=this.ensureBuffered(w);if(v(y)&&(y=await y),y<w)break;this.seekTo(o+m);const b=$i(this.readBytes(Cs));if(!b)break;m+=b.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),v(c)&&(c=await c);const g=Math.round(h*He/e.info.sampleRate);return this.supplyPacket(c,g)}else throw new Error("Unhandled.")}if(n<i)break}}}supplyPacket(e,t){const i=this.getCurrentPesPacket();let n;if(this.lastSuppliedPesPacket===i)p(this.nextPts!==null),n=this.nextPts;else{if(i.pts===null)throw new Error(Cl);n=i.pts,Ds(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=_n(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 $n{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(),p(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);p(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(p(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)=>
1e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const Rr="application/vnd.apple.mpegurl",go="#EXT-X-STREAM-INF:",wo="#EXT-X-I-FRAME-STREAM-INF:",yo="#EXT-X-MEDIA:",zs="#EXTINF:",bo="#EXT-X-MAP:",ko="#EXT-X-KEY:",To="#EXT-X-MEDIA-SEQUENCE:",So="#EXT-X-BYTERANGE:",Ao="#EXT-X-PROGRAM-DATE-TIME:",Pf="#EXT-X-DISCONTINUITY",xo="#EXT-X-TARGETDURATION:",Cf="#EXT-X-ENDLIST",Po="#EXT-X-PLAYLIST-TYPE:",_f="#EXT-X-I-FRAMES-ONLY",_l=r=>r.length===0||r.startsWith("#")&&!r.startsWith("#EXT");class fi{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 If{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=ni(e,n=>n.getType()==="video")+1;e.push(new Co(this,t,i))}else if(t.type==="audio"){const i=ni(e,n=>n.getType()==="audio")+1;e.push(new _o(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=ni(e,a=>a.getType()==="video")+1;e.push(new Co(this,{id:e.length+1,type:"video"},s))}else if(n.type==="audio"){const s=ni(e,a=>a.getType()==="audio")+1;e.push(new _o(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 Il{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(),p(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){p(e.sequenceNumber>=0),p(this.segmentedInput.firstSegment);const n=await this.segmentedInput.getMediaOffset(t,i.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:Dr(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(),p(this.firstInputTrack),p(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 Co extends Il{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())}getTransformationMatrix(){return this.delegate(()=>this.firstInputTrack._backing.getTransformationMatrix())}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 _o extends Il{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())}}const dn=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));ea();const Io=typeof dn<"u"?dn:void 0,El=0,vl=1/0;let Os=null;typeof FinalizationRegistry<"u"&&(Os=new FinalizationRegistry(r=>{r()}));class $e extends vi{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 Me;return this._sizePromise??=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,El,vl),e=this._getFileSize(),p(e!==void 0)),e})()}async getSize(){if(this._disposed)throw new Me;
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 Mf(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new ba(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,this._refCount===0&&(this._dispose(),this._disposed=!0)}}class ba{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;p(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class gr extends $e{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 $e||n instanceof ba))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const s=n instanceof $e?n.ref():n;return s.source._usedForHls||=this._usedForHls,s};return v(t)?t.then(i):i(t)}}const Eo=(r,e)=>r.path===e.path;class Ef extends gr{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 $e?o.ref():o;return this._root=c,this._rootRequest=null,c};v(s)?this._rootRequest=s.then(a):(a(s),p(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())}}class Kp extends $e{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=se(e),this._view=q(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}const vo=typeof FinalizationRegistry<"u"?new FinalizationRegistry(r=>{r.cancel().catch(()=>{})}):null;class Qp extends $e{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&&(!Ke(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.");if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Ta({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),vo?.unregister(i),n.cancel().catch(()=>{}))},prefetchProfile:ka.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}
1_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,n){return this._orchestrator.read(e,t,i,n)}async _runWorker(e){p(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!vr()&&this._options.useStreamReader!==!1?(t=this._blob.slice(e.currentPos).stream().getReader(),vo?.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._orchestrator.supplyWorkerData(e,new Uint8Array(i))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel().catch(()=>{})}_dispose(){this._orchestrator.dispose()}}const vf=.5*2**20,Bf=((r,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let n=null;try{typeof window<"u"&&typeof window.location<"u"&&(n=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&n!==null&&n!==window.location.origin)return O._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(r-2),16)}),Bo=new Set;class Bl extends gr{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Ke(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");if(t.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");const i=e instanceof Request?e.url:e instanceof URL?e.href:e;super(i,a=>new Bl(a.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._abortControllers=new Map,this._sequentialAbortController=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Bf,this._requestInit={...t.requestInit};let n=null;if(t.requestInit?.headers){const a={...bs(t.requestInit.headers)},o=Object.keys(a).find(c=>c.toLowerCase()==="range");o!==void 0&&(n=a[o],delete a[o],this._requestInit.headers=a)}if(e instanceof Request){const a=e.headers.get("Range");if(a!==null){n??=a;const o=new Request(e);o.headers.delete("Range"),this._url=o}}if(n!==null){const a=Rf(n);a&&(this._offset=a.offset,this._length=a.length)}const s=2;this._orchestrator=new Ta({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:a=>this._abortControllers.delete(a),prefetchProfile:ka.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return this._length!==null?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return e===null?this._length!==null?this._length:null:le(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._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+t):this._orchestrator.read(s+e,s+t,Math.max(s+i,s),s+Math.min(n,this._length??1/0)),o=c=>c?(c.offset-=this._offset,c):null;return v(a)?a.then(o):o(a)}async _runWorker(e){for(;;
1){if(e.aborted){this._orchestrator.signalWorkerStoppedRunning(e);return}const t=new AbortController;this._abortControllers.set(e,t);const i=await qa(this._options.fetchFn??fetch,this._url,La(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>t.signal.aborted);if(!i.ok)throw new Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);i.redirected&&(this.rootPath=i.url);e:if(this._orchestrator.fileSize===null&&!i.headers.has("Content-Encoding")&&(i.status===206||i.type==="basic")){const s=i.headers.get("Content-Range");if(s){const o=/\/(\d+)/.exec(s);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=i.headers.get("Content-Length");if(a){const o=i.status===206?e.currentPos:0;this._orchestrator.supplyFileSize(o+Number(a))}}if(this._fileSizeDetermined=!0,!i.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(i.status!==206){if(this._sequentialBacking){i.body.cancel().catch(()=>{});return}if(!this._usedForHls){const s=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);s.origin!=="null"&&!(s.pathname.endsWith(".m3u8")||s.pathname.endsWith(".m3u"))&&(Bo.has(s.origin)||(O._warn(`HTTP server (origin ${s.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),Bo.add(s.origin)))}this._abortControllers.delete(e),this._transitionToSequentialMode(i.body,t);return}const n=i.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let s;try{s=await n.read()}catch(c){if(t.signal.aborted)throw c;const l=this._getRetryDelay(1,c,this._url);if(l!==null){O._error("Error while reading response stream. Attempting to resume.",c),await wi(1e3*l);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=s;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_transitionToSequentialMode(e,t){this._sequentialAbortController=t;let i=e.getReader(),n=0,s=0;const a=new ReadableStream({pull:async l=>{for(;;){let u;try{u=await i.read()}catch(f){if(this._disposed)throw f;const h=this._getRetryDelay(1,f,this._url);if(h===null)throw f;O._error("Error while reading response stream. Attempting to resume.",f),await wi(1e3*h),this._sequentialAbortController=new AbortController,this._disposed&&this._sequentialAbortController.abort();const g=await qa(this._options.fetchFn??fetch,this._url,La(this._requestInit,{headers:{Range:`bytes=${n}-`},signal:this._sequentialAbortController.signal}),this._getRetryDelay,()=>this._disposed);if(!g.ok)throw new Error(`Error fetching ${String(this._url)}: ${g.status} ${g.statusText}`);if(!g.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");i=g.body.getReader(),s=g.status===206?0:n;continue}if(u.done){l.close();return}let d=u.value;if(s>0){const f=Math.min(s,d.length);s-=f,d=d.subarray(f)}if(d.length!==0){n+=d.length,l.enqueue(d);return}}},cancel:()=>i.cancel().catch(()=>{})}),o=new Ml(a,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});o._endIndex=this._orchestrator.fileSize,o._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",o.on("read",({start:l,end:u})=>this._dispatchRead(l,u)),this._sequentialBacking=o;const c=new Set;
1for(const l of this._orchestrator.workers){for(const u of l.pendingSlices)c.add(u);l.aborted=!0,l.pendingSlices.length=0}for(const l of this._orchestrator.queuedReads)for(const u of l.pendingSlices)c.add(u);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const[,l]of this._abortControllers)l.abort();this._abortControllers.clear();for(const l of c){const u=o._read(l.start,l.start+l.bytes.length);v(u)?u.then(d=>{d?(p(d.offset===l.start),l.resolve(d.bytes)):l.resolve(null)},d=>l.reject(d)):(p(u===null),l.resolve(null))}}_dispose(){this._orchestrator.dispose();for(const[,e]of this._abortControllers)e.abort();this._abortControllers.clear(),this._sequentialAbortController?.abort(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Ff=/^bytes=(\d+)-(\d*)$/,Rf=r=>{const e=Ff.exec(r.trim());if(!e)return null;const t=Number(e[1]),i=e[2]===""?null:Number(e[2]);return i!==null&&i<t?null:{offset:t,length:i!==null?i-t+1:null}};class Fl extends gr{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Ke(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Io.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,i=>new Fl(i.path,t)),this._fileHandle=null,this._customSource=new Rl({getSize:async()=>{const i=await Io.fs.open(e,"r");return this._fileHandle=i,Os?.register(this,()=>{i.close()},this),(await i.stat()).size},read:async(i,n)=>{p(this._fileHandle);const s=new Uint8Array(n-i);return await this._fileHandle.read(s,0,n-i,i),s},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem",handleUnhandledError:t.handleUnhandledError})}_read(e,t,i,n){return this._customSource._read(e,t,i,n)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,Os?.unregister(this))}}class Rl extends $e{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.handleUnhandledError!==void 0&&typeof e.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!Ke(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._readers=new Set,this._options=e,this._orchestrator=new Ta({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:ka[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this),handleUnhandledError:e.handleUnhandledError})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,i,n){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,i,n);const s=this._options.getSize();if(v(s))return s.then(a=>{if(!Number.isInteger(a)||a<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=a,this._orchestrator.read(e,t,i,n)});if(!Number.isInteger(s)||s<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=s,this._orchestrator.read(e,t,i,n)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,i=e.targetPos;let n=this._options.read(e.currentPos,i);if(v(n)&&(n=await n),e.aborted){n instanceof ReadableStream&&await n.cancel().catch(()=>{});break}if(n instanceof Uint8Array){if(n=se(n),n.length!==i-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${i-e.currentPos} bytes, but got ${n.length}.`);
1this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}else if(n instanceof ReadableStream){const s=n.getReader();this._readers.add(s);try{for(;e.currentPos<i&&!e.aborted;){const{done:a,value:o}=await s.read();if(a){if(e.currentPos<i)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${i-t} bytes, but got ${e.currentPos-t}`);break}if(!(o instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const c=se(o);this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}finally{this._readers.delete(s),s.releaseLock()}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){this._orchestrator.dispose();for(const e of this._readers)e.cancel().catch(()=>{});this._readers.clear(),this._options.dispose?.()}}const Gp=Rl;class Ml extends $e{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.handleUnhandledError!==void 0&&typeof t.handleUnhandledError!="function")throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Ke(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,this._handleUnhandledError=t.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=X(this._cache,e,u=>u.start),n=i!==-1?this._cache[i]:null;if(n&&n.start<=e&&t<=n.end)return{bytes:n.bytes,view:n.view,offset:n.start};let s=e;const a=new Uint8Array(t-e);if(i!==-1)for(let u=i;u<this._cache.length;u++){const d=this._cache[u];if(d.start>=t)break;const f=Math.max(e,d.start);f>s&&this._throwDueToCacheMiss();const h=Math.min(t,d.end);f<h&&(a.set(d.bytes.subarray(f-d.start,h-d.start),f-e),s=h)}if(s===t)return{bytes:a,view:q(a),offset:e};this._currentIndex>s&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:l}=ne();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 if(this._handleUnhandledError)this._handleUnhandledError(u);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:q(a.bytes),offset:a.start}),this._pendingSlices.splice(s,1),s--))}for(this._cache.push({start:i,end:n,bytes:t,view:q(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 Me);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel().catch(()=>{})}}const ka={none:(r,e)=>({start:r,end:e}),fileSystem:(r,e)=>(r=Math.floor((r-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:r,end:e}),network:(r,e,t)=>{r=Math.max(0,Math.floor((r-65536)/65536)*65536);for(const n of t){const a=Math.max((n.startPos+n.targetPos)/2,n.targetPos-8388608);if(Ts(r,e,a,n.targetPos)){const o=n.targetPos-n.startPos,c=Math.ceil((o+1)/8388608)*8388608,l=2**Math.ceil(Math.log2(o+1)),u=Math.min(l,c);e=Math.max(e,n.startPos+u)}}return e=Math.max(e,r+vf),{start:r,end:e}}};class Ta{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){p(!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);p(a<=e&&t<=o);let c=null;const l=X(this.cache,e,T=>T.start),u=l!==-1?this.cache[l]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,c={bytes:u.bytes,view:u.view,offset:u.start});const d=X(this.cache,a,T=>T.start),f=c?null:new Uint8Array(t-e);let h=0,g=a;const m=[];
1if(d!==-1){for(let T=d;T<this.cache.length;T++){const A=this.cache[T];if(A.start>=o)break;if(A.end<=a)continue;const P=Math.max(a,A.start),C=Math.min(o,A.end);if(p(P<=C),g<P&&m.push({start:g,end:P}),g=C,f){const x=Math.max(e,A.start),I=Math.min(t,A.end);if(x<I){const E=x-e;f.set(A.bytes.subarray(x-A.start,I-A.start),E),E===h&&(h=I-e)}}A.age=this.nextAge++}g<o&&m.push({start:g,end:o})}else m.push({start:a,end:o});if(f&&h>=f.length&&(c={bytes:f,view:q(f),offset:e}),m.length===0)return p(c),c;const{promise:w,resolve:y,reject:b}=ne(),k=[];for(const T of m){const A=Math.max(e,T.start),P=Math.min(t,T.end);A===T.start&&P===T.end?k.push(T):A<P&&k.push({start:A,end:P})}const S=f&&{start:e,bytes:f,holes:k,resolve:y,reject:b};e:for(const T of m){for(const C of this.workers)if(this.checkHoleAgainstWorker(C,T,S?[S]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}const A=T.end<o||this.fileSize!==null,P=this.createWorker(T.start,T.end,A);if(P)S&&(P.pendingSlices=[S]),this.runWorker(P);else{let C=X(this.queuedReads,T.start,I=>I.hole.start),x=C!==-1?this.queuedReads[C]:null;for(x&&T.start<=x.hole.end?(x.hole.end=Math.max(x.hole.end,T.end),x.strictTarget&&=A,S&&x.pendingSlices.push(S)):(C++,x={hole:{start:T.start,end:T.end},strictTarget:A,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(C,0,x));C+1<this.queuedReads.length;){const I=this.queuedReads[C+1];if(I.hole.start>x.hole.end)break;x.hole.end=Math.max(x.hole.end,I.hole.end),x.pendingSlices.push(...I.pendingSlices),x.strictTarget&&=I.strictTarget,x.age=Math.min(x.age,I.age),this.queuedReads.splice(C+1,1)}}}return c?w.catch(T=>{if(!this.disposed)if(this.options.handleUnhandledError)this.options.handleUnhandledError(T);else throw T}):(p(f),c=w.then(T=>T&&{bytes:T,view:q(T),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(Ts(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)p(a!==null),p(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){p(!e.running),p(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)if(this.options.handleUnhandledError)this.options.handleUnhandledError(t);else 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){p(!e.aborted);const i=e.currentPos,n=i+t.length;this.insertIntoCache({start:i,end:n,bytes:t,view:q(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||Ts(i,n,a.currentPos,a.targetPos)&&(this.workers.splice(s,1),this.options.onIdleWorkerRemoved?.(a),s--)}}supplyFileSize(e){p(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);p(t!==-1),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=X(this.cache,e.start,i=>i.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const n=new Uint8Array(e.end-i.start);n.set(i.bytes,0),n.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=n,i.view=q(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=q(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 Me);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 Me);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class Mf extends $e{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:le(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 v(s)?s.then(a):a(s)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}var Fo=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},Ro=(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 Df=/^0[xX][0-9a-fA-F]+$/,zf=/^data:.*;base64,/i;class Mo extends If{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 wi(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 k={stack:[],error:void 0,hasError:!1};
1try{const S=Fo(k,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),A=await new Yi(S.source).requestEntireFile();p(A),e=au(A,A.length,{ignore:_l}),S.source instanceof gr&&(this.rootPath=S.source.rootPath)}catch(S){k.error=S,k.hasError=!0}finally{Ro(k)}}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,g=null,m=!1,w=ue(this.segments)??null;const y=k=>{const S=k.indexOf("@"),T=Number(S===-1?k:k.slice(0,S));if(!Number.isInteger(T)||T<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${k}'.`);let A=null;if(S!==-1&&(A=Number(k.slice(S+1)),!Number.isInteger(A)||A<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${k}'.`);return{length:T,offset:A}},b=k=>{c=k,w&&(p(w.sequenceNumber!==null),w.sequenceNumber<k&&(n=w.timestamp+w.duration,l=w.firstSegment,u=w.initSegment,h=w.lastProgramDateTimeSeconds,s=w.unixEpochTimestamp!==null?w.unixEpochTimestamp+w.duration:null,w=null))};for(let k=0;k<e.length;k++){const S=e[k];if(!i){if(S!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0;continue}if(!S.startsWith("#")){if(!w){if(a===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let T=o;if(T&&T.method==="AES-128"&&!T.iv){const x=new Uint8Array(ut),I=q(x);I.setUint32(8,Math.floor(c/2**32)),I.setUint32(12,c),T={...T,iv:x}}const P={path:Be(this.rootPath,S),offset:f?.offset??0,length:f?.length??null},C={timestamp:n,unixEpochTimestamp:s,firstSegment:l,sequenceNumber:c,location:P,duration:a,encryption:T,initSegment:u,lastProgramDateTimeSeconds:h};l??=C,n+=a,s!==null&&(s+=a),this.segments.push(C)}a=null,f===null?d=null:f=null,b(c+1)}if(S.startsWith(zs)){if(w){m=!0;continue}m||(h===null&&c>0&&g!==null&&(n=c*g),m=!0);const T=S.slice(zs.length),A=T.indexOf(","),P=A===-1?T:T.slice(0,A),C=Number(P);if(!Number.isFinite(C)||C<0)throw new Error(`Invalid #EXTINF tag duration '${P}'.`);a=C}else if(S.startsWith(bo)){const T=new fi(S.slice(bo.length)),A=T.get("uri");if(!A)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const P=T.get("byterange");let C=null;if(P!==null&&(C=y(P)),C&&C.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!w){const I={path:Be(this.rootPath,A),offset:C?.offset??0,length:C?.length??null};if(o?.method==="AES-128"&&!o.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");u={timestamp:n,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:I,duration:0,encryption:o,initSegment:null,lastProgramDateTimeSeconds:h}}a=null,f===null?d=null:f=null}else if(S.startsWith(ko)){const T=new fi(S.slice(ko.length)),A=T.get("method");if(A==="NONE")o=null;else if(A==="AES-128"){const P=T.get("uri");if(!P)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let C=null;const x=T.get("iv");if(x){if(!Df.test(x))throw new Error(`Unsupported IV format '${x}'.`);let E=x.slice(2);E=E.padStart(2*ut,"0"),E=E.slice(-2*ut),C=new Uint8Array(ut);for(let F=0;F<ut;F++){const D=2*F;C[F]=parseInt(E.slice(D,D+2),16)}}const I=T.get("keyformat")??"identity";if(I!=="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:Be(this.rootPath,P),iv:C,keyFormat:I}}else if(A==="SAMPLE-AES"||A==="SAMPLE-AES-CTR"){const P=T.get("uri");if(!P)throw new Error(`Invalid #EXT-X-KEY: ${A} requires a URI attribute.`);if((T.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let x=null;if(zf.test(P)){const I=P.indexOf(","),E=rn(P.slice(I+1));if(E.length>=8&&E[4]===112&&E[5]===115&&E[6]===115&&E[7]===104){const F=q(E).getUint32(0);x=rl(E.subarray(8,Math.min(F,E.length)))}}o={method:A,psshBox:x}}else throw new Error(`Unsupported encryption method '${A}'. If you think this method should be supported, please raise an issue.`)}else if(S.startsWith(To)){const T=S.slice(To.length),A=Number(T);
1if(!Number.isInteger(A)||A<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${T}'.`);b(A)}else if(S.startsWith(So)){const T=y(S.slice(So.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(Ao)){if(w)continue;const T=S.slice(Ao.length),A=Date.parse(T);if(!Number.isFinite(A))continue;const P=A/1e3;if(h===P)continue;if(h===null&&this.segments.length>0){const C=ue(this.segments),x=C.timestamp+C.duration,I=P-x;for(const E of this.segments)E.unixEpochTimestamp=E.timestamp+I,t&&(E.timestamp=E.unixEpochTimestamp)}h=P,s=P,t&&(n=P)}else if(S===Pf)l=null;else if(S.startsWith(xo)){const T=S.slice(xo.length),A=Number(T);if(!Number.isFinite(A)||A<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${T}'.`);this.refreshInterval=A,g=A}else if(S===Cf){this.streamHasEnded=!0;break}else S.startsWith(Po)&&S.slice(Po.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const n=X(this.segments,e,a=>a.timestamp);if(n===-1)return null;if(n<this.segments.length-1||this.streamHasEnded||i)return this.segments[n];const s=this.segments[n];if(e<s.timestamp+s.duration)return s;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){const i=this.segments.indexOf(e);p(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 p(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=>il(d,u))&&(l=[...l,u]),this.input._formatOptions.isobmff.resolveKeyId({...c,psshBoxes:l})})}},a=new Mn({source:new Ef(t.location.path,async c=>{p(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;p(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 g=new Yi(h.source),m=qd(g,async()=>{const w={stack:[],error:void 0,hasError:!1};try{const y=Fo(w,await this.input._getSourceCached({path:f.keyUri,isRoot:!1},Mh),!1),k=await new Yi(y.source).requestSlice(0,ut);if(!k)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:N(k,ut),iv:f.iv}}catch(y){w.error=y,w.hasError=!0}finally{Ro(w)}},()=>{h.free()});u=new Ml(m).ref()}else p(!1);return u}),formats:this.input._formats.filter(c=>!(c instanceof Vl)),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=ta(this.inputCache,l=>l.age);p(c!==-1),this.inputCache.splice(c,1)}return a}
1async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class Of extends Rt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{p(this.input._rootSource instanceof gr);const e=await this.input._reader.requestEntireFile();p(e);const t=au(e,e.length,{ignore:_l}),{rootPath:i}=this.input._rootSource,n=[],s=[];for(let l=1;l<t.length;l++){const u=t[l];if(u.startsWith(go)){const d=l,f=t[++l];if(f===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const h=Be(i,f),g=new fi(u.slice(go.length));if(g.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:h,attributes:g,lineNumber:d,hasOnlyKeyPackets:!1})}else if(u.startsWith(wo)){const d=new fi(u.slice(wo.length)),f=d.get("uri");if(f===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(d.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 g=Be(i,f);n.push({fullPath:g,attributes:d,lineNumber:l,hasOnlyKeyPackets:!0})}else if(u.startsWith(yo)){const d=new fi(u.slice(yo.length));if(d.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(d.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let g=null;const m=d.get("uri");m!==null&&(g=Be(i,m)),s.push({fullPath:g,attributes:d,lineNumber:l})}else if(u!==_f){if(u.startsWith(zs)){const d=new Mo(this,i,null,t);this.segmentedInputs=[d],this.hasMasterPlaylist=!1,this.trackBackings=await d.getTrackBackings();return}}}const a=await Promise.all(n.map(async(l,u)=>{const d=[],f=l.attributes.get("codecs");let h;if(f)h=f.split(",").map(P=>P.trim());
1else{const C=await this.getSegmentedInputForPath(l.fullPath).getTrackBackings(),x=await Promise.all(C.map(async I=>({track:I,codec:await I.getCodec()})));h=await Promise.all(x.filter(I=>I.codec!==null).map(I=>I.track.getDecoderConfig().then(E=>E.codec)))}const g=l.attributes.get("video"),m=l.attributes.get("audio"),w=h.some(P=>we.includes(tt(P))),y=h.some(P=>xe.includes(tt(P)));if(g!==null&&!w){const P=s.find(C=>{const x=C.attributes.get("group-id"),I=C.attributes.get("type");return x===g&&I.toLowerCase()==="video"});e:if(P){const C=P.attributes.get("uri");if(C===null)break e;const x=Be(i,C),F=(await this.getSegmentedInputForPath(x).getTrackBackings()).find(z=>z.getType()==="video");if(!F||await F.getCodec()===null)break e;const D=await F.getDecoderConfig().then(z=>z?.codec??null);p(D!==null),h.push(D)}}if(m!==null&&!y){const P=s.find(C=>{const x=C.attributes.get("group-id"),I=C.attributes.get("type");return x===m&&I.toLowerCase()==="audio"});e:if(P){const C=P.attributes.get("uri");if(C===null)break e;const x=Be(i,C),F=(await this.get
1SegmentedInputForPath(x).getTrackBackings()).find(z=>z.getType()==="audio");if(!F||await F.getCodec()===null)break e;const D=await F.getDecoderConfig().then(z=>z?.codec??null);p(D!==null),h.push(D)}}h=[...new Set(h)];let b=null,k=null;const S=l.attributes.getAsNumber("bandwidth");p(S!==null);const T=l.attributes.getAsNumber("average-bandwidth"),A=l.attributes.get("name");for(const P of h){const C=tt(P);if(C!==null){if(we.includes(C)){if(b!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=P;const x=l.attributes.get("video");if(x===null){const I=l.attributes.get("resolution");let E=null,F=null;if(I){const D=I.match(/^(\d+)x(\d+)$/);D&&(E=Number(D[1]),F=Number(D[2]))}d.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Ie,lineNumber:l.lineNumber,fullPath:l.fullPath,fullCodecString:b,pairingMask:1n<<BigInt(u),peakBitrate:S,averageBitrate:T,name:A,hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"video",width:E,height:F}})}else for(const I of s){const E=I.attributes.get("group-id"),F=I.attributes.get("type");if(E!==x||F.toLowerCase()!=="video")continue;const D=I.attributes.get("resolution")??l.attributes.get("resolution");let z=null,V=null;if(D){const j=D.match(/^(\d+)x(\d+)$/);j&&(z=Number(j[1]),V=Number(j[2]))}d.push({id:-1,demuxer:this,backingTrack:null,default:Vi(I.attributes),autoselect:Vi(I.attributes)||Do(I.attributes),languageCode:zo(I.attributes.get("language")),lineNumber:I.lineNumber,fullPath:I.fullPath??l.fullPath,fullCodecString:b,pairingMask:1n<<BigInt(u),peakBitrate:I.fullPath===null?S:null,averageBitrate:I.fullPath===null?T:null,name:I.attributes.get("name"),hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"video",width:z,height:V}})}}else if(xe.includes(C)){if(k!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");k=P;const x=l.attributes.get("audio");if(x===null){const I=l.attributes.get("channels"),E=I!==null?Number(I.split("/")[0]):null;d.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Ie,lineNumber:l.lineNumber,fullPath:l.fullPath,fullCodecString:k,pairingMask:1n<<BigInt(u),peakBitrate:S,averageBitrate:T,name:A,hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:E!==null&&Number.isInteger(E)&&E>0?E:null}})}else for(const I of s){const E=I.attributes.get("group-id"),F=I.attributes.get("type");if(E!==x||F.toLowerCase()!=="audio")continue;const D=I.attributes.get("channels")??l.attributes.get("channels"),z=D!==null?Number(D.split("/")[0]):null;d.push({id:-1,demuxer:this,backingTrack:null,default:Vi(I.attributes),autoselect:Vi(I.attributes)||Do(I.attributes),languageCode:zo(I.attributes.get("language")),lineNumber:I.lineNumber,fullPath:I.fullPath??l.fullPath,fullCodecString:k,pairingMask:1n<<BigInt(u),peakBitrate:I.fullPath===null?S:null,averageBitrate:I.fullPath===null?T:null,name:I.attributes.get("name"),hasOnlyKeyPackets:l.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:z!==null&&Number.isInteger(z)&&z>0?z:null}})}}}}return d})),o=[],c=l=>{const u=o.find(d=>d.fullPath===l.fullPath&&d.info.type===l.info.type);u?(u.pairingMask|=l.pairingMask,u.default||=l.default,u.autoselect||=l.autoselect,u.lineNumber=Math.min(u.lineNumber,l.lineNumber),l.peakBitrate!==null&&(u.peakBitrate=Math.max(u.peakBitrate??-1/0,l.peakBitrate)),l.averageBitrate!==null&&(u.averageBitrate=Math.max(u.averageBitrate??-1/0,l.averageBitrate)),u.languageCode===Ie&&(u.languageCode=l.languageCode)):(l.id=o.length+1,o.push(l))};for(const l of a)for(const u of l)c(u);o.sort((l,u)=>l.lineNumber-u.lineNumber),this.trackBackings=[];for(const l of o)l.info.type==="video"?this.trackBackings.push(new zl(l)):this.trackBackings.push(new Ol(l));this.internalTracks=o})()}async getTrackBackings(){return await this.readMetadata(),p(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 Mo(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Rr}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Dl{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 zl){for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}else{p(this instanceof Ol);for(const s of n)if(await s.getCodec()===this.getCodec()){t=s;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})()}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...Ft,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){p(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}
vendor: 1,618 bytes, line 1
1async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class zl extends Dl{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return tt(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}getTransformationMatrix(){return this.delegate(()=>this.backingVideoTrack.getTransformationMatrix())}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 Ol extends Dl{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return tt(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 Vi=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}".`)},Do=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}".`)},zo=r=>{if(r===null)return Ie;const e=r.split("-")[0];return e||Ie};class pt{constructor(){this._isIsobmff=!1}}class Ul extends pt{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(v(t)&&(t=await t),!t)return null;t.skip(4);const i=fe(t,4);return i!=="ftyp"&&i!=="styp"?null:fe(t,4)}_createDemuxer(e){return new ga(e)}}class Uf extends Ul{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(v(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(v(l)&&(l=await l),!l)return!1;a=We(l),o=16}if(a<o)return!1;const c=fe(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 Nf extends Ul{async _canReadInput(e){return await this._getMajorBrand(e)==="qt  "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Nl extends pt{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,ft);if(v(i)&&(i=await i),!i)return!1;const n=dl(i);if(n===null||n<1||n>8||Q(i,n)!==_.EBML)return!1;const a=fl(i);if(typeof a!="number")return!1;let o=e._reader.requestSlice(i.filePos,a);if(v(o)&&(o=await o),!o)return!1;const c=i.filePos;for(;o.filePos<=c+a-Le;){const l=dt(o);if(!l)break;const{id:u,size:d}=l,f=o.filePos;if(d===void 0)return!1;switch(u){case _.EBMLVersion:if(Q(o,d)!==1)return!1;break;case _.EBMLReadVersion:if(Q(o,d)!==1)return!1;break;case _.DocType:if(Cr(o,d)!==t)return!1;break;case _.DocTypeVersion:if(Q(o,d)>4)return!1;break}o.filePos=f+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Jd(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Vf extends Nl{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Wf extends pt{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,Ye);if(v(d)&&(d=await d),!d)break;const f=Bt(d);if(!f)break;t=d.filePos+f.size}const i=await Ms(e._reader,t,t+4096);if(!i)return!1;const n=i.header,s=En(n.mpegVersionId,n.channel);let a=e._reader.requestSlice(i.startPos+s,4);if(v(a)&&(a=await a),!a)return!1;const o=R(a);if(o===In||o===pa)return!0;t=i.startPos+i.header.totalSize;const l=await Ms(e._reader,t,t+lr);if(!l)return!1;const u=l.header;return!(n.channel!==u.channel||n.sampleRate!==u.sampleRate)}_createDemuxer(e){return new rf(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}
1class Lf extends pt{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(v(t)&&(t=await t),!t)return!1;const i=fe(t,4);return i!=="RIFF"&&i!=="RIFX"&&i!=="RF64"?!1:(t.skip(4),fe(t,4)==="WAVE")}_createDemuxer(e){return new lf(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class qf extends pt{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return v(t)&&(t=await t),t?fe(t,4)==="OggS":!1}_createDemuxer(e){return new of(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Hf extends pt{async _canReadInput(e){let t=0;for(;;){let n=e._reader.requestSlice(t,Ye);if(v(n)&&(n=await n),!n)break;const s=Bt(n);if(!s)break;t=n.filePos+s.size}let i=e._reader.requestSlice(t,4);return v(i)&&(i=await i),i?fe(i,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new gf(e)}}class jf extends pt{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,Ye);if(v(a)&&(a=await a),!a)break;const o=Bt(a);if(!o)break;t=a.filePos+o.size}let i=e._reader.requestSliceRange(t,Ai,Kt);if(v(i)&&(i=await i),!i)return!1;const n=vt(i);if(!n||(t+=n.frameLength,i=e._reader.requestSliceRange(t,Ai,Kt),v(i)&&(i=await i),!i))return!1;const s=vt(i);return s?n.objectType===s.objectType&&n.samplingFrequencyIndex===s.samplingFrequencyIndex&&n.channelConfiguration===s.channelConfiguration:!1}_createDemuxer(e){return new df(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Kf extends pt{async _canReadInput(e){const t=Oe+16+1;let i=e._reader.requestSlice(0,t);if(v(i)&&(i=await i),!i)return!1;const n=N(i,t);return n[0]===71&&n[Oe]===71||n[0]===71&&n[Oe+16]===71?!0:n[4]===71&&n[4+Oe+4]===71}_createDemuxer(e){return new Sf(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Vl extends pt{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(v(t)&&(t=await t),!t||!(fe(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof gr))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 Of(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Rr}}const Wl=new Uf,Ll=new Nf,Qf=new Nl,Gf=new Vf,ql=new Wf,$f=new Lf,Xf=new qf,Hl=new jf,Yf=new Hf,jl=new Kf,Kl=new Vl,$p=[Kl,Wl,Ll,Qf,Gf,$f,Xf,Yf,ql,Hl,jl],Xp=[Kl,Wl,Ll,ql,Hl,jl],Zf=(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.`)}};const Us=new Map,Ns=new Map,Jf=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&tt(e.codec)!==r)throw new TypeError(`options.codec, when provided, must match the specified codec (${r}).`);if(e.codedWidth!==void 0&&(!Number.isInteger(e.codedWidth)||e.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(e.codedHeight!==void 0&&(!Number.isInteger(e.codedHeight)||e.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(e.displayAspectWidth!==void 0&&(!Number.isInteger(e.displayAspectWidth)||e.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(e.displayAspectHeight!==void 0&&(!Number.isInteger(e.displayAspectHeight)||e.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(e.description!==void 0&&!Nr(e.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");
1if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},eh=(r,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&tt(e.codec)!==r)throw new TypeError(`options.codec, when provided, must match the specified codec (${r}).`);if(e.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(e.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(e.description!==void 0&&!Nr(e.description))throw new TypeError("options.description, when provided, must be a buffer source.")},Yp=r=>we.includes(r)?Ql(r):xe.includes(r)?Gl(r):!1,Ql=async(r,e={})=>{if(!we.includes(r))return!1;Jf(r,e);const t={...e,codedWidth:e.codedWidth??1280,codedHeight:e.codedHeight??720,codec:e.codec??Gc(r,1280,720,1e6,!1)};t.description??=Ed();const i=JSON.stringify(t),n=Us.get(i);if(n)return n;const s=(async()=>Ci.some(o=>o.supports(r,t))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(t)).supported===!0)();return Us.set(i,s),s},Gl=async(r,e={})=>{if(!xe.includes(r))return!1;eh(r,e);const t={...e,numberOfChannels:e.numberOfChannels??2,sampleRate:e.sampleRate??48e3,codec:e.codec??Yc(r,2,48e3)};if(t.description===void 0){const a=vd(t);if(a===!1)return!1;t.description=a}const i=JSON.stringify(t),n=Ns.get(i);if(n)return n;const s=(async()=>_i.some(o=>o.supports(r,t))||ke.includes(r)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0)();return Ns.set(i,s),s},Zp=async()=>{const[r,e]=await Promise.all([th(),rh()]);return[...r,...e]},th=async(r=we,e)=>{const t=await Promise.all(r.map(i=>Ql(i,e)));return r.filter((i,n)=>t[n])},rh=async(r=xe,e)=>{const t=await Promise.all(r.map(i=>Gl(i,e)));return r.filter((i,n)=>t[n])};var ih=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},nh=(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});ea();let Oo=-1/0,Uo=-1/0,xi=null;typeof FinalizationRegistry<"u"&&(xi=new FinalizationRegistry(r=>{const e=performance.now();r.type==="video"?(e-Oo>=1e3&&(O._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."),Oo=e),typeof VideoFrame<"u"&&r.data instanceof VideoFrame&&r.data.close()):(e-Uo>=1e3&&(O._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."),Uo=e),typeof AudioData<"u"&&r.data instanceof AudioData&&r.data.close())}));class $t{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Vs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],sh=new Set(Vs);class _e{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Wt*this.timestamp)}get microsecondDuration(){return Math.trunc(Wt*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!sh.has(t.format))throw new TypeError("init.format must be one of: "+Vs.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.");
vendor: 4,749 bytes, line 1
1if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");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&&Wn(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.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??oh(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._doNotCopy?se(e):se(e).slice(),this._layout=i,this.colorSpace=new Xn(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?.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");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&&Wn(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.flip=t?.flip??!1,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 Xn(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(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");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&&Wn(t.visibleRect,"init.visibleRect"),typeof VideoFrame<"u")return new _e(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Wt),duration:Math.trunc((t.duration??0)*Wt)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,n=0;
1if("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:tn(),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.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Xn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof $t){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(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("init.flip, when provided, must be a boolean.");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&&!Vs.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.flip=t.flip??!1,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=zr({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),xi?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return p(this._data!==null),this._data instanceof $t?new _e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):Gr(this._data)?new _e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(p(this._layout),new _e(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,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new _e(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,flip:this.flip,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(xi?.unregister(this),this._data instanceof $t?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Gr(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Wo(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 Gr(this._data)?this._data.allocationSize(e):Lo(this,e).allocationSize}async copyTo(e,t={}){if(!Nr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Wo(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(p(this._data!==null),Gr(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 $t){const l={stack:[],error:void 0,hasError:!1};try{const u=ih(l,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,flip:this.flip},t.colorSpace??"srgb"),!1);if(!(u instanceof _e))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{nh(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=Lo(this,t);p(this.format);const n=se(e);if(n.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${n.byteLength}`);const s=Bn(this.format);let a;if(this._data instanceof $t){let l=this._data.getDataPlanes();if(v(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)p(this._layout),p(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");p(u);const d=u.getImageData(0,0,this.codedWidth,this.codedHeight);
1a=[{data:se(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 g=u.destinationOffset;const m=u.sourceWidthBytes,w={offset:g,stride:u.destinationStride};for(let y=0;y<u.sourceHeight;y++){if(h+m>f.byteLength)throw new Error("Source buffer OOB read.");if(g+m>n.byteLength)throw new Error("Destination buffer OOB write.");const b=f.subarray(h,h+m);n.set(b,g),h+=d,g+=u.destinationStride}o.push(w)}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(p(this._data!==null),this._data instanceof $t){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(v(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 Gr(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(p(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,g=0,m=0,w=this.displayWidth,y=this.displayHeight;if(a!==void 0?(u=t,d=i,f=n,h=s,g=a,m=o,c!==void 0?(w=c,y=l):(w=f,y=h
1)):(g=t,m=i,n!==void 0&&(w=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(g))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(w)||w<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._unmapSourceRegion(u,d,f,h,this.rotation,this.flip));const b=this.toCanvasImageSource();e.save();const k=g+w/2,S=m+y/2;e.translate(k,S),this.flip&&e.scale(-1,1),e.rotate(this.rotation*Math.PI/180);const T=this.rotation%180===0?1:w/y;e.scale(1/T,T),e.drawImage(b,u,d,f,h,-w/2,-y/2,w,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.");if(!["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.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");t.crop!==void 0&&Pi(t.crop,"options.");const i=e.canvas.width,n=e.canvas.height,s=t.rotation??this.rotation,a=t.flip??this.flip,[o,c]=s%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let l=t.crop;l&&(l=fn(l,o,c));let u,d,f,h;const{sx:g,sy:m,sWidth:w,sHeight:y}=this._unmapSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??o,t.crop?.height??c,s,a);if(t.fit==="fill")u=0,d=0,f=i,h=n;else{const[k,S]=t.crop?[t.crop.width,t.crop.height]:[o,c],T=t.fit==="contain"?Math.min(i/k,n/S):Math.max(i/k,n/S);f=k*T,h=S*T,u=(i-f)/2,d=(n-h)/2}e.save();const b=s%180===0?1:f/h;e.translate(i/2,n/2),a&&e.scale(-1,1),e.rotate(s*Math.PI/180),e.scale(1/b,b),e.translate(-i/2,-n/2),e.drawImage(this.toCanvasImageSource(),g,m,w,y,u,d,f,h),e.restore()}_unmapSourceRegion(e,t,i,n,s,a){return a&&(e=(s%180===0?this.squarePixelWidth:this.squarePixelHeight)-e-i),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:g,isNew:m}=u>0?Vo(d,f):{canvas:e,context:t,isNew:i.targetIsFresh};g.imageSmoothingQuality="high",i.fillBlack?(g.fillStyle="black",g.fillRect(0,0,d,f)):m||g.clearRect(0,0,d,f),this.drawWithFit(g,{fit:i.fit,rotation:i.rotation,flip:i.flip,crop:i.crop}),g.globalCompositeOperation="copy";for(let w=u;w>1;w--){const y=n*2**w,b=s*2**w;g.drawImage(h,0,0,y,b,0,0,y/2,b/2)}g.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")}
1toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(p(this._data!==null),this._data instanceof $t||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.flip!==void 0&&typeof e.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(e.crop!==void 0&&Pi(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{rotation:t,flip:i}=Tc(this.rotation,this.flip,e.rotate??0,e.flip??!1),[n,s]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=fn(a,n,s));const o=a?a.width:n,c=a?a.height:s,l=o/c;let u,d;e.width!==void 0&&e.height===void 0?(u=e.width,d=u/l):e.width===void 0&&e.height!==void 0?(d=e.height,u=d*l):e.width!==void 0&&e.height!==void 0?(u=e.width,d=e.height):(u=o,d=c),u=ws(u,e.roundDimensionsTo??1),d=ws(d,e.roundDimensionsTo??1);const f={width:u,height:d,fit:e.fit??"fill",rotation:t,flip:i,crop:a??{left:0,top:0,width:n,height:s},alpha:e.alpha??"keep"};for(const w of Ws){let y=w(this,f);if(v(y)&&(y=await y),y!==null)return y}const{canvas:h,context:g,isNew:m}=Vo(f.width,f.height);return this._drawWithFitAndMipmapping(h,g,{fit:f.fit,rotation:f.rotation,flip:f.flip,crop:f.crop,targetIsFresh:m,fillBlack:f.alpha==="discard"}),new _e(h,{timestamp:this.timestamp,duration:this.duration,rotation:0,flip:!1})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setFlip(e){if(typeof e!="boolean")throw new TypeError("newFlip must be a boolean.");this.flip=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 Ws=[],Jp=r=>{Ws.includes(r)||Ws.push(r)},ah=3,Qr=[];let No=0;const Vo=(r,e)=>{for(const n of Qr)if(n.canvas.width===r&&n.canvas.height===e)return n.age=No++,{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 Qr.length>=ah&&Qr.splice(ta(Qr,n=>n.age),1),Qr.push({canvas:t,context:i,age:No++}),{canvas:t,context:i,isNew:!0}};class Xn{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(fr);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(hr);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(mr);if(e.matrix!=null&&!n.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${n.join(", ")}.`);
vendor: 1,354 bytes, line 1
1if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Gr=r=>typeof VideoFrame<"u"&&r instanceof VideoFrame,fn=(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 p(s>=0),p(a>=0),{left:i,top:n,width:s,height:a}},Pi=(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.")},Wo=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.")}},oh=(r,e,t)=>{const i=Bn(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},Bn=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:Ae(r),p(!1)}},Lo=(r,e)=>{const t={left:0,top:0,width:r.codedWidth,height:r.codedHeight},i=e.rect,n=ch(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 uh(n,a,s)},ch=(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(!lh(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},lh=(r,e)=>{if(r===null)return!0;const t=Bn(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},uh=(r,e,t)=>{const i=Bn(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 w=t[c];if(w.stride<h.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);h.destinationOffset=w.offset,h.destinationStride=w.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 w=0;w<c;w++){const y=a[w];if(!(o[c]<=y.destinationOffset||o[w]<=h.destinationOffset))throw new TypeError("Planes overlap.")}a.push(h)}return{allocationSize:s,computedLayouts:a}},Wi=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class $r{constructor(){this._referenceCount=0}}class be{get microsecondTimestamp(){return Math.trunc(Wt*this.timestamp)}get microsecondDuration(){return Math.trunc(Wt*this.duration)}constructor(e){if(this._closed=!1,Xr(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 $r){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Wi.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(!Wi.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Tt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let i;if(e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const n=this.numberOfFrames*this.numberOfChannels*Tt(this.format);if(i.byteLength<n)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}xi?.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&&!Wi.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const n=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-i;if(n>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const s=Tt(t),a=er(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(!Nr(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&&!Wi.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:n,frameOffset:s}=t;let{planeIndex:a}=t,o=this.format;const c=i??this.format;if(!c)throw new Error("Destination format not determined");const l=this.numberOfFrames,u=this.numberOfChannels,d=s??0;if(d>=l)throw new RangeError("frameOffset out of range");const f=n!==void 0?n:l-d;if(f>l-d)throw new RangeError("frameCount out of range");const h=Tt(c),g=er(c);if(g&&a>=u)throw new RangeError("planeIndex out of range");if(!g&&a!==0)throw new RangeError("planeIndex out of range");const w=(g?f:f*u)*h;if(e.byteLength<w)throw new RangeError("Destination buffer is too small");const y=q(e),b=Xl(c);if(Xr(this._data))if(vr()&&u>2&&c!==o){fh(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}catch(C){if(c==="f32-planar")throw C;o="f32-planar"}const k=$l(o),S=Tt(o),T=er(o);let A;if(this._data instanceof $r){const C=x=>{const I=this._data.getDataPlane(x);if(!(I instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const E=l*S*(T?1:u);if(I.byteLength!==E)throw new TypeError(`Data plane ${x}
1 has invalid size. Expected exactly ${E} bytes, got ${I.byteLength} bytes.`);return I};if(T)if(g)A=C(a),a=0;else{A=new Uint8Array(l*S*u);for(let x=0;x<u;x++){const I=C(x);A.set(I,x*l*S)}}else A=C(0)}else if(this._data instanceof Uint8Array)A=this._data;else if(p(o==="f32-planar"),g)A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:a})),this._data.copyTo(A,{format:"f32-planar",planeIndex:a}),a=0;else{A=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*u);for(let C=0;C<u;C++)this._data.copyTo(A.subarray(C*l*S,(C+1)*l*S),{format:"f32-planar",planeIndex:C})}const P=q(A);for(let C=0;C<f;C++)if(g){const x=C*h;let I;T?I=(a*l+(C+d))*S:I=((C+d)*u+a)*S;const E=k(P,I);b(y,x,E)}else for(let x=0;x<u;x++){const E=(C*u+x)*h;let F;T?F=(x*l+(C+d))*S:F=((C+d)*u+x)*S;const D=k(P,F);b(y,E,D)}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof $r){const e=new be(this._data);return e.setTimestamp(this.timestamp),e}else if(Xr(this._data)){const e=new be(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new be({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("startFrame must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endFrame must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t<e)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");const i=t-e,n=Tt(this.format);let s;if(er(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 be({data:s,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(xi?.unregister(this),this._data instanceof $r?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):Xr(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 $r?this._createAudioDataFromData():Xr(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(er(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 be({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 g=0;g<n;g++)e.copyFromChannel(f.subarray(g*d,(g+1)*d),g,c);const h=new be({format:"f32-planar",sampleRate:s,numberOfFrames:d,numberOfChannels:n,timestamp:t+c/s,data:f});u.push(h),c+=d,l-=d}return u}}const Tt=r=>{switch(r){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},er=r=>{switch(r){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},$l=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)}},Xl=r=>{switch(r){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,le(Math.round(i*128)+128,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,le(Math.round(i*32768),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,le(Math.round(i*2147483648),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Xr=r=>typeof AudioData<"u"&&r instanceof AudioData,dh=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}},fh=(r,e,t,i,n,s,a,o)=>{const c=$l(t),l=Xl(i),u=Tt(t),d=Tt(i),f=er(t);if(er(i))if(f){const g=new ArrayBuffer(o*u),m=q(g);r.copyTo(g,{planeIndex:s,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const y=w*u,b=w*d,k=c(m,y);l(e,b,k)}}else{const g=new ArrayBuffer(o*n*u),m=q(g);r.copyTo(g,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const y=(w*n+s)*u,b=w*d,k=c(m,y);l(e,b,k)}}else if(f){const g=o*u,m=new ArrayBuffer(g),w=q(m);for(let y=0;y<n;y++){r.copyTo(m,{planeIndex:y,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){const k=b*u,S=(b*n+y)*d,T=c(w,k);l(e,S,T)}}}else{const g=new ArrayBuffer(o*n*u),m=q(g);r.copyTo(g,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++)for(let y=0;y<n;y++){const b=w*n+y,k=b*u,S=b*d,T=c(m,k);l(e,S,T)}}},hh=(r,e)=>{const t=r.allocationSize({format:e,planeIndex:0}),i=new ArrayBuffer(t);return r.copyTo(i,{format:e,planeIndex:0}),new be({data:i,format:e,numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,timestamp:r.timestamp,duration:r.duration})};const Ls=new Map,qs=new Map,Sa=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!we.includes(r.codec))throw new TypeError(`Invalid video codec '${r.codec}'. Must be one of: ${we.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 he))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof he)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(r.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.width!==void 0&&(!Number.isInteger(r.transform.width)||r.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(r.transform.height!==void 0&&(!Number.isInteger(r.transform.height)||r.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(r.transform.fit!==void 0&&!["fill","contain","cover"].includes(r.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(r.transform.width!==void 0&&r.transform.height!==void 0&&r.transform.fit===void 0&&!["fill","contain","cover"].includes(r.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(r.transform.fit!==void 0&&["fill","contain","cover"].includes(r.sizeChangeBehavior)&&r.transform.fit!==r.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(r.transform.rotate!==void 0&&![0,90,180,270].includes(r.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");
vendor: 10,994 bytes, line 1
1if(r.transform.flip!==void 0&&typeof r.transform.flip!="boolean")throw new TypeError("config.transform.flip, when provided, must be a boolean.");if(r.transform.crop!==void 0&&Pi(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.");Yl(r.codec,r)},Yl=(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&&tt(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.")},Zl=r=>{const e=r.bitrateMode,t=r.quality._toVideoRateControl(r.codec,r.width,r.height,e),i=(s,a,o)=>({codec:r.fullCodecString??Gc(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,...Bd(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}),p(n.length>0),n},Aa=r=>{if(!r||typeof r!="object")throw new TypeError("Encoding config must be an object.");if(!xe.includes(r.codec))throw new TypeError(`Invalid audio codec '${r.codec}'. Must be one of: ${xe.join(", ")}.`);const e=r.bitrate;if(r.quality===void 0&&e===void 0&&!(ke.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 he))throw new TypeError("config.quality, when provided, must be a Quality.");if(e!==void 0&&!(e instanceof he)&&(!Number.isInteger(e)||e<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(r.transform!==void 0){if(typeof r.transform!="object"||!r.transform)throw new TypeError("config.transform, when provided, must be an object.");if(r.transform.numberOfChannels!==void 0&&(!Number.isInteger(r.transform.numberOfChannels)||r.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(r.transform.sampleRate!==void 0&&(!Number.isInteger(r.transform.sampleRate)||r.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(r.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r.transform.process!==void 0&&typeof r.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(r.onEncodedPacket!==void 0&&typeof r.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(r.onEncoderConfig!==void 0&&typeof r.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");if(r.onEncodedSample!==void 0&&typeof r.onEncodedSample!="function")throw new TypeError("config.onEncodedSample, when provided, must be a function.");Jl(r.codec,r)},Jl=(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&&tt(e.fullCodecString)!==r)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${r}).`)},eu=r=>{const e=r.bitrateMode;return{codec:r.fullCodecString??Yc(r.codec,r.numberOfChannels,r.sampleRate),numberOfChannels:r.numberOfChannels,sampleRate:r.sampleRate,bitrate:r.quality?._toAudioBitrate(r.codec),bitrateMode:r.quality?._bitrateMode??e,...Fd(r.codec)}};class he{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 qo):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"?qo[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=mh[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&&(p(this._quality!==void 0),a=le(Math.round(Du(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&&(p(a!==null&&s),l=le((a-s.worst)/(s.best-s.worst),0,1)),c=Ho(e,t,i,Yn(l))}return{quantizer:a,bitrate:c,bitrateMode:o}}_toVideoBitrate(e,t,i){return this._bitrate!==void 0?this._bitrate:(p(this._quality!==void 0),Ho(e,t,i,Yn(this._quality)))}_toAudioBitrate(e){if(ke.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=Yn(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 qo={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},mh={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}},Yn=r=>.3*Math.exp(2.5538*r),Ho=(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},tu=(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}};p(!1)},eg=new he("very-low"),tg=new he("low"),rg=new he("medium"),ig=new he("high"),ng=new he("very-high"),sg=r=>{if(we.includes(r))return xa(r);if(xe.includes(r))return Pa(r);if(mt.includes(r))return Ca(r);throw new TypeError(`Unknown codec '${r}'.`)},xa=async(r,e={})=>{const{width:t=1280,height:i=720,quality:n,bitrate:s,frameRate:a,...o}=e;if(!we.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 he))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 he)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");if(a!==void 0&&(!Number.isFinite(a)||a<=0))throw new TypeError("frameRate, when provided, must be a finite positive number.");Yl(r,o);const c=Or(n,s)??new he("medium");let l;try{l=Zl({codec:r,width:t,height:i,quality:c,framerate:a,...o,alpha:"discard"})}catch{return!1}const u=JSON.stringify(l),d=Ls.get(u);if(d)return d;const f=(async()=>{for(const{config:g}of l)if(hn.some(m=>m.supports(r,g)))return!0;if(typeof VideoEncoder>"u"||(t%2===1||i%2===1)&&(r==="avc"||r==="hevc"))return!1;for(const{config:g,quantizer:m}of l){try{if(!(await VideoEncoder.isConfigSupported(g)).supported)continue}catch{continue}if(!tn()||await new Promise(async y=>{try{const b=new VideoEncoder({output:()=>{},error:()=>y(!1)});b.configure(g);const k=new Uint8Array(t*i*4),S=new VideoFrame(k,{format:"RGBA",codedWidth:t,codedHeight:i,timestamp:0});b.encode(S,m!==null?tu(r,m):void 0),S.close(),await b.flush(),y(!0)}catch{y(!1)}}))return!0}return!1})();return Ls.set(u,f),f},Pa=async(r,e={})=>{const{numberOfChannels:t=2,sampleRate:i=48e3,quality:n,bitrate:s,...a}=e;if(!xe.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 he))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 he)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");Jl(r,a);const o=Or(n,s)??new he("medium"),c=eu({codec:r,numberOfChannels:t,sampleRate:i,quality:o,...a}),l=JSON.stringify(c),u=qs.get(l);if(u)return u;const d=(async()=>{if(mn.some(f=>f.supports(r,c))||ke.includes(r))return!0;if(typeof AudioEncoder>"u")return!1;try{return(await AudioEncoder.isConfigSupported(c)).supported===!0}catch{return!1}})();return qs.set(l,d),d},Or=(r,e)=>{if(r!==void 0)return r;if(e!==void 0)return e instanceof he?e:new he({bitrate:e})},Ca=async r=>!!mt.includes(r),ag=async()=>{const[r,e,t]=await Promise.all([ph(),Hs(),gh()]);return[...r,...e,...t]},ph=async(r=we,e)=>{const t=await Promise.all(r.map(i=>xa(i,e)));return r.filter((i,n)=>t[n])},Hs=async(r=xe,e)=>{const t=await Promise.all(r.map(i=>Pa(i,e)));return r.filter((i,n)=>t[n])},gh=async(r=mt)=>{const e=await Promise.all(r.map(Ca));return r.filter((t,i)=>e[i])},wh=async(r,e)=>{for(const t of r)if(await xa(t,e))return t;return null},og=async(r,e)=>{for(const t of r)if(await Pa(t,e))return t;return null},cg=async r=>{for(const e of r)if(await Ca(e))return e;return null};class yh{static supports(e,t){return!1}}class bh{static supports(e,t){return!1}}class kh{static supports(e,t){return!1}}class Th{static supports(e,t){return!1}}const Ci=[],_i=[],hn=[],mn=[],lg=r=>{if(r.prototype instanceof yh){const e=r;if(Ci.includes(e)){O._warn("Video decoder already registered.");return}Ci.push(e),Us.clear()}else if(r.prototype instanceof bh){const e=r;if(_i.includes(e)){O._warn("Audio decoder already registered.");return}_i.push(e),Ns.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},ug=r=>{if(r.prototype instanceof kh){const e=r;if(hn.includes(e)){O._warn("Video encoder already registered.");return}hn.push(e),Ls.clear()}else if(r.prototype instanceof Th){const e=r;if(mn.includes(e)){O._warn("Audio encoder already registered.");return}mn.push(e),qs.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};const Sh=r=>{let i=r>>2,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},Ah=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)<<2},xh=r=>{let t=2048,i=0,n=11,s=0,a=r>>3;for(a<0?a=-a-1: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},Ph=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)<<3};const Xt=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.")},Et=r=>{if(!Ke(r))throw new TypeError("timestamp must be a number.")},Zn=(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 Ht{constructor(e){if(!(e instanceof Ri))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Xt(e),this._track.input._disposed)throw new Me;return Zn(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Xt(e);const t=await this.getFirstPacket(e);
1return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Et(e),Xt(t),this._track.input._disposed)throw new Me;return Zn(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof te))throw new TypeError("packet must be an EncodedPacket.");if(Xt(t),this._track.input._disposed)throw new Me;return Zn(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Et(e),Xt(t),this._track.input._disposed)throw new Me;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);return i&&(p(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 te))throw new TypeError("packet must be an EncodedPacket.");if(Xt(t),this._track.input._disposed)throw new Me;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);return i&&(p(i.type==="key"),await this._track.determinePacketType(i)==="delta"?this.getNextKeyPacket(i,t):i)}packets(e,t,i={}){if(e!==void 0&&!(e instanceof te))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 te))throw new TypeError("endPacket must be an EncodedPacket.");if(Xt(i),this._track.input._disposed)throw new Me;const n=[];let{promise:s,resolve:a}=ne(),{promise:o,resolve:c}=ne(),l=!1,u=!1,d=null,f=!1;const h=[],g=()=>Math.max(2,h.length);(async()=>{let w=e??await this.getFirstPacket(i);for(;w&&!u&&!this._track.input._disposed&&!(t&&w.sequenceNumber>=t?.sequenceNumber);){if(n.length>g()){({promise:o,resolve:c}=ne()),await o;continue}n.push(w),a(),{promise:s,resolve:a}=ne(),w=await this.getNextPacket(w,i)}l=!0,a()})().catch(w=>{f||(d=w,f=!0,a())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Me;if(u)return{value:void 0,done:!0};if(f)throw d;if(n.length>0){const w=n.shift(),y=performance.now();for(h.push(y);h.length>0&&y-h[0]>=1e3;)h.shift();return c(),{value:w,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(w){throw w},[Symbol.asyncIterator](){return this}}}}class _a{constructor(e,t){this.onSample=e,this.onError=t}}class ru{mediaSamplesInRange(e=-1/0,t=1/0,i){Et(e),Et(t);const n=[];let s=!1,a=null,{promise:o,resolve:c}=ne(),{promise:l,resolve:u}=ne(),d=!1,f=!1,h=!1,g=null,m=null,w=!1;const y={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{g=await this._createDecoder(x=>{if(u(),x.timestamp>=t&&(f=!0),f){x.close();return}a&&(x.timestamp>e?(n.push(a),s=!0):a.close()),x.timestamp>=e&&(n.push(x),s=!0),a=s?null:x,n.length>0&&(c(),{promise:o,resolve:c}=ne())},x=>{w||(m=x,w=!0,c())});const S=this._createPacketSink(),T=await S.getKeyPacket(e,y)??await S.getFirstKeyPacket(y);let A=T;const C=S.packets(T??void 0,void 0,y);for(await C.next();A&&!f&&!this._track.input._disposed;){const x=jo(n.length);if(n.length+g.getDecodeQueueSize()>x){({promise:l,resolve:u}=ne()),await l;continue}g.decode(A);const I=await C.next();if(I.done)break;A=I.value}await C.return(),!h&&!this._track.input._disposed&&await g.flush(),!s&&a&&n.push(a),d=!0,c()})().catch(S=>{w||(m=S,w=!0,c())}).finally(()=>{g?.close()});const b=this._track,k=()=>{a?.close();for(const S of n)S.close()};return{async next(){for(;;){if(b.input._disposed)throw h=!0,f=!0,k(),new Me;if(h)return{value:void 0,done:!0};if(w)throw h=!0,f=!0,k(),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(),k(),{value:void 0,done:!0}},async throw(S){throw S},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){Bu(e);const i=vu(e),n=[],s=[];let{promise:a,resolve:o}=ne(),{promise:c,resolve:l}=ne(),u=!1,d=!1,f=null,h=null,g=!1;const m=k=>{s.push(k),o(),{promise:a,resolve:o}=ne()},w={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>
1{f=await this._createDecoder(x=>{if(l(),d){x.close();return}let I=0;for(;n.length>0&&x.timestamp-n[0]>-1e-10;)I++,n.shift();if(I>0)for(let E=0;E<I;E++)m(E<I-1?x.clone():x);else x.close()},x=>{g||(h=x,g=!0,o())});const k=this._createPacketSink();let S=null,T=null,A=-1;const P=async()=>{p(T),p(f);let x=T;for(f.decode(x);x.sequenceNumber<A;){const I=jo(s.length);for(;s.length+f.getDecodeQueueSize()>I&&!d;)({promise:c,resolve:l}=ne()),await c;if(d)break;const E=await k.getNextPacket(x,w);p(E),f.decode(E),x=E}A=-1},C=async()=>{p(f),await f.flush();for(let x=0;x<n.length;x++)m(null);n.length=0};for await(const x of i){if(Et(x),d||this._track.input._disposed)break;const I=await k.getPacket(x,w),E=I&&await k.getKeyPacket(x,w);if(!E){A!==-1&&(await P(),await C()),m(null),S=null;continue}S&&(E.sequenceNumber!==T.sequenceNumber||I.timestamp<S.timestamp)&&(await P(),await C()),n.push(I.timestamp),A=Math.max(I.sequenceNumber,A),S=I,T=E}!d&&!this._track.input._disposed&&(A!==-1&&await P(),await C()),u=!0,o()})().catch(k=>{g||(h=k,g=!0,o())}).finally(()=>{f?.close()});const y=this._track,b=()=>{for(const k of s)k?.close()};return{async next(){for(;;){if(y.input._disposed)throw d=!0,b(),new Me;if(d)return{value:void 0,done:!0};if(g)throw d=!0,b(),h;if(s.length>0){const k=s.shift();return p(k!==void 0),l(),{value:k,done:!1}}else if(!u)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,l(),o(),b(),{value:void 0,done:!0}},async throw(k){throw k},[Symbol.asyncIterator](){return this}}}}const jo=r=>r===0?40:8;class Ch extends _a{constructor(e,t,i,n,s,a,o){super(e,t),this.codec=i,this.decoderConfig=n,this.rotation=s,this.flip=a,this.timeResolution=o,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new kn,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 c=Ci.find(l=>l.supports(i,n));if(c)this.customDecoder=new c,this.customDecoder.codec=i,this.customDecoder.config=n,this.customDecoder.onSample=l=>{if(!(l instanceof _e))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(l)},this.customDecoder.onError=l=>{t(l)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(l=>t(l));else{const l=d=>{if(this.alphaQueue.length>0){const f=this.alphaQueue.shift();p(f!==void 0),this.mergeAlpha(d,f)}else this.colorQueue.push(d)};if(ks()){if(i==="avc"&&this.decoderConfig.description){const d=oa(se(this.decoderConfig.description));if(d&&d.sequenceParameterSets.length>0){const f=bi(d.sequenceParameterSets[0]);f&&(f.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),f.maxDecFrameBuffering!==0&&f.bitstreamRestrictionFlag!==1&&(d.sequenceParameterSets[0]=Ga(f),this.decoderConfig={...this.decoderConfig,description:Rc(d)}))}}Js(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 u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:d=>{try{l(d)}catch(f){this.onError(f)}},error:d=>{d.stack=u,this.onError(d)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if(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(p(this.decoder),vr()||Na(this.inputTimestamps,e.timestamp,t=>t),ks()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];let i=!1;for(const s of Fc(e.data,this.decoderConfig)){const a=dr(e.data[s.offset]);if(i||=a>=1&&a<=5,a===ye.AUD){if(i)break;t.length=0}a>=20&&a<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}if(!this.decoderConfig.description)for(let s=0;s<t.length;s++){const a=t[s];if(dr(a[0])!==ye.SPS)continue;const o=bi(a);o&&o.maxDecFrameBuffering!==0&&o.bitstreamRestrictionFlag!==1&&(t[s]=Ga(o));break}const n=$u(t,this.decoderConfig);e=new te(n,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=nd(e.data,this.decoderConfig);t&&(e=new te(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 _h),!this.alphaDecoder){const i=s=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();p(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();p(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=_n(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 sn(e,this.decoderConfig)){const i=Gt(e[t.offset]);if(i===ae.RASL_N||i===ae.RASL_R)return!0}return!1}sampleHandler(e){if(vr()){if(this.sampleQueue.length>0&&e.timestamp>=ue(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}Na(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();p(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),e.setFlip(this.flip),this.onSample(e)}async mergeAlpha(e,t){const i=ne();this.mergeAlphaPromises.push(i.promise);const n={sample:null};this.finalSamples.push(n);try{if(!t)n.sample=new _e(e);else{p(this.merger);const s=await this.merger.merge(e,t);n.sample=new _e(s)}for(;this.finalSamples.length>0&&this.finalSamples[0].sample!==null;){const s=this.finalSamples.shift();this.sampleHandler(s.sample)}}catch(s){Ji(this.finalSamples,n),this.onError(s)}finally{Ji(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(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),vr()){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()):(p(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 Jn=null;class _h{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(this.workers.length===0){if(!Jn){const o=new Blob([`(${Ih.toString()})()`],{type:"application/javascript"});Jn=URL.createObjectURL(o)}const a=le(navigator.hardwareConcurrency,1,4);for(let o=0;o<a;o++){const c=new Worker(Jn);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=ne();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 Ih=()=>{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"),g=d.includes("P10"),m=d.includes("P12");
1if(g!==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,g=new Uint8Array(h*4);await c.copyTo(g);const m=await o(l,d,f,1);for(let b=0,k=3;b<h;b++,k+=4)g[k]=m[b];const y={format:u==="RGBX"||u==="RGBA"?"RGBA":"BGRA",codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[g.buffer]};return new VideoFrame(g,y)},s=async(c,l,u)=>{const d=c.visibleRect?.width??c.codedWidth,f=c.visibleRect?.height??c.codedHeight,h=u.includes("P10"),g=u.includes("P12"),m=h||g?2:1;let w,y;u.startsWith("I420")?(w=Math.ceil(d/2),y=Math.ceil(f/2)):u.startsWith("I422")?(w=Math.ceil(d/2),y=f):(w=d,y=f);const b=d*f,k=w*y,S=b*m,T=k*m,A=b*m,P=S+2*T+A,C=new Uint8Array(P);await c.copyTo(C);const x=await o(l,d,f,m),I=S+2*T;C.set(x,I);const F={format:u.slice(0,4)+"A"+u.slice(4),codedWidth:d,codedHeight:f,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,F)},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),g=Math.ceil(d/2),m=h*g,w=c.allocationSize();(!e||e.byteLength!==w)&&(e=new Uint8Array(w)),await c.copyTo(e);const y=new Uint8Array(f+2*m+f);y.set(e.subarray(0,f),0);const b=f,k=f+m,S=f;for(let P=0;P<m;P++)y[b+P]=e[S+P*2],y[k+P]=e[S+P*2+1];const T=await o(l,u,d,1);y.set(T,f+2*m);const A={format:"I420A",codedWidth:u,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,A)},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 g=h==="RGBA"||h==="RGBX"?0:2,m=l*u;for(let w=0;w<m;w++)r[w]=r[w*4+g];return r.subarray(0,m)}else return r.subarray(0,l*u*d)}},iu=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 js extends ru{constructor(e,t={}){if(!(e instanceof Fn))throw new TypeError("videoTrack must be an InputVideoTrack.");iu(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw typeof VideoDecoder>"u"?new Error(Tn("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(),s=await this._track.getFlip();let a=await this._track.getDecoderConfig();const o=await this._track.getTimeResolution();return p(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new Ch(e,t,i,a,n,s,o)}_createPacketSink(){return new Ht(this._track)}async getSample(e,t={}){Et(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 dg{constructor(e,t={}){if(this._rotation=0,this._flip=!1,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Fn))throw new TypeError("videoTrack must be an InputVideoTrack.");
vendor: 6,602 bytes, line 1
1if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");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.");if(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("options.flip, when provided, must be a boolean.");if(t.crop!==void 0&&Pi(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");t.decoderOptions!==void 0&&iu(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new js(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),n=e.flip??await t.getFlip(),s=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[o,c]=i%180===0?[s,a]:[a,s];let l=e.crop;l&&(l=fn(l,o,c));let[u,d]=l?[l.width,l.height]:[o,c];const f=u/d;e.width!==void 0&&e.height===void 0?(u=e.width,d=Math.round(u/f)):e.width===void 0&&e.height!==void 0?(d=e.height,u=Math.round(d*f)):e.width!==void 0&&e.height!==void 0&&(u=e.width,d=e.height),this._width=u,this._height=d,this._rotation=i,this._flip=n,this._crop=l})()}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let n=this._canvasPool[this._nextCanvasIndex],s=!1;n||(typeof document<"u"?(n=document.createElement("canvas"),n.width=t,n.height=i):n=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=n),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=n.getContext("2d",{alpha:this._alpha||tn()});p(a),e._drawWithFitAndMipmapping(n,a,{fit:this._fit,rotation:this._rotation,flip:this._flip,crop:this._crop,targetIsFresh:s,fillBlack:!this._alpha&&tn()});const o={canvas:n,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){Et(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*en(this._videoSampleSink.samples(e,t,i),n=>this._videoSampleToWrappedCanvas(n))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*en(this._videoSampleSink.samplesAtTimestamps(e,t),i=>i&&this._videoSampleToWrappedCanvas(i))}}class Eh extends _a{constructor(e,t,i,n){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new kn,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=_i.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 be))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 be(c))}catch(l){this.onError(l)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(n)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(p(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(t=>this.onError(t)).finally(()=>this.customDecoderQueueSize--)):(p(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(p(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(p(this.decoder),this.decoder.state!=="closed"&&this.decoder.close())}}class vh extends _a{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,p(ke.includes(i.codec)),this.codec=i.codec;const{dataType:n,sampleSize:s,littleEndian:a}=rt(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)=>Ah(o.getUint8(c)):n==="alaw"?this.readInputValue=(o,c)=>Ph(o.getUint8(c)):p(!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):p(!1);break;case 3:n==="unsigned"?this.readInputValue=(o,c)=>yn(o,c,a)-2**23:n==="signed"?this.readInputValue=(o,c)=>Fu(o,c,a):p(!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):p(!1);break;case 8:n==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):p(!1);break;default:Ae(s),p(!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:Ae(s),p(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=q(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 be({format:this.outputFormat,data:s,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:c});this.onSample(l)}async flush(){}close(){}}class nu extends ru{constructor(e){if(!(e instanceof Rn))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(Tn("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 p(i&&n),ke.includes(n.codec)?new vh(e,t,n):new Eh(e,t,i,n)}_createPacketSink(){return new Ht(this._track)}async getSample(e,t={}){Et(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 fg{constructor(e){if(!(e instanceof Rn))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new nu(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Et(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return en(this._audioSampleSink.samples(e,t,i),n=>this._audioSampleToWrappedArrayBuffer(n))}buffersAtTimestamps(e,t){return en(this._audioSampleSink.samplesAtTimestamps(e,t),i=>i&&this._audioSampleToWrappedArrayBuffer(i))}}class Ri{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Fn}isAudioTrack(){return this instanceof Rn}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return ce(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return ce(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return ce(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return ce(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 ce(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}
1),i=(t?.timestamp??0)+(t?.duration??0);return Dr(i,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new Ht(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?Number((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 Ri))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(tr({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(tr({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(tr({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(tr({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(tr({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=es(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&&=es(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=es(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const ce=(r,e,t)=>{if(v(r))throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return r},es=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 v(i)?i.then(t):t(i)}:void 0};class Fn extends Ri{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return ce(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 ce(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return ce(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getTransformationMatrix(){return this._backing.getTransformationMatrix()}async getRotation(){return ii(await this._backing.getTransformationMatrix())}get rotation(){return ii(ce(this._backing.getTransformationMatrix(),"rotation","getRotation"))}async getFlip(){return bc(await this._backing.getTransformationMatrix())}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return ce(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return ce(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=zr({num:await this.get
1SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=zr({num:ce(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ce(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ce(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ce(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=ce(e,"displayWidth","getDisplayWidth");if(n!==null)return n}const i=ii(ce(this._backing.getTransformationMatrix(),"displayWidth","getDisplayWidth"))%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ce(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=ce(e,"displayHeight","getDisplayHeight");if(n!==null)return n}const i=ii(ce(this._backing.getTransformationMatrix(),"displayHeight","getDisplayHeight"))%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ce(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 p(t!==null),Ci.some(n=>n.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return O._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof te))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 p(i),_n(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&&(!Ke(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 Ht(this),s=[];let a=-1/0,o=0;for await(const I of n.packets(void 0,void 0,{metadataOnly:!0})){if(s.length>=i&&I.timestamp>=a)break;s.push(I.timestamp),a=Math.max(a,I.timestamp),o++}const c=new Float64Array(s.length);for(let I=0;I<s.length;I++)c[I]=Math.round(s[I]*t);c.sort();let l=1;for(let I=1;I<c.length;I++)c[I]!==c[l-1]&&(c[l++]=c[I]);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=Bh(u,t),f=d??t,h=d!==null?t/d:null,g=new Map;let m=1/0,w=-1/0,y=0;for(let I=1;I<l;I++){const E=u[I]-u[I-1],F=h!==null?Math.max(1,Math.round(E/h)):E;g.set(F,(g.get(F)??0)+1),m=Math.min(m,F),w=Math.max(w,F),y+=F}const b=l-1,k=[...g.keys()].sort((I,E)=>I-E),S=b-1>>1,T=b>>1;let A=0,P=0,C=0;for(const I of k)if(C+=g.get(I),A===0&&C>S&&(A=I),C>T){P=I;break}const x=(f/A+f/P)/2;return{underlyingFrameRate:d,bestGuessFrameRate:d!==null?d:Fh(x),minFrameRate:f/w,maxFrameRate:f/m,averageFrameRate:f*b/y,medianFrameRate:x,frameRateIsConstant:d!==null&&m===1&&w===1,probedPacketCount:o}}}class Rn extends Ri{constructor(e,t){super(e,t)}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return ce(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return ce(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return ce(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 p(t!==null),_i.some(i=>i.supports(t,e))||ke.includes(e.codec)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return O._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof te))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const hg=r=>r??1/0,Ko=r=>-(r??-1/0),Yr=r=>-r,Zr=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 v(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 v(i)?i.then(t):t(i)}:void 0}},tr=(r,e)=>({filter:r?.filter||e?.filter?t=>{const i=r?.filter?.(t)??!0,n=s=>s===!1?!1:e?.filter?.(t)??!0;return v(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 v(i)||v(n)?Promise.all([i,n]).then(([a,o])=>s(a,o)):s(i,n)}:void 0}),ts=async(r,e)=>{let t=r;if(e?.filter){const a=r.map(c=>e.filter(c));if(a.some(c=>v(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=>v(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)},Bh=(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 P=1;P<r.length;P++){const C=r[P]-r[P-1];if(!(C>0))return null;o[P-1]=C}const c=o.slice();c.sort();let l=c[Math.floor(c.length*.05)];for(let P=0;P<6;P++){let C=0,x=0;for(const E of o){const F=Math.max(1,Math.round(E/l));Math.abs(E-F*l)>=n||(C+=E,x+=F)}if(x===0)return null;const I=C/x;if(Math.abs(I-l)<=1e-12*Math.max(1,l)){l=I;break}l=I}let u=0,d=0,f=0;for(const P of o){const C=Math.max(1,Math.round(P/l));Math.abs(P-C*l)>=n||(u++,d+=P,f+=C)}if(u/o.length<.98)return null;l=d/f;const h=1/Math.min(f,s),g=Math.max(Number.EPSILON,l-h),m=l+h,w=e/m,y=e/g,b=e/l;let k=null,S=1/0;for(const P of a){if(P<w||P>y)continue;const C=Math.abs(P/b-1);C<S&&(k=P,S=C)}if(k===null){const P=Qo(g,m,1e6),C=Qo(w,y,1e6);if(C&&(!P||C.den<P.den||C.den===P.den&&C.num<=P.num))k=C.num/C.den;else if(P)k=e*P.den/P.num;else return null}const T=e/k;let A=0;for(const P of o){const C=Math.max(1,Math.round(P/T));Math.abs(P-C*T)<n&&A++}return A/o.length<.98?null:k},Qo=(r,e,t)=>{for(let i=1;i<=t;i++){const n=Math.floor(r*i)+1;if(n/i<e)return zr({num:n,den:i})}return null},Fh=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};ea();const Rh=1,Mh=2;class Mn extends vi{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 pt)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof $e||e.source instanceof ba))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof $e&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof Mn))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&Zf(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof $e?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){p(this._rootSource instanceof gr);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=Rh){const i=this._sourceCache.find(a=>a.cacheGroup===t&&Eo(a.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const n=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Eo(a.request,e));if(n)return n.promise.then(a=>a.sourceRef.source.ref());const s=(async()=>{const a=await this._getSourceUncached(e);if(ni(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=ta(this._sourceCache,h=>h.cacheGroup===t&&h.sourceRef.source._refCount===1?h.age:1/0);p(d!==-1);const f=this._sourceCache[d];this._sourceCache.splice(d,1),f.sourceRef.free(),Ji(this._sourceRefs,f.sourceRef)}this._sourceRefs.push(a);const l=this._sourceCachePromises.findIndex(d=>d.request===e);return p(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 Yi(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});
1for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new Go})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),p(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Go)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&&=Zr(e);const i=(await this._getTrackBackings()).map(n=>this._wrapBackingAsTrack(n));return ts(i,e)}async getVideoTracks(e){e&&=Zr(e);const i=(await this.getTracks()).filter(n=>n.isVideoTrack());return ts(i,e)}async getAudioTracks(e){e&&=Zr(e);const i=(await this.getTracks()).filter(n=>n.isAudioTrack());return ts(i,e)}async getPrimaryVideoTrack(e){e&&=Zr(e);const t=tr(e,{sortBy:async n=>[Yr((await n.getDisposition()).default),Yr(await n.hasPairableAudioTrack()),Yr(!await n.hasOnlyKeyPackets()),Ko(await n.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=Zr(e);const t=await this.getPrimaryVideoTrack(),i=tr(e,{sortBy:async s=>[Yr(!t||s.canBePairedWith(t)),Yr((await s.getDisposition()).default),Ko(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 Fn(this,e):new Rn(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 Go extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Me extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class Yi{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 Me;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const s=new Uint8Array(0);return new De(s,q(s),0,e,e)}const i=e+t,n=this.source._read(e,i,El,vl);return v(n)?n.then(s=>s?new De(s.bytes,s.view,s.offset,e,i):null):n?new De(n.bytes,n.view,n.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Me;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,le(this.fileSizeNonStrict-e,t,i));{const n=this.requestSlice(e,i),s=a=>a||(p(this.fileSizeNonStrict!==null),this.requestSlice(e,le(this.fileSizeNonStrict-e,t,i)));return v(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(v(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 De(n,q(n),0,0,i)})()}}class De{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 De(e,q(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 De(this.bytes,this.view,this.offset,e,e+t)}}const Ne=(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)=>{Ne(r,e);const t=r.bytes.subarray(r.bufferPos,r.bufferPos+e);return r.bufferPos+=e,t},U=r=>(Ne(r,1),r.view.getUint8(r.bufferPos++)),Jr=(r,e)=>{Ne(r,2);const t=r.view.getUint16(r.bufferPos,e);return r.bufferPos+=2,t},ge=r=>{Ne(r,2);const e=r.view.getUint16(r.bufferPos,!1);return r.bufferPos+=2,e},bt=r=>{Ne(r,3);const e=yn(r.view,r.bufferPos,!1);return r.bufferPos+=3,e},Ks=r=>{Ne(r,2);const e=r.view.getInt16(r.bufferPos,!1);return r.bufferPos+=2,e},jt=(r,e)=>{Ne(r,4);const t=r.view.getUint32(r.bufferPos,e);return r.bufferPos+=4,t},R=r=>{Ne(r,4);const e=r.view.getUint32(r.bufferPos,!1);return r.bufferPos+=4,e},Ir=r=>{Ne(r,4);const e=r.view.getUint32(r.bufferPos,!0);return r.bufferPos+=4,e},sr=r=>{Ne(r,4);const e=r.view.getInt32(r.bufferPos,!1);return r.bufferPos+=4,e},Dh=r=>{Ne(r,4);const e=r.view.getInt32(r.bufferPos,!0);return r.bufferPos+=4,e},$o=(r,e)=>{let t,i;return e?(t=jt(r,!0),i=jt(r,!0)):(i=jt(r,!1),t=jt(r,!1)),i*4294967296+t},We=r=>{const e=R(r),t=R(r);return e*4294967296+t},zh=r=>{const e=sr(r),t=R(r);return e*4294967296+t},Oh=r=>{const e=Ir(r);return Dh(r)*4294967296+e},Uh=r=>{Ne(r,4);const e=r.view.getFloat32(r.bufferPos,!1);return r.bufferPos+=4,e},su=r=>{Ne(r,8);const e=r.view.getFloat64(r.bufferPos,!1);return r.bufferPos+=8,e},fe=(r,e)=>{Ne(r,e);let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(r.bytes[r.bufferPos++]);return t},au=(r,e,t)=>Ue.decode(N(r,e)).split(`
2`).map(s=>s.trim()).filter(s=>s.length>0&&!t?.ignore?.(s));var ar;(function(r){r[r.Unsynchronisation=128]="Unsynchronisation",r[r.ExtendedHeader=64]="ExtendedHeader",r[r.ExperimentalIndicator=32]="ExperimentalIndicator",r[r.Footer=16]="Footer"})(ar||(ar={}));var Ce;(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"})(Ce||(Ce={}));const Zi=128,Ye=10,Er=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","S
2ound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Nh=(r,e)=>{const t=r.filePos;e.raw??={},e.raw.TAG??=N(r,Zi-3),r.filePos=t;const i=kr(r,30);i&&(e.title??=i);const n=kr(r,30);n&&(e.artist??=n);const s=kr(r,30);s&&(e.album??=s);const a=kr(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=kr(r,28),r.skip(2)}else r.skip(-30),l=kr(r,30);l&&(e.comment??=l);const u=U(r);u<Er.length&&(e.genre??=Er[u])},kr=(r,e)=>{const t=N(r,e),i=Tr(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()},Bt=r=>{const e=r.filePos,t=fe(r,3),i=U(r),n=U(r),s=U(r),a=R(r);if(t!=="ID3"||i===255||n===255||(a&2155905152)!==0)return r.filePos=e,null;let o=Es(a);return s&ar.Footer&&(o+=Ye),{majorVersion:i,revision:n,flags:s,size:o}},Dn=(r,e,t)=>{if(![2,3,4].includes(e.majorVersion)){O._warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const i=e.flags&ar.Footer?e.size-Ye:e.size,n=N(r,i),s=new Vh(e,n);if(e.flags&ar.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&ar.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&ar.Unsynchronisation)),l){O._warn(`Skipping encrypted ID3v2 frame ${a.id}`),s.pos=c;continue}if(u){O._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(),g=s.readId3V2Text(h,c),m=s.readId3V2Text(h,c);f[g]??=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("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(t.trackNumber??=g),m&&Number.isInteger(m)&&m>0&&(t.tracksTotal??=m)}break;case"TPOS":case"TPA":{const h=s.readId3V2EncodingAndText(c).split("/"),g=Number.parseInt(h[0],10),m=h[1]&&Number.parseInt(h[1],10);Number.isInteger(g)&&g>0&&(t.discNumber??=g),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 g=Number.parseInt(h[1]);if(Er[g]!==void 0){t.genre??=Er[g];break}}if(h=/^\d+$/.exec(f),h){const g=Number.parseInt(h[0]);if(Er[g]!==void 0){t.genre??=Er[g];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"TBPM":case"TBP":{const f=s.readId3V2EncodingAndText(c),h=Number.parseInt(f,10);Number.isInteger(h)&&(t.beatsPerMinute??=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 g=s.readU8(),m=s.readId3V2Text(f,c).trimEnd(),w=c-s.pos;if(w>=0){const y=s.readBytes(w);t.images||(t.images=[]),t.images.push({data:y,mimeType:h,kind:g===3?"coverFront":g===4?"coverBack":"unknown",description:m})}}break;default:s.pos+=a.size;break}s.pos=c}};class Vh{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?Es(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:Es(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 Ce.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 Ce.UTF_16_WITH_BOM:if(n[0]===255&&n[1]===254){const s=new ci("utf-16le"),a=Tr(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 ci("utf-16be"),a=Tr(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=Tr(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),Ue.decode(n.subarray(0,s))}case Ce.UTF_16_BE_NO_BOM:{const s=new ci("utf-16be"),a=Tr(n.findIndex((o,c)=>o===0&&n[c+1]===0&&c%2===0),n.length);
2return this.pos=i+Math.min(a+2,n.length),s.decode(n.subarray(0,a))}case Ce.UTF_8:{const s=Tr(n.findIndex(a=>a===0),n.length);return this.pos=i+Math.min(s+1,n.length),Ue.decode(n.subarray(0,s))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ia{constructor(e){this.helper=new Uint8Array(8),this.helperView=q(this.helper),this.writer=e}writeId3V2Tag(e){const t=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);const i=this.writer.getPos(),n=new Set;for(const{key:o,value:c}of Vr(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),n.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),n.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),n.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),n.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),n.add("TPE2");break;case"trackNumber":{const l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",l),n.add("TRCK")}break;case"discNumber":{const l=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",l),n.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),n.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),n.add("TDRC");break;case"beatsPerMinute":this.writeId3V2TextFrame("TBPM",`${c}`),n.add("TBPM");break;case"lyrics":this.writeId3V2LyricsFrame(c),n.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),n.add("COMM");break;case"images":{const l={coverFront:3,coverBack:4,unknown:0};for(const u of c){const d=l[u.kind]??0,f=u.description??"";this.writeId3V2ApicFrame(u.mimeType,d,f,u.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ae(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];if(c==null||o.length!==4||n.has(o))continue;let l;if(typeof c=="string")if(gt(c)){l=new Uint8Array(c.length+2),l[0]=Ce.ISO_8859_1;for(let d=0;d<c.length;d++)l[d+1]=c.charCodeAt(d)}else{const d=Z.encode(c);l=new Uint8Array(d.byteLength+2),l[0]=Ce.UTF_8,l.set(d,1)}else if(c instanceof Uint8Array)l=c;else if(o==="TXXX"&&Ic(c)){for(const u in c){const d=c[u],f=gt(u)&&gt(d),h=f?null:Z.encode(u),g=f?null:Z.encode(d),m=f?u.length:h.byteLength,w=f?d.length:g.byteLength,y=1+m+1+w+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(y),this.writeU16(0),this.writeU8(f?Ce.ISO_8859_1:Ce.UTF_8),f?(this.writeIsoString(u),this.writeIsoString(d)):(this.writer.write(h),this.writeU8(0),this.writer.write(g),this.writeU8(0))}continue}else continue;this.writeAscii(o),this.writeSynchsafeU32(l.byteLength),this.writeU16(0),this.writer.write(l)}const s=this.writer.getPos(),a=s-i;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(s),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(Vd(e))}writeIsoString(e){const t=new Uint8Array(e.length+1);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);this.writer.write(t)}writeUtf8String(e){const t=Z.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){const i=gt(t),s=1+(i?t.length:Z.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(i?Ce.ISO_8859_1:Ce.UTF_8),i?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){const t=gt(e),i="",n=4+i.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?Ce.ISO_8859_1:Ce.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(i),this.writeIsoString(e)):(this.writeUtf8String(i),this.writeUtf8String(e))}writeId3V2CommentFrame(e){const t=gt(e),i=t?e.length:Z.encode(e).byteLength,n="",s=4+n.length+1+i+1;this.writeAscii("COMM"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(t?Ce.ISO_8859_1:Ce.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(n),this.writeIsoString(e)):(this.writeUtf8String(n),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,i,n){const s=gt(e)&&gt(i),a=s?i.length:Z.encode(i).byteLength,o=1+e.length+1+1+a+1+n.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(s?Ce.ISO_8859_1:Ce.UTF_8),s?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),s?this.writeIsoString(i):this.writeUtf8String(i),this.writer.write(n)}}class Mt{constructor(e){this.mutex=new pr,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){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)}}}class Wh extends Mt{constructor(e,t){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),yi(this.output._metadataTags)||new Ia(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.inputIsAdts===null){it(i,e.source._codec);const s=i?.decoderConfig?.description;if(this.inputIsAdts=!s,!this.inputIsAdts){const a=Bi(se(s)),o=Ec(a);this.header=o.header,this.headerBitstream=o.bitstream}}if(this.inputIsAdts){const s=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,s)}else{p(this.header);const s=t.data.byteLength+this.header.byteLength;vc(this.headerBitstream,s);const a=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){const o=new Uint8Array(s);o.set(this.header,0),o.set(t.data,this.header.byteLength),this.format._options.onFrame(o,a)}}await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(this.inputIsAdts===null)throw new Error("Cannot finalize an empty ADTS file: not a single packet was added.");e()}}const Xo=new Uint8Array([102,76,97,67]),Lh=38,qh=34;class Hh extends Mt{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(Xo);const t=this.output.tracks[0];p(t?.isAudioTrack()),t.metadata.decoderConfig&&(it({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.applyDecoderConfig(t.metadata.decoderConfig)),e()}applyDecoderConfig(e){p(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;const t=new H(se(e.description));t.skipBits(167),this.bitsPerSample=t.readBits(5)+1,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:i,minimumFrameSize:n,maximumFrameSize:s,sampleRate:a,channels:o,totalSamples:c}){p(this.writer.getPos()===4);const l=!yi(this.output._metadataTags),u=new H(new Uint8Array(4));u.writeBits(1,+!l),u.writeBits(7,It.STREAMINFO),u.writeBits(24,qh),this.writer.write(u.bytes);const d=new H(new Uint8Array(18));if(d.writeBits(16,t),d.writeBits(16,i),d.writeBits(24,n),d.writeBits(24,s),d.writeBits(20,a),d.writeBits(3,o-1),d.writeBits(5,e-1),c>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");d.writeBits(4,0),d.writeBits(32,c),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){const t=32+e.mimeType.length+(e.description?.length??0)+e.data.length,i=new Uint8Array(t);let n=0;const s=q(i);s.setUint32(n,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),n+=4,s.setUint32(n,e.mimeType.length),n+=4,i.set(Z.encode(e.mimeType),8),n+=e.mimeType.length,s.setUint32(n,e.description?.length??0),n+=4,i.set(Z.encode(e.description??""),n),n+=e.description?.length??0,n+=16,s.setUint32(n,e.data.length),n+=4,i.set(e.data,n),n+=e.data.length,p(n===t);const a=new H(new Uint8Array(4));a.writeBits(1,0),a.writeBits(7,It.PICTURE),a.writeBits(24,t),this.writer.write(a.bytes),this.writer.write(i)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(Lh+Xo.byteLength),yi(this.output._metadataTags)){this.metadataWritten=!0;return}const e=this.output._metadataTags.images??[];for(const n of e)this.writePictureBlock(n);const t=Ps(new Uint8Array(0),this.output._metadataTags,!1),i=new H(new Uint8Array(4));i.writeBits(1,1),i.writeBits(7,It.VORBIS_COMMENT),i.writeBits(24,t.length),this.writer.write(i.bytes),this.writer.write(t),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();
2try{this.validateTimestamp(e,t.timestamp,t.type==="key"),this.sampleRate===null&&(it(i,e.source._codec),p(i),p(i.decoderConfig),this.applyDecoderConfig(i.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();const s=De.tempFromBytes(t.data);s.skip(2);const a=N(s,2),o=new H(a),c=Sl(o.readBits(4));if(c===null)throw new Error("Invalid FLAC frame: Invalid block size.");Al(s);const l=xl(s,c);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(t.data.length));const u=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,u),await this.writer.flush()}finally{n()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(this.sampleRate===null)throw new Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let t=1/0,i=0,n=1/0,s=0,a=0;for(let o=0;o<this.blockSizes.length;o++)n=Math.min(n,this.frameSizes[o]),s=Math.max(s,this.frameSizes[o]),i=Math.max(i,this.blockSizes[o]),a+=this.blockSizes[o],o!==this.blockSizes.length-1&&(t=Math.min(t,this.blockSizes[o]));this.blockSizes.length===0&&(t=16,i=65535,n=0,s=0),p(this.channels!==null),p(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:t,maximumBlockSize:i,minimumFrameSize:n,maximumFrameSize:s,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}}const ei=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,jh=/^WEBVTT(.|\n)*?\n{2}/,pn=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class Kh{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
3`,`
4`).replaceAll("\r",`
5`),ei.lastIndex=0;let t;if(!this.preambleText){if(!jh.test(e))throw new Error("WebVTT preamble incorrect.");t=ei.exec(e);const i=e.slice(0,t?.index??e.length).trimEnd();if(!i)throw new Error("No WebVTT preamble provided.");this.preambleText=i,t&&(e=e.slice(t.index),ei.lastIndex=0)}for(;t=ei.exec(e);){const i=e.slice(0,t.index),n=t[1],s=t.index+t[0].length,a=e.indexOf(`
6`,s)+1,o=e.slice(s,a).trim();let c=e.indexOf(`
7
8`,s);c===-1&&(c=e.length);const l=Qs(t[2]),d=Qs(t[3])-l,f=e.slice(a,c).trim();e=e.slice(c).trimStart(),ei.lastIndex=0;const h={timestamp:l/1e3,duration:d/1e3,text:f,identifier:n,settings:o,notes:i},g={};this.preambleEmitted||(g.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(h,g)}}}const Qh=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Qs=r=>{const e=Qh.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])},ou=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 Li{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);p(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 K=new Uint8Array(8),Ze=new DataView(K.buffer),de=r=>[(r%256+256)%256],L=r=>(Ze.setUint16(0,r,!1),[K[0],K[1]]),Ea=r=>(Ze.setInt16(0,r,!1),[K[0],K[1]]),cu=r=>(Ze.setUint32(0,r,!1),[K[1],K[2],K[3]]),B=r=>(Ze.setUint32(0,r,!1),[K[0],K[1],K[2],K[3]]),ht=r=>(Ze.setInt32(0,r,!1),[K[0],K[1],K[2],K[3]]),nt=r=>(Ze.setUint32(0,Math.floor(r/2**32),!1),Ze.setUint32(4,r,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),Yo=r=>(Ze.setInt32(0,Math.floor(r/2**32),!1),Ze.setUint32(4,r,!1),[K[0],K[1],K[2],K[3],K[4],K[5],K[6],K[7]]),lu=r=>(Ze.setInt16(0,2**8*r,!1),[K[0],K[1]]),Ge=r=>(Ze.setInt32(0,2**16*r,!1),[K[0],K[1],K[2],K[3]]),rs=r=>(Ze.setInt32(0,2**30*r,!1),[K[0],K[1],K[2],K[3]]),is=(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()},ee=(r,e=!1)=>{const t=Array(r.length).fill(null).map((i,n)=>r.charCodeAt(n));return e&&t.push(0),t},uu=r=>[Ge(r[0]),Ge(r[1]),rs(r[2]),Ge(r[3]),Ge(r[4]),rs(r[5]),Ge(r[6]),Ge(r[7]),rs(r[8])],W=(r,e,t)=>({type:r,contents:e&&new Uint8Array(e.flat(10)),children:t}),Y=(r,e,t,i,n)=>W(r,[de(e),cu(t),i??[]],n),Gh=r=>r.isQuickTime?W("ftyp",[ee("qt  "),B(512),ee("qt  ")]):r.fragmented?r.cmaf?W("ftyp",[ee("iso5"),B(512),ee("iso5"),ee("iso6"),ee("mp41"),ee("cmfc"),ee("dash")]):W("ftyp",[ee("iso5"),B(512),ee("iso5"),ee("iso6"),ee("mp41")]):W("ftyp",[ee("isom"),B(512),ee("isom"),r.holdsAvc?ee("avc1"):[],ee("mp41")]),Zo=()=>W("styp",[ee("iso5"),B(0),ee("iso5"),ee("iso6"),ee("mp41"),ee("cmfc"),ee("dash")]),Jo=(r,e)=>{const t=Math.max(0,r.minWrittenTimestamp);let i=Math.max(0,r.maxWrittenEndTimestamp-t);return Number.isFinite(i)||(i=0),Y("sidx",1,0,[B(1),B(je),nt(ie(t,je)),nt
vendor: 6,943 bytes, line 8
8(0),L(0),L(1),B(e&2147483647),B(ie(i,je)),B(0)])},qi=r=>({type:"mdat",largeSize:r}),$h=r=>({type:"free",size:r}),ti=r=>W("moov",void 0,[Xh(r.creationTime,r.trackDatas),...r.trackDatas.map(e=>Yh(e,r.creationTime)),r.isFragmented?Om(r.trackDatas):null,Xm(r)]),Xh=(r,e)=>{const t=Math.max(0,...e.map(a=>Math.max(0,ie(Ur(a),je)+ie(a.startTimestampOffset??0,je)))),i=Math.max(0,...e.map(a=>a.track.id))+1,n=!_t(r)||!_t(t),s=n?nt:B;return Y("mvhd",+n,0,[s(r),s(r),B(je),s(t),Ge(1),lu(1),Array(10).fill(0),uu(hi),Array(24).fill(0),B(i)])},Yh=(r,e)=>{const t=lp(r),i=r.startTimestampOffset!==null&&r.startTimestampOffset!==0;return W("trak",void 0,[Zh(r,e),i?Jh(r):null,em(r,e),t.name!==void 0?W("udta",void 0,[W("name",[...Z.encode(t.name)])]):null])},Zh=(r,e)=>{const t=Math.max(0,ie(Ur(r),je)+ie(r.startTimestampOffset??0,je)),i=!_t(e)||!_t(t),n=i?nt:B;let s;if(r.type==="video"&&r.track.metadata.transformationMatrix)s=r.track.metadata.transformationMatrix;else if(r.type==="video"){const{rotation:c,flip:l}=r.track.metadata,u=Mr(Ys(c??0),kc(l?-1:1,1));s=yc(u,r.info.width,r.info.height)}else s=hi;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:Ae(r);return Y("tkhd",+i,a,[n(e),n(e),B(r.track.id),B(0),n(t),Array(8).fill(0),L(0),L(o),lu(r.type==="audio"?1:0),L(0),uu(s),Ge(r.type==="video"?r.info.width:0),Ge(r.type==="video"?r.info.height:0)])},Jh=r=>{const e=r.startTimestampOffset;if(p(e!==null),e>0){const t=ie(e,je),i=ie(Ur(r),je),n=!_t(t)||!_t(i),s=n?nt:B,a=n?Yo:ht;return W("edts",void 0,[Y("elst",n?1:0,0,[B(2),s(t),a(-1),Ge(1),s(i),a(0),Ge(1)])])}else{const t=ie(-e,r.timescale),i=Math.max(0,ie(Ur(r),je)+ie(e,je)),n=!Pu(t)||!_t(i),s=n?nt:B,a=n?Yo:ht;return W("edts",void 0,[Y("elst",n?1:0,0,[B(1),s(i),a(t),Ge(1)])])}},em=(r,e)=>W("mdia",void 0,[tm(r,e),va(!0,rm[r.type],im[r.type]),nm(r)]),tm=(r,e)=>{const t=ie(Ur(r),r.timescale),i=!_t(e)||!_t(t),n=i?nt:B;return Y("mdhd",+i,0,[n(e),n(e),B(r.timescale),n(t),L(mu(r.track.metadata.languageCode??Ie)),L(0)])},rm={video:"vide",audio:"soun",subtitle:"text"},im={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},va=(r,e,t,i="\0\0\0\0")=>Y("hdlr",0,0,[r?ee("mhlr"):B(0),ee(e),ee(i),B(0),B(0),ee(t,!0)]),nm=r=>W("minf",void 0,[cm[r.type](),lm(),fm(r)]),sm=()=>Y("vmhd",0,1,[L(0),L(0),L(0),L(0)]),am=()=>Y("smhd",0,0,[L(0),L(0)]),om=()=>Y("nmhd",0,0),cm={video:sm,audio:am,subtitle:om},lm=()=>W("dinf",void 0,[um()]),um=()=>Y("dref",0,0,[B(1)],[dm()]),dm=()=>Y("url ",0,1),fm=r=>{const e=r.compositionTimeOffsetTable.length>1||r.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return W("stbl",void 0,[hm(r),vm(r),e?Dm(r):null,e?zm(r):null,Fm(r),Rm(r),Mm(r),Bm(r)])},hm=r=>{let e;if(r.type==="video")e=mm(ep(r.track.source._codec,r.info.decoderConfig.codec),r);else if(r.type==="audio"){const t=hu(r.track.source._codec,r.info.decoderConfig.codec,r.muxer.isQuickTime);p(t),e=km(t,r)}else r.type==="subtitle"&&(e=Im(ip[r.track.source._codec],r));return p(e),Y("stsd",0,0,[B(1)],[e])},mm=(r,e)=>W(r,[Array(6).fill(0),L(1),L(0),L(0),Array(12).fill(0),L(e.info.width),L(e.info.height),B(4718592),B(4718592),B(0),L(1),de(10),ee("Mediabunny"),Array(21).fill(0),L(e.info.hasAlphaChannel?32:24),Ea(65535)],[tp[e.track.source._codec]?.(e)??null,pm(e),Sc(e.info.decoderConfig.colorSpace)?null:gm(e),Ba(e)]),Ba=r=>r.avgBitrate===0&&r.maxBitrate===0?null:W("btrt",[B(0),B(r.maxBitrate),B(r.avgBitrate)]),pm=r=>r.info.pixelAspectRatio.num===r.info.pixelAspectRatio.den?null:W("pasp",[B(r.info.pixelAspectRatio.num),B(r.info.pixelAspectRatio.den)]),gm=r=>{const e=r.info.decoderConfig.colorSpace;return W("colr",[ee(r.muxer.isQuickTime?"nclc":"nclx"),L(e?.primaries!=null?fr[e.primaries]:2),L(e?.transfer!=null?hr[e.transfer]:2),L(e?.matrix!=null?mr[e.matrix]:2),r.muxer.isQuickTime?[]:de((e?.fullRange?1:0)<<7)])},wm=r=>r.info.decoderConfig&&W("avcC",[...se(r.info.decoderConfig.description)]),ym=r=>r.info.decoderConfig&&W("hvcC",[...se(r.info.decoderConfig.description)]),ec=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?fr[e.colorSpace.primaries]:1,u=t[6]?Number(t[6]):e.colorSpace?.transfer?hr[e.colorSpace.transfer]:1,d=t[7]?Number(t[7]):e.colorSpace?.matrix?mr[e.colorSpace.matrix]:1;return Y("vpcC",1,0,[de(i),de(n),de(c),de(l),de(u),de(d),L(0)])},bm=r=>W("av1C",$c(r.info.decoderConfig.codec)),km=(r,e)=>{let t=0,i,n=16;const s=ke.includes(e.track.source._codec);if(s){const a=e.track.source._codec,{sampleSize:o}=rt(a);n=8*o,n>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)i=[Array(6).fill(0),L(1),L(t),L(0),B(0),L(e.info.numberOfChannels),L(n),L(0),L(0),L(e.info.sampleRate<2**16?e.info.sampleRate:0),L(0)];else{const a=s?0:-2;i=[Array(6).fill(0),L(1),L(t),L(0),B(0),L(e.info.numberOfChannels),L(Math.min(n,16)),Ea(a),L(0),L(e.info.sampleRate<2**16?e.info.sampleRate:0),L(0),s?[B(1),B(n/8),B(e.info.numberOfChannels*n/8)]:[B(0),B(0),B(0)],B(2)]}return W(r,i,[rp(e.track.source._codec,e.muxer.isQuickTime)?.(e)??null,Ba(e)])},ns=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=[...de(e),...de(21),...cu(0),...B(r.maxBitrate),...B(r.avgBitrate)];if(r.info.decoderConfig.description){const i=se(r.info.decoderConfig.description);t=[...t,...de(5),...is(i.byteLength),...i]}return t=[...L(1),...de(0),...de(4),...is(t.length),...t,...de(6),...de(1),...de(2)],t=[...de(3),...is(t.length),...t],Y("esds",0,0,t)},Ot=r=>W("wave",void 0,[Tm(r),Sm(r),W("\0\0\0\0")]),Tm=r=>W("frma",[ee(hu(r.track.source._codec,r.info.decoderConfig.codec,r.muxer.isQuickTime))]),Sm=r=>{const{littleEndian:e}=rt(r.track.source._codec);return W("enda",[L(+e)])},Am=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){p(o.byteLength>=18);const c=se(o),l=Cn(c);e=l.outputChannelCount,t=l.preSkip,i=l.inputSampleRate,n=l.outputGain,s=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return W("dOps",[de(0),de(e),L(t),B(i),Ea(n),de(s),...a])},xm=r=>{const e=r.info.decoderConfig?.description;p(e);const t=se(e);return Y("dfLa",0,0,[...t.subarray(4)])},ot=r=>{const{littleEndian:e,sampleSize:t}=rt(r.track.source._codec),i=+e;return Y("pcmC",0,0,[de(i),de(8*t)])},Pm=r=>{p(r.info.primingPacket);const e=Vc(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 H(t);return i.writeBits(2,e.fscod),i.writeBits(5,e.bsid),i.writeBits(3,e.b
8smod),i.writeBits(3,e.acmod),i.writeBits(1,e.lfeon),i.writeBits(5,e.bitRateCode),i.writeBits(5,0),W("dac3",[...t])},Cm=r=>{p(r.info.primingPacket);const e=Lc(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 H(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 W("dec3",[...n])},_m=r=>{p(r.info.primingPacket);const e=fa(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 W("ddts",[...Pd(e)])},Im=(r,e)=>W(r,[Array(6).fill(0),L(1)],[np[e.track.source._codec](e),Ba(e)]),Em=r=>W("vttC",[...Z.encode(r.info.config.description)]),vm=r=>Y("stts",0,0,[B(r.timeToSampleTable.length),r.timeToSampleTable.map(e=>[B(e.sampleCount),B(e.sampleDelta)])]),Bm=r=>{if(r.samples.every(t=>t.type==="key"))return null;const e=[...r.samples.entries()].filter(([,t])=>t.type==="key");return Y("stss",0,0,[B(e.length),e.map(([t])=>B(t+1))])},Fm=r=>Y("stsc",0,0,[B(r.compactlyCodedChunkTable.length),r.compactlyCodedChunkTable.map(e=>[B(e.firstChunk),B(e.samplesPerChunk),B(1)])]),Rm=r=>{if(r.type==="audio"&&r.info.requiresPcmTransformation){const{sampleSize:e}=rt(r.track.source._codec);return Y("stsz",0,0,[B(e*r.info.numberOfChannels),B(r.samples.reduce((t,i)=>t+ie(i.duration,r.timescale),0))])}return Y("stsz",0,0,[B(0),B(r.samples.length),r.samples.map(e=>B(e.size))])},Mm=r=>r.finalizedChunks.length>0&&ue(r.finalizedChunks).offset>=2**32?Y("co64",0,0,[B(r.finalizedChunks.length),r.finalizedChunks.map(e=>nt(e.offset))]):Y("stco",0,0,[B(r.finalizedChunks.length),r.finalizedChunks.map(e=>B(e.offset))]),Dm=r=>Y("ctts",1,0,[B(r.compositionTimeOffsetTable.length),r.compositionTimeOffsetTable.map(e=>[B(e.sampleCount),ht(e.sampleCompositionTimeOffset)])]),zm=r=>{let e=1/0,t=-1/0,i=1/0,n=-1/0;p(r.compositionTimeOffsetTable.length>0),p(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,ie(o.timestamp,r.timescale)),n=Math.max(n,ie(o.timestamp+o.duration,r.timescale))}const s=Math.max(-e,0);return n>=2**31?null:Y("cslg",0,0,[ht(s),ht(e),ht(t),ht(i),ht(n)])},Om=r=>W("mvex",void 0,r.map(Um)),Um=r=>Y("trex",0,0,[B(r.track.id),B(1),B(0),B(0),B(0)]),tc=(r,e)=>W("moof",void 0,[Nm(r),...e.map(Vm)]),Nm=r=>Y("mfhd",0,0,[B(r)]),du=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},Vm=r=>W("traf",void 0,[Wm(r),Lm(r),qm(r)]),Wm=r=>{p(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:du(t)};return Y("tfhd",0,e,[B(r.track.id),B(i.duration),B(i.size),B(i.flags)])},Lm=r=>(p(r.currentChunk),Y("tfdt",1,0,[nt(ie(r.currentChunk.startTimestamp,r.timescale))])),qm=r=>{p(r.currentChunk);const e=r.currentChunk.samples.map(m=>m.timescaleUnitsToNextSample),t=r.currentChunk.samples.map(m=>m.size),i=r.currentChunk.samples.map(du),n=r.currentChunk.samples.map(m=>ie(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 g=0;return g|=1,g|=4*+l,g|=256*+u,g|=512*+d,g|=1024*+f,g|=2048*+h,Y("trun",1,g,[B(r.currentChunk.samples.length),B(r.currentChunk.offset-r.currentChunk.moofOffset||0),l?B(i[0]):[],r.currentChunk.samples.map((m,w)=>[u?B(e[w]):[],d?B(t[w]):[],f?B(i[w]):[],h?ht(n[w]):[]])])},Hm=r=>W("mfra",void 0,[...r.map(jm),Km()]),jm=r=>Y("tfra",1,0,[B(r.track.id),B(63),B(r.finalizedChunks.length),r.finalizedChunks.map(t=>[nt(ie(t.samples[0].timestamp,r.timescale)),nt(t.moofOffset),B(t.trafIndex+1),B(1),B(1)])]),Km=()=>Y("mfro",0,0,[B(0)]),Qm=()=>W("vtte"),Gm=(r,e,t,i,n)=>W("vttc",void 0,[n!==null?W("vsid",[ht(n)]):null,t!==null?W("iden",[...Z.encode(t)]):null,e!==null?W("ctim",[...Z.encode(ou(e))]):null,i!==null?W("sttg",[...Z.encode(i)]):null,W("payl",[...Z.encode(r)])]),$m=r=>W("vtta",[...Z.encode(r)]),Xm=r=>{const e=[],t=r.format._options.metadataFormat??"auto",i=r.output._metadataTags;if(t==="mdir"||t==="auto"&&!r.isQuickTime){const n=Zm(i);n&&e.push(n)}else if(t==="mdta"){const n=Jm(i);n&&e.push(n)}else(t==="udta"||t==="auto"&&r.isQuickTime)&&Ym(e,r.output._metadataTags);return e.length===0?null:W("udta",void 0,e)},Ym=(r,e)=>{for(const{key:t,value:i}of Vr(e))switch(t){case"title":r.push(ct("©nam",i));break;
8case"description":r.push(ct("©des",i));break;case"artist":r.push(ct("©ART",i));break;case"album":r.push(ct("©alb",i));break;case"albumArtist":r.push(ct("albr",i));break;case"genre":r.push(ct("©gen",i));break;case"date":r.push(ct("©day",i.toISOString().slice(0,10)));break;case"comment":r.push(ct("©cmt",i));break;case"lyrics":r.push(ct("©lyr",i));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"beatsPerMinute":case"images":break;default:Ae(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(ct(t,i)):i instanceof Uint8Array&&r.push(W(t,Array.from(i))))}},ct=(r,e)=>{const t=Z.encode(e);return W(r,[L(t.length),L(mu("und")),Array.from(t)])},rc={"image/jpeg":13,"image/png":14,"image/bmp":27},fu=(r,e)=>{const t=[];for(const{key:i,value:n}of Vr(r))switch(i){case"title":t.push({key:e?"title":"©nam",value:Je(n)});break;case"description":t.push({key:e?"description":"©des",value:Je(n)});break;case"artist":t.push({key:e?"artist":"©ART",value:Je(n)});break;case"album":t.push({key:e?"album":"©alb",value:Je(n)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Je(n)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Je(n)});break;case"genre":t.push({key:e?"genre":"©gen",value:Je(n)});break;case"beatsPerMinute":e||t.push({key:"tmpo",value:W("data",[B(21),B(0),L(n)])});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Je(n)});break;case"date":t.push({key:e?"date":"©day",value:Je(n.toISOString().slice(0,10))});break;case"images":for(const s of n)s.kind==="coverFront"&&t.push({key:"covr",value:W("data",[B(rc[s.mimeType]??0),B(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:Je(s)})}else t.push({key:"trkn",value:W("data",[B(0),B(0),L(0),L(n),L(r.tracksTotal??0),L(0)])});break;case"discNumber":e||t.push({key:"disc",value:W("data",[B(0),B(0),L(0),L(n),L(r.discsTotal??0),L(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:Ae(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:Je(n)}):n instanceof Uint8Array?t.push({key:i,value:W("data",[B(0),B(0),Array.from(n)])}):n instanceof Br&&t.push({key:i,value:W("data",[B(rc[n.mimeType]??0),B(0),Array.from(n.data)])}))}return t},Zm=r=>{const e=fu(r,!1);return e.length===0?null:Y("meta",0,0,void 0,[va(!1,"mdir","","appl"),W("ilst",void 0,e.map(t=>W(t.key,void 0,[t.value])))])},Jm=r=>{const e=fu(r,!0);return e.length===0?null:W("meta",void 0,[va(!1,"mdta",""),Y("keys",0,0,[B(e.length)],e.map(t=>W("mdta",[...Z.encode(t.key)]))),W("ilst",void 0,e.map((t,i)=>{const n=String.fromCharCode(...B(i+1));return W(n,void 0,[t.value])}))])},Je=r=>W("data",[B(1),B(0),...Z.encode(r)]),ep=(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";
8case"prores":return e}},tp={avc:wm,hevc:ym,vp8:ec,vp9:ec,av1:bm,prores:null},hu=(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"}},rp=(r,e)=>{switch(r){case"aac":return ns;case"mp3":return ns;case"opus":return Am;case"vorbis":return ns;case"flac":return xm;case"ac3":return Pm;case"eac3":return Cm;case"dts":return _m}if(e)switch(r){case"pcm-s24":return Ot;case"pcm-s24be":return Ot;case"pcm-s32":return Ot;case"pcm-s32be":return Ot;case"pcm-f32":return Ot;case"pcm-f32be":return Ot;case"pcm-f64":return Ot;case"pcm-f64be":return Ot}else switch(r){case"pcm-s16":return ot;case"pcm-s16be":return ot;case"pcm-s24":return ot;case"pcm-s24be":return ot;case"pcm-s32":return ot;case"pcm-s32be":return ot;case"pcm-f32":return ot;case"pcm-f32be":return ot;case"pcm-f64":return ot;case"pcm-f64be":return ot}return null},ip={webvtt:"wvtt"},np={webvtt:Em},mu=r=>{p(r.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=r.charCodeAt(t)-96;return e};class Ii{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(){p(!this.started),this.target._start(),this.started=!0}write(e){p(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 p(this.started&&!this.finalized),this.target._flush()}async finalize(){p(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}}const ic=typeof dn<"u"?dn:void 0;class qe extends vi{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 op(this,e)}}const ss=2**16,as=2**32;class os extends qe{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.");
8if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(ss,{maxByteLength:as})}catch{this._buffer=new ArrayBuffer(ss),this._supportsResize=!1}else this._buffer=new ArrayBuffer(ss);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>as)throw new Error(`ArrayBuffer exceeded maximum size of ${as} 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)}}const sp=2**24,ap=2;class pu extends qe{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??sp}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){const i=t-this._lastWriteEnd;this._write(new Uint8Array(i),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(p(this._streamWriter),this._sections.length===0)return;const e=[],t=[...this._sections].sort((i,n)=>i.start-n.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let i=1;i<t.length;i++){const n=e[e.length-1],s=t[i];s.start<=n.start+n.size?n.size=Math.max(n.size,s.start+s.data.byteLength-n.start):e.push({start:s.start,size:s.data.byteLength})}for(const i of e){i.data=new Uint8Array(i.size);for(const n of this._sections)i.start<=n.start&&n.start<i.start+i.size&&i.data.set(n.data,n.start-i.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(i.data,i.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&i.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:i.data,position:i.start}).catch(n=>{this._writeError??=n}),this._lastFlushEnd=i.start+i.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let i=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);i===-1&&(i=this._createChunk(t));const n=this._chunks[i],s=t-n.start,a=e.subarray(0,Math.min(this._chunkSize-s,e.byteLength));n.data.set(a,s);const o={start:s,end:s+a.byteLength};if(this._insertSectionIntoChunk(n,o),n.written[0].start===0&&n.written[0].end===this._chunkSize&&(n.shouldFlush=!0),this._chunks.length>ap){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let i=0,n=e.written.length-1,s=-1;for(;i<=n;){const a=Math.floor(i+(n-i+1)/2);e.written[a].start<=t.start?(i=a+1,s=a):n=a-1}for(e.written.splice(s+1,0,t),(s===-1||e.written[s].end<t.start)&&s++;s<e.written.length-1&&e.written[s].end>=e.written[s+1].start;)e.written[s].end=Math.max(e.written[s].end,e.written[s+1].end),e.written.splice(s+1,1)}_createChunk(e){const i={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(i),this._chunks.sort((n,s)=>n.start-s.start),this._chunks.indexOf(i)}_tryToFlushChunks(e=!1){p(this._streamWriter);for(let t=0;t<this._chunks.length;t++){const i=this._chunks[t];if(!(!i.shouldFlush&&!e)){for(const n of i.written){const s=i.start+n.start;if(this._monotonicity===!0&&s!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");const a=n.start!==0||n.end!==i.data.byteLength;let o;a&&vr()?o=i.data.slice(n.start,n.end):o=i.data.subarray(n.start,n.end),this._streamWriter.write({type:"write",data:o,position:s}).catch(c=>{this._writeError??=c}),this._lastFlushEnd=i.start+n.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;p(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}}class mg extends qe{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new pu(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:t=>
8{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return p(t.position===this._nextWritePos),this._nextWritePos+=t.data.byteLength,p(this._writer),this._writer.write(t.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class pg extends qe{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!ic.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super(),this._fileHandle=null;const i=new WritableStream({start:async()=>{this._fileHandle=await ic.fs.open(e,"w")},write:async n=>{p(this._fileHandle),await this._fileHandle.write(n.data,0,n.data.byteLength,n.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new pu(i,{chunked:!0,...t})}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class gu extends qe{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class op extends qe{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 Vt{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 je=57600,cp=2082844800,lp=r=>{const e={},t=r.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},ie=(r,e,t=!0)=>{const i=r*e;return t?Math.round(i):i},Ur=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};class up extends Mt{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new os,this.auxWriter=new Ii(this.auxTarget,!1),this.auxBoxWriter=new Li(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ne(),this.creationTime=Math.floor(Date.now()/1e3)+cp,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 Su,this.isCmaf=t instanceof hc,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof hc?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 os),this.boxWriter=new Li(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof os?"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 Ii(i,!0);
8n.start(),this.initWriter=n,this.initBoxWriter=new Li(n)}const t=this.output.tracks.some(i=>i.isVideoTrack()&&i.source._codec==="avc");{const i=this.initBoxWriter??this.boxWriter;if(p(i),this.formatOptions.onFtyp&&i.writer.startTrackingWrites(),i.writeBox(Gh({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||(p(this.writer),p(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=qi(!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 tl({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;Fi(i,e.source._codec),p(i),p(i.decoderConfig);const s={...i.decoderConfig};
8p(s.codedWidth!==void 0),p(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=xn(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=Rc(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=Pn(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=id(h),a=!0}const o=Uu(1/(e.metadata.frameRate??je),1e6).den,c=s.displayAspectWidth,l=s.displayAspectHeight,u=c===void 0||l===void 0?{num:1,den:1}
8:zr({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,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};return this.trackDatas.push(f),this.trackDatas.sort((h,g)=>h.track.id-g.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;it(i,e.source._codec),p(i),p(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=vt(De.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=Qt[c.samplingFrequencyIndex],u=Wr[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=na({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&&ke.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,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0};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;Jc(t),p(t),p(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,avgBitrate:e.source._nominalBitrate??e.metadata.averageBitrate??0,maxBitrate:e.source._nominalBitrate??e.metadata.bitrate??0,lastCueEndTimestamp:null,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=[...Lr(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=aa(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=vt(De.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const d=u.crcCheck===null?Ai:Kt;a=a.subarray(d)}
8this.validateTimestamp(s.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(s.info.requiresPcmTransformation){const d=rt(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=ie(i,e.timescale);if(i=n/e.timescale,n>0){const{sampleSize:s,silentValue:a}=rt(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;){e.lastCueEndTimestamp??=Math.min(0,e.cueQueue[0].timestamp);const i=new Set([]);for(const l of e.cueQueue)p(l.timestamp<=t),p(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=Qm();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;pn.lastIndex=0;const d=pn.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=$m(u.notes);this.auxBoxWriter.writeBox(m)}const g=Gm(u.text,d?s:null,u.identifier??null,u.settings??null,h??null);this.auxBoxWriter.writeBox(g),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:ie(n,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){p(!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=ie(a.duration,e.timescale);n+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:n,sampleDelta:1});else{const s=ue(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??=Math.min(i[0],0):e.startTimestampOffset??=i[0];for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n];const a=ie(s.timestamp-s.decodeTimestamp,e.timescale),o=ie(s.duration,e.timescale);if(e.lastTimescaleUnits!==null){p(e.lastSample);const c=ie(s.decodeTimestamp,e.timescale,!1),l=Math.round(c-e.lastTimescaleUnits);if(p(l>=0),e.lastTimescaleUnits+=l,e.lastSample.timescaleUnitsToNextSample=l,!this.isFragmented){let u=ue(e.timeToSampleTable);
8if(p(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=ue(e.compositionTimeOffsetTable);p(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=ie(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,p(e.lastSample),p(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){p(t.type==="key");const n=ie(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(p(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}),p(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(p(!this.isFragmented),p(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+ie(n.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||ue(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)p(i.data),this.writer.write(i.data),i.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(p(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(p(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;const h=this.initBoxWriter??this.boxWriter;p(h),this.formatOptions.onMoov&&h.writer.startTrackingWrites(),this.ensureOneEnabledTrack();const g=ti(this);if(h.writeBox(g),this.formatOptions.onMoov){const{data:m,start:w}=h.writer.stopTrackingWrites();this.formatOptions.onMoov(m,w)}if(this.isCmaf){p(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Li(this.writer);const m=this.boxWriter.measureBox(Zo()),w=this.boxWriter.measureBox(Jo(this,0));this.segmentHeaderSize=m+w,this.writer.seek(this.segmentHeaderSize)}}p(this.writer),p(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=tc(i,t),s=this.writer.getPos(),a=s+this.boxWriter.measureBox(n);let o=a+Pt,c=1/0;for(let h=0;h<t.length;h++){const g=t[h];p(g.currentChunk),p(g.startTimestampOffset!==null),g.currentChunk.offset=o,g.currentChunk.moofOff
8set=s,g.currentChunk.trafIndex=h,g.currentChunk.startTimestamp-=g.startTimestampOffset;for(const m of g.currentChunk.samples)o+=m.size,m.timestamp-=g.startTimestampOffset,m.decodeTimestamp-=g.startTimestampOffset;c=Math.min(c,g.currentChunk.startTimestamp)}const l=o-a,u=l>=2**32;if(u)for(const h of t)h.currentChunk.offset+=ir-Pt;this.formatOptions.onMoof&&this.writer.startTrackingWrites();const d=tc(i,t);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){const{data:h,start:g}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(h,g,c)}p(this.writer.getPos()===a),this.formatOptions.onMdat&&this.writer.startTrackingWrites();const f=qi(u);f.size=l,this.boxWriter.writeBox(f),this.writer.seek(a+(u?ir:Pt));for(const h of t)for(const g of h.currentChunk.samples)this.writer.write(g.data),g.data=null;if(this.formatOptions.onMdat){const{data:h,start:g}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(h,g)}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(){p(this.writer),p(this.boxWriter),this.ensureOneEnabledTrack();const e=ti(this),i=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;p(this.ftypSize!==null),this.writer.seek(this.ftypSize+i),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=qi(!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(){p(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const i=t.track.metadata.maximumPacketCount;p(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(){p(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){await this.finalizeCurrentChunk(t);const i=Ur(t);if(i>0){let o=0;for(const c of t.samples)o+=c.size;t.avgBitrate=Math.round(8*o/i)}else t.avgBitrate=0;let n=0,s=0,a=0;for(let o=0;o<t.samples.length;o++){const c=t.samples[o];for(s+=c.size;c.decodeTimestamp-t.samples[n].decodeTimestamp>=1;)s-=t.samples[n].size,n++;a=Math.max(a,s)}if(t.maxBitrate=8*a,t.startTimestampOffset!==null)for(let o=0;o<t.samples.length;o++){const c=t.samples[o];c.timestamp-=t.startTimestampOffset,c.decodeTimestamp-=t.startTimestampOffset}}if(p(this.writer),p(this.boxWriter),this.fastStart==="in-memory"){this.mdat=qi(!1);let t;for(let n=0;n<2;n++){const s=ti(this),a=this.boxWriter.measureBox(s);t=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)p(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=ti(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)p(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(Zo()),this.boxWriter.writeBox(Jo(this,t))}else{const t=this.writer.getPos(),i=Hm(this.trackDatas);this.boxWriter.writeBox(i);const n=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(n)}else{p(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);p(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=ti(this);if(this.fastStart==="reserve"){p(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($h(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 dp=-32768,fp=2**15-1,nc="Mediabunny",sc=6,ac=5,hp={video:1,audio:2,subtitle:17};class mp extends Mt{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=ne(),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.currentClusterMa
8xMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.warnedAboutTooNegativeTimestamp=!1,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new Yd(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:_.EBML,data:[{id:_.EBMLVersion,data:1},{id:_.EBMLReadVersion,data:1},{id:_.EBMLMaxIDLength,data:4},{id:_.EBMLMaxSizeLength,data:8},{id:_.DocType,data:this.format instanceof ds?"webm":"matroska"},{id:_.DocTypeVersion,data:2},{id:_.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:_.SeekHead,data:[{id:_.Seek,data:[{id:_.SeekID,data:t},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:_.Seek,data:[{id:_.SeekID,data:i},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:_.Seek,data:[{id:_.SeekID,data:n},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:_.Seek,data:[{id:_.SeekID,data:s},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:_.Seek,data:[{id:_.SeekID,data:a},{id:_.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:_.Duration,data:new Bs(0)};this.segmentDuration=e;const t={id:_.Info,data:[{id:_.TimestampScale,data:1e6},{id:_.MuxingApp,data:nc},{id:_.WritingApp,data:nc},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:_.Tracks,data:[]};this.tracksElement=e;for(const t of this.trackDatas){let i=ze[t.track.source._codec];p(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=se(s),o=Cn(a);n=Math.round(1e9*(o.preSkip/qr))}}e.data.push({id:_.TrackEntry,data:[{id:_.TrackNumber,data:t.track.id},{id:_.TrackUID,data:t.track.id},{id:_.TrackType,data:hp[t.type]},t.track.metadata.disposition?.default===!1?{id:_.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:_.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:_.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:_.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:_.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:_.FlagCommentary,data:1}:null,{id:_.FlagLacing,data:0},{id:_.Language,data:t.track.metadata.languageCode??Ie},{id:_.CodecID,data:i},t.codecPrivate?{id:_.CodecPrivate,data:se(t.codecPrivate)}:null,{id:_.CodecDelay,data:0},{id:_.SeekPreRoll,data:n},t.track.metadata.name!==void 0?{id:_.Name,data:new Ut(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,transformationMatrix:i}=e.track.metadata,n=[t?{id:_.DefaultDuration,data:1e9/t}:null];let s,a,o;if(i){s=ii(i);const g=Mr(Ys(-s),i);a=Math.sign(g[0]),o=Math.sign(g[4]),o===-1&&(o=1,a=-a,s=or(s+180))}else s=e.track.metadata.rotation??0,a=e.track.metadata.flip?-1:1,o=1;const c=s?or(a===-1?s:-s):0,l=Math.round(Math.acos(a)*gs),u=Math.round(Math.acos(o)*gs),d=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,f=e.info.decoderConfig.colorSpace,h={id:_.Video,data:[{id:_.PixelWidth,data:e.info.width},{id:_.PixelHeight,data:e.info.height},d?{id:_.DisplayWidth,data:e.info.aspectRatio.num}:null,d?{id:_.DisplayHeight,data:e.info.aspectRatio.den}:null,d?{id:_.DisplayUnit,data:3}:null,e.info.alphaMode?{id:_.AlphaMode,data:1}:null,Sc(f)?null:{id:_.Colour,data:[{id:_.MatrixCoefficients,data:f?.matrix!=null?mr[f.matrix]:2},{id:_.TransferCharacteristics,data:f?.transfer!=null?hr[f.transfer]:2},{id:_.Primaries,data:f?.primaries!=null?fr[f.primaries]:2},{id:_.Range,data:f?.fullRange!=null?f.fullRange?2:1:0}]},c||l||u?{id:_.Projection,data:[{id:_.ProjectionType,data:0},l?{id:_.ProjectionPoseYaw,data:new si(l)}:null,u?{id:_.ProjectionPosePitch,data:new si(u)}:null,c?{id:_.ProjectionPoseRoll,data:new si((c+180)%360-180)}:null]}:null]};return n.push(h),n}audioSpecificTrackInfo(e){const t=ke.includes(e.track.source._codec)?rt(e.track.source._codec):null;return[{id:_.Audio,data:[{id:_.SamplingFrequency,data:new si(e.info.sampleRate)},{id:_.Channels,data:e.info.numberOfChannels},t?{id:_.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){const e=[],t=(s,a)=>{e.push({id:_.SimpleTag,data:[{id:_.TagName,data:new Ut(s)}
8,typeof a=="string"?{id:_.TagString,data:new Ut(a)}:{id:_.TagBinary,data:a}]})},i=this.output._metadataTags,n=new Set;for(const{key:s,value:a}of Vr(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"beatsPerMinute":t("BPM",a.toString()),n.add("BPM");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:Ae(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:_.Tags,data:[{id:_.Tag,data:[{id:_.Targets,data:[{id:_.TargetTypeValue,data:50},{id:_.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")+(Vu(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:_.AttachedFile,data:[s.description!==void 0?{id:_.FileDescription,data:new Ut(s.description)}:null,{id:_.FileName,data:new Ut(a)},{id:_.FileMediaType,data:s.mimeType},{id:_.FileData,data:s.data},{id:_.FileUID,data:o}]})}for(const[s,a]of Object.entries(e.raw??{}))!(a instanceof ia)||!/^\d+$/.test(s)||n.find(c=>
8c.mimeType===a.mimeType&&Pc(c.data,a.data))||t.push({id:_.AttachedFile,data:[a.description!==void 0?{id:_.FileDescription,data:new Ut(a.description)}:null,{id:_.FileName,data:new Ut(a.name??"")},{id:_.FileMediaType,data:a.mimeType??""},{id:_.FileData,data:a.data},{id:_.FileUID,data:BigInt(s)}]});t.length!==0&&(this.attachmentsElement={id:_.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:_.Segment,size:this.format._options.appendOnly?-1:sc,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:_.Cues,data:[]}}get segmentDataOffset(){return p(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 ml({isWebM:this.format instanceof ds,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;Fi(i,e.source._codec),p(i),p(i.decoderConfig),p(i.decoderConfig.codedWidth!==void 0),p(i.decoderConfig.codedHeight!==void 0);const s=i.decoderConfig.displayAspectWidth,a=i.decoderConfig.displayAspectHeight,o=s===void 0||a===void 0?null:zr({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(Id(c.info.decoderConfig.codec)):e.source._codec==="av1"?c.codecPr
8ivate=new Uint8Array($c(c.info.decoderConfig.codec)):e.source._codec==="prores"&&(c.codecPrivate=Z.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;it(i,e.source._codec),p(i),p(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=vt(De.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=Qt[c.samplingFrequencyIndex],u=Wr[c.channelConfiguration];if(l===void 0||u===void 0)throw new Error("Invalid ADTS frame header.");s.description=na({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;Jc(t),p(t),p(t.config);const n={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:Z.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=Dr(c,e.metadata.frameRate),l=Dr(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=vt(De.tempFromBytes(a));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const u=l.crcCheck===null?Ai:Kt;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);pn.lastIndex=0,a=a.replace(pn,d=>{const h=Qs(d.slice(1,-1))-o;return`<${ou(h)}>`});const c=Z.encode(a),l=`${t.settings??""}
9${t.identifier??""}
10${t.notes??""}`,u=this.createInternalChunk(c,t.timestamp,t.duration,"key",l.trim()?Z.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 H(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];Cu(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=>
10{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{p(this.currentClusterStartMsTimestamp!==null),p(this.currentClusterMaxMsTimestamp!==null);const d=i-this.currentClusterStartMsTimestamp;s=n&&i>this.currentClusterMaxMsTimestamp&&d>=1e3*(this.format._options.minimumClusterDuration??1)||d>fp}s&&this.createNewCluster(i);const a=i-this.currentClusterStartMsTimestamp;if(a<dp){if(!this.warnedAboutTooNegativeTimestamp){const d=this.format instanceof ds?"WebM":"Matroska";O._warn(`Packets had to be discarded because their timestamp is too negative to represent in ${d}.`),this.warnedAboutTooNegativeTimestamp=!0}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:_.BlockGroup,data:[{id:_.Block,data:[o,t.data]},t.type==="delta"?{id:_.ReferenceBlock,data:new ul(e.lastWrittenMsTimestamp-i)}:null,t.additions?{id:_.BlockAdditions,data:[{id:_.BlockMore,data:[{id:_.BlockAddID,data:1},{id:_.BlockAdditional,data:t.additions}]}]}:null,l>0?{id:_.BlockDuration,data:l}:null]};this.ebmlWriter.writeEBML(d)}else{c.setUint8(3,+(t.type==="key")<<7);const d={id:_.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){e=Math.max(0,e),this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:_.Cluster,size:this.format._options.appendOnly?-1:ac,data:[{id:_.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(p(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,ac),this.writer.seek(s)}if(this.format._options.onCluster){p(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)p(this.cues),this.cues.data.push({id:_.CuePoint,data:[{id:_.CueTime,data:Math.max(0,n)},...s.map(a=>({id:_.CueTrackPositions,data:[{id:_.CueTrack,data:a.track.id},{id:_.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(),p(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,sc);const i=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new Bs(i),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),p(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}class pp{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){const t=this.writer.getPos(),i=255,n=224|e.mpegVersionId<<3|e.layer<<1;let s;e.mpegVersionId&2?s=e.mpegVersionId&1?0:1:s=1;const a=0,o=155;let c=-1;const l=s*16*4+e.layer*16;for(let w=0;w<16;w++){const y=_s[l+w];if(Is(s,e.layer,1e3*y,e.sampleRate,a)>=o){c=w;break}}if(c===-1)throw new Error("No suitable bitrate found.");const u=c<<4|e.frequencyIndex<<2|a<<1,d=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=i,this.helper[1]=n,this.helper[2]=u,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));const f=En(e.mpegVersionId,e.channel);this.writer.seek(t+f),this.writeU32(In);let h=0;e.frameCount!==null&&(h|=ur.FrameCount),e.fileSize!==null&&(h|=ur.FileSize),e.toc!==null&&(h|=ur.Toc),this.writeU32(h),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));const g=_s[l+c],m=Is(s,e.layer,1e3*g,e.sampleRate,a);
10this.writer.write(new Uint8Array(t+m-this.writer.getPos()))}}class gp extends Mt{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(this.format._options.xingHeader===!1),this.mp3Writer=new pp(this.writer),yi(this.output._metadataTags)||new Ia(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){const i=await this.mutex.acquire();try{const n=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&n){const s=q(t.data);if(s.byteLength<4)throw new Error("Invalid MP3 header in sample.");const a=s.getUint32(0,!1),o=ki(a,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");const c=En(o.mpegVersionId,o.channel);if(s.byteLength>=c+4){const l=s.getUint32(c,!1);if(l===In||l===pa)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,t.timestamp,t.type==="key"),n&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(!this.xingFrameData&&this.format._options.xingHeader===!1)throw new Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");if(!this.xingFrameData){const n=this.output.tracks[0];p(n?.isAudioTrack());const s=n.metadata.primingPacket;if(s){const a=q(s.data);if(a.byteLength<4)throw new Error("Invalid MP3 header in priming packet.");const o=a.getUint32(0,!1),c=ki(o,null).header;if(!c)throw new Error("Invalid MP3 header in priming packet.");this.xingFrameData={mpegVersionId:c.mpegVersionId,layer:c.layer,frequencyIndex:c.frequencyIndex,sampleRate:c.sampleRate,channel:c.channel,modeExtension:c.modeExtension,copyright:c.copyright,original:c.original,emphasis:c.emphasis,frameCount:null,fileSize:null,toc:null}}else if(n.metadata.decoderConfig){const{sampleRate:a,numberOfChannels:o}=n.metadata.decoderConfig,c=[3,2,0];let l=null,u=-1;for(let d=0;d<c.length;d++)if(u=el.indexOf(a<<d),u!==-1){l=c[d];break}if(l===null)throw new Error(`${a} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:l,layer:1,frequencyIndex:u,sampleRate:a,channel:o===1?3:0,modeExtension:0,copyright:0,original:0,emphasis:0,frameCount:null,fileSize:null,toc:null}}else throw new Error("Cannot finalize an empty MP3 file: no packets were added and the track specified neither a decoderConfig nor a primingPacket in its metadata, so there's no telling what the file should look like.");this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}p(this.xingFramePos!==null);const i=this.writer.getPos()-this.xingFramePos;if(this.writer.seek(this.xingFramePos),this.framePositions.length>0){const n=new Uint8Array(100);for(let s=0;s<100;s++){const a=Math.floor(this.framePositions.length*(s/100)),o=this.framePositions[a]-this.xingFramePos;n[s]=256*(o/i)}this.xingFrameData.toc=n}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=i,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){const{data:n,start:s}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,s)}e()}}const wp=8192;class yp extends Mt{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=ne(),this.pageBytes=new Uint8Array(Tl),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0);for(const t of this.output.tracks)p(t.isAudioTrack()),t.metadata.decoderConfig&&this.getTrackData(t,{decoderConfig:t.metadata.decoderConfig});e()}async getMimeType(){return await this.allTracksKnown.promise,kl({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,t){const i=this.trackDatas.find(a=>a.track===e);if(i)return i;let n;do n=Math.floor(2**32*Math.random());while(this.trackDatas.some(a=>a.serialNumber===n));p(e.source._codec==="vorbis"||e.source._codec==="opus"),it(t,e.source._codec),p(t),p(t.decoderConfig);const s={track:e,serialNumber:n,internalSampleRate:e.source._codec==="opus"?qr:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,
10currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,t),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,t){if(p(t.decoderConfig),e.track.source._codec==="vorbis"){p(t.decoderConfig.description);const i=se(t.decoderConfig.description);if(i[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let n=1;const s=()=>{let m=0;for(;;){const w=i[n++];if(w===void 0)throw new TypeError("Vorbis decoder description is too short.");if(m+=w,w<255)return m}},a=s(),o=s();if(i.length-n<=0)throw new TypeError("Vorbis decoder description is too short.");const l=i.subarray(n,n+=a);n+=o;const u=i.subarray(n),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;const f=Ps(d,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:f,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:u,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});const g=q(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(g&15),1<<(g>>4)],modeBlockflags:Nc(u).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!t.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const i=se(t.decoderConfig.description),n=new Uint8Array(8),s=q(n);s.setUint32(0,1332770163,!1),s.setUint32(4,1415669619,!1);const a=Ps(n,this.output._metadataTags,!0);e.packetQueue.push({data:i,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:Cn(i).preSkip}}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const s=this.getTrackData(e,i);this.validateTimestamp(s.track,t.timestamp,t.type==="key");const a=s.currentTimestampInSamples,{durationInSamples:o,vorbisBlockSize:c}=bl(t.data,s.codecInfo,s.vorbisLastBlocksize);s.currentTimestampInSamples+=o,s.vorbisLastBlocksize=c,s.packetQueue.push({data:t.data,timestampInSamples:a,durationInSamples:o,forcePageFlush:!1}),await this.interleavePages()}finally{n()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(const t of this.trackDatas)for(;t.packetQueue.length>0;){const i=t.packetQueue.shift();if(this.writePacket(t,i,!1),i.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let t=null,i=1/0;for(const a of this.trackDatas){if(!e&&a.packetQueue.length<=1&&!a.closed)break e;a.packetQueue.length>0&&a.packetQueue[0].timestampInSamples<i&&(t=a,i=a.packetQueue[0].timestampInSamples)}if(!t)break;const n=t.packetQueue.shift(),s=t.packetQueue.length===0;this.writePacket(t,n,s)}e||await this.writer.flush()}writePacket(e,t,i){const n=t.timestampInSamples+t.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){const l=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&n-e.currentPageStartTimestampInSamples>l&&this.writePage(e,!1)}let s=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);const l=Math.min(255,s);e.currentLacingValues.push(l),e.currentPageSize++,o+=l;const u=s<255;if(e.currentLacingValues.length===255){const d=t.data.subarray(a,o);if(a=o,e.currentPageData.push(d),e.currentPageSize+=d.length,this.writePage(e,i&&u),u)return}if(u)break;s-=255}const c=t.data.subarray(a);e.currentPageData.push(c),e.currentPageSize+=c.length,e.currentGranulePosition=n,(e.currentPageSize>=wp||t.forcePageFlush)&&this.writePage(e,i)}writePage(e,t){this.pageView.setUint32(0,ya,!0),this.pageView.setUint8(4,0);let i=0;e.currentPageStartsWithFreshPacket||(i|=1),e.pagesWritten===0&&(i|=2),t&&(i|=4),this.pageView.setUint8(5,i);const n=e.currentLacingValues.every(c=>c===255)?-1:e.currentGranulePosition;Mu(this.pageView,6,n),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(const c of e.currentPageData)this.pageBytes.set(c,s),s+=c.length;const a=this.pageBytes.subarray(0,s),o=yl(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){const{data:c,start:l}=this.writer.stopTrackingWrites();this.format._options.onPage(c,l,e.track.source)}}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.interleavePages(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;await this.interleavePages(!0);for(const t of this.trackDatas)t.currentLacingValues.length>0&&this.writePage(t,!0);e()}}const bp=0,wu=4096,oc=256,kp=224,cc=192,lc=new Uint8Array([9,240]),uc=new Uint8Array([70,1]);class Tp extends Mt{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(Oe),this.packetView=q(this.packetBuffer),this.allTracksKnown=ne(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,Pl(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){const i=this.trackDatas.find(l=>l.track===e);if(i)return i;Fi(t,e.source._codec),p(t?.decoderConfig);const n=e.source._codec;p(n==="avc"||n==="hevc");const s=n==="avc"?27:36,a=oc+this.trackDatas.length,o=kp+this.videoTrackIndex++,c={track:e,pid:a,streamType:s,streamId:o,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1}
10;return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t){const i=this.trackDatas.find(l=>l.track===e);if(i)return i;it(t,e.source._codec),p(t?.decoderConfig);const n=e.source._codec;p(n==="aac"||n==="mp3"||n==="ac3"||n==="eac3"||n==="dts");let s,a;switch(n){case"aac":s=15,a=cc+this.audioTrackIndex++;break;case"mp3":s=3,a=cc+this.audioTrackIndex++;break;case"ac3":s=129,a=189;break;case"eac3":s=135,a=189;break;case"dts":s=130,a=189;break}const o=oc+this.trackDatas.length,c={track:e,pid:o,streamType:s,streamId:a,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}async addEncodedVideoPacket(e,t,i){const n=await this.mutex.acquire();try{const s=this.getVideoTrackData(e,i);this.validateTimestamp(s.track,t.timestamp,t.type==="key");const a=this.prepareVideoPacket(s,t,i);t.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{n()}}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{const s=this.getAudioTrackData(e,i);this.validateTimestamp(s.track,t.timestamp,t.type==="key");const a=this.prepareAudioPacket(s,t,i);t.type==="key"&&await this.flushTimestampQueue(s),s.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{n()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,t,i){const n=e.track.source._codec;if(e.inputIsAnnexB===null){const s=i?.decoderConfig?.description;if(e.inputIsAnnexB=!s,!e.inputIsAnnexB){const a=se(s);n==="avc"?e.avcDecoderConfig=oa(a):e.hevcDecoderConfig=Dc(a)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,n):this.prepareLengthPrefixedVideoPacket(e,t,n)}prepareAnnexBVideoPacket(e,t){const i=[];for(const s of Lr(e)){const a=e.subarray(s.offset,s.offset+s.length);(t==="avc"?dr(a[0])===ye.AUD:Gt(a[0])===ae.AUD_NUT)||i.push(a)}const n=t==="avc"?lc:uc;return i.unshift(n),nn(i)}prepareLengthPrefixedVideoPacket(e,t,i){const n=t.data,s=i==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(const c of sa(n,s)){const l=n.subarray(c.offset,c.offset+c.length);(i==="avc"?dr(l[0])===ye.AUD:Gt(l[0])===ae.AUD_NUT)||a.push(l)}if(t.type==="key")if(i==="avc"){const c=e.avcDecoderConfig;for(const l of c.pictureParameterSets)a.unshift(l);for(const l of c.sequenceParameterSets)a.unshift(l)}else{const c=e.hevcDecoderConfig;for(const l of c.arrays)if(l.nalUnitType===ae.PPS_NUT)for(const u of l.nalUnits)a.unshift(u);for(const l of c.arrays)if(l.nalUnitType===ae.SPS_NUT)for(const u of l.nalUnits)a.unshift(u);for(const l of c.arrays)if(l.nalUnitType===ae.VPS_NUT)for(const u of l.nalUnits)a.unshift(u)}const o=i==="avc"?lc:uc;return a.unshift(o),nn(a)}prepareAudioPacket(e,t,i){const n=e.track.source._codec;if(n==="mp3"||n==="ac3"||n==="eac3"||n==="dts")return t.data;if(e.inputIsAdts===null){const c=i?.decoderConfig?.description;if(e.inputIsAdts=!c,!e.inputIsAdts){const l=Bi(se(c)),u=Ec(l);e.adtsHeader=u.header,e.adtsHeaderBitstream=u.bitstream}}if(e.inputIsAdts)return t.data;p(e.adtsHeader),p(e.adtsHeaderBitstream);const s=e.adtsHeader,a=t.data.byteLength+s.byteLength;vc(e.adtsHeaderBitstream,a);const o=new Uint8Array(a);return o.set(s,0),o.set(t.data,s.byteLength),o}allTracksAreKnown(){for(const e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async flushTimestampQueue(e,t=!0){if(e.timestampProcessingQueue.length===0)return;const i=e.timestampProcessingQueue.map(n=>n.presentationTimestamp).sort((n,s)=>n-s);for(let n=0;n<e.timestampProcessingQueue.length;n++){const s=e.timestampProcessingQueue[n];s.decodeTimestamp=i[n],e.packetQueue.push(s)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}
10async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let t=null,i=1/0;for(const s of this.trackDatas){if(!e&&s.packetQueue.length===0&&!s.closed)break e;s.packetQueue.length>0&&s.packetQueue[0].presentationTimestamp<i&&(t=s,i=s.packetQueue[0].presentationTimestamp)}if(!t)break;const n=t.packetQueue.shift();this.writePesPacket(t,n)}e||await this.writer.flush()}writeTables(){p(!this.tablesWritten),this.writePsiSection(bp,Jt),this.writePsiSection(wu,Ap(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let i=0,n=!0;for(;i<t.length;){const a=184-(n?1:0),o=t.length-i,c=Math.min(a,o);let l;n?(l=this.payloadBuffer.subarray(0,1+c),l[0]=0,l.set(t.subarray(i,i+c),1)):l=t.subarray(i,i+c),this.writeTsPacket(e,n,null,l),i+=c,n=!1}}writePesPacket(e,t){const i=e.track.type==="video",n=i?10:5,s=new Uint8Array(9+n),a=q(s),o=new H(s.subarray(9));bn(a,0,1,!1),s[3]=e.streamId;const c=e.track.type==="video"?0:Math.min(8+t.data.length,65535);a.setUint16(4,c,!1),a.setUint8(6,132),a.setUint8(7,i?192:128),a.setUint8(8,n);const l=Math.round(t.presentationTimestamp*He),u=Va(l,di);if(o.pos=0,o.writeBits(4,i?3:2),o.writeBits(3,Math.floor(u/2**30)),o.writeBits(1,1),o.writeBits(15,Math.floor(u/2**15)%2**15),o.writeBits(1,1),o.writeBits(15,u%2**15),o.writeBits(1,1),i){p(t.decodeTimestamp!==null);const g=Math.round(t.decodeTimestamp*He),m=Va(g,di);o.writeBits(4,1),o.writeBits(3,Math.floor(m/2**30)),o.writeBits(1,1),o.writeBits(15,Math.floor(m/2**15)%2**15),o.writeBits(1,1),o.writeBits(15,m%2**15),o.writeBits(1,1)}const d=s.length+t.data.length;let f=0,h=!0;for(;f<d;){const g=h,m=d-f,w=h&&t.isKeyframe,y=h&&!e.firstPacketWritten,b=Math.max(0,184-m);let k;w||y?k=Math.max(2,b):k=b;let S=null;if(k>0){const I=this.adaptationFieldBuffer;k===1?I[0]=0:(I[0]=k-1,I[1]=Number(y)<<7|Number(w)<<6,I.fill(255,2,k)),S=I.subarray(0,k)}const T=Math.min(184-k,m),A=this.payloadBuffer.subarray(0,T);let P=0;if(f<s.length){const I=Math.min(s.length-f,T);A.set(s.subarray(f,f+I),0),P=I}const C=Math.max(0,f-s.length),x=C+(T-P);P<T&&A.set(t.data.subarray(C,x),P),this.writeTsPacket(e.pid,g,S,A),f+=T,h=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,i,n){const s=this.continuityCounters.get(e)??0,a=n.length>0,o=i?a?3:2:a?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(t?16384:0)|e&8191,!1),this.packetBuffer[3]=o<<4|s&15,a&&this.continuityCounters.set(e,s+1&15);let c=4;i&&(this.packetBuffer.set(i,c),c+=i.length),this.packetBuffer.set(n,c),c+=n.length,c<Oe&&this.packetBuffer.fill(255,c);const l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(n=>n.track===e);i&&(i.closed=!0,await this.flushTimestampQueue(i,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0,await this.flushTimestampQueue(t,!1);await this.interleavePackets(!0),e()}}const Sp=79764919,yu=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^Sp:e<<1;yu[r]=e>>>0&4294967295}const bu=r=>{let e=4294967295;for(let t=0;t<r.length;t++){const i=r[t];e=(e<<8^yu[e>>>24^i])>>>0}return e},Jt=new Uint8Array(16);{const r=q(Jt);Jt[0]=0,r.setUint16(1,45069,!1),r.setUint16(3,1,!1),Jt[5]=193,Jt[6]=0,Jt[7]=0,r.setUint16(8,1,!1),r.setUint16(10,57344|wu&8191,!1),r.setUint32(12,bu(Jt.subarray(0,12)),!1)}const Ap=r=>{let e=0;for(const c of r)e+=5,c.streamType===129?e+=Ui.length:c.streamType===135&&(e+=Ni.length);const t=9+e+4,i=new Uint8Array(3+t-4),n=q(i);i[0]=2,n.setUint16(1,45056|t&4095,!1),n.setUint16(3,1,!1),i[5]=193,i[6]=0,i[7]=0,n.setUint16(8,65535,!1),n.setUint16(10,61440,!1);let s=12;for(const c of r)i[s++]=c.streamType,n.setUint16(s,57344|c.pid&8191,!1),s+=2,c.streamType===129?(n.setUint16(s,61440|Ui.length,!1),s+=2,i.set(Ui,s),s+=Ui.length):c.streamType===135?(n.setUint16(s,61440|Ni.length,!1),s+=2,i.set(Ni,s),s+=Ni.length):(n.setUint16(s,61440,!1),s+=2);const a=bu(i),o=new Uint8Array(i.length+4);return o.set(i,0),q(o).setUint32(i.length,a,!1),o};class xp{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(Z.encode(e))}}class Pp extends Mt{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new xp(this.writer);const t=this.output.tracks[0];p(t?.isAudioTrack()),t.metadata.decoderConfig&&(it({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.writeHeader(t,t.metadata.decoderConfig),this.sampleRate=t.metadata.decoderConfig.sampleRate,this.headerWritten=!0),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,i){const n=await this.mutex.acquire();try{if(this.headerWritten||(it(i,e.source._codec),p(i),p(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,t.type==="
10key"),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{n()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let i;const n=e.source._codec,s=rt(n);s.dataType==="ulaw"?i=Se.MULAW:s.dataType==="alaw"?i=Se.ALAW:s.dataType==="float"?i=Se.IEEE_FLOAT:i=Se.PCM;const a=t.numberOfChannels,o=t.sampleRate,c=s.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(i),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*c),this.riffWriter.writeU16(c),this.riffWriter.writeU16(8*s.sampleSize),!yi(this.output._metadataTags)){const l=this.format._options.metadataFormat??"info";l==="info"?this.writeInfoChunk(this.output._metadataTags):l==="id3"?this.writeId3Chunk(this.output._metadataTags):Ae(l)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){const{data:l,start:u}=this.writer.stopTrackingWrites();this.format._options.onHeader(l,u)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const i=new Set,n=(o,c)=>{if(!gt(c)){O._warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}const l=c.length+1,u=new Uint8Array(l);for(let d=0;d<c.length;d++)u[d]=c.charCodeAt(d);this.riffWriter.writeAscii(o),this.riffWriter.writeU32(l),this.writer.write(u),l&1&&this.writer.write(new Uint8Array(1)),i.add(o)};for(const{key:o,value:c}of Vr(e))switch(o){case"title":n("INAM",c),i.add("INAM");break;case"artist":n("IART",c),i.add("IART");break;case"album":n("IPRD",c),i.add("IPRD");break;case"trackNumber":{const l=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();n("ITRK",l),i.add("ITRK")}break;case"genre":n("IGNR",c),i.add("IGNR");break;case"date":n("ICRD",c.toISOString().slice(0,10)),i.add("ICRD");break;case"comment":n("ICMT",c),i.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"beatsPerMinute":case"description":case"lyrics":case"images":break;case"raw":break;default:Ae(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];c==null||o.length!==4||i.has(o)||typeof c=="string"&&n(o,c)}const s=this.writer.getPos(),a=s-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(s),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);const n=new Ia(this.writer).writeId3V2Tag(e),s=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(n),this.writer.seek(s),n&1&&this.writer.write(new Uint8Array(1))}async finalize(){const e=await this.mutex.acquire();if(!this.headerWritten)throw new Error("Cannot finalize an empty WAVE file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");const t=this.writer.getPos();this.isRf64?(p(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),p(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),p(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(p(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),p(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}}class Cp{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}doChannelMixerSetup(){p(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)=>s<2?i[n*e+s]:0:e===2&&t===6?this.channelMixer=(i,n,s)=>s<2?i[n*e+s]:0: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){if(this.sourceSampleRate===null){this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp;const l=Math.ceil(this.targetSampleRate/this.sourceSampleRate);this.bufferCapacityInFrames=this.bufferSizeInFrames+l,this.outputBuffer=new Float32Array(this.bufferCapacityInFrames*this.targetNumberOfChannels),this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()}p(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.bufferCapacityInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const u=l-this.bufferStartFrame;p(u<this.bufferCapacityInFrames);const h=(l/this.targetSampleRate-s)*this.sourceSampleRate,g=Math.floor(h),m=Math.ceil(h),w=h-g;for(let y=0;y<this.targetNumberOfChannels;y++){let b=0,k=0;g>=0&&g<e.numberOfFrames&&(b=this.channelMixer(n,g,y)),m>=0&&m<e.numberOfFrames&&(k=this.channelMixer(n,m,y));const S=b+w*(k-b),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;p(this.startTime!==null);const e=Math.min(this.maxWrittenFrame+1,this.bufferSizeInFrames)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const i=new be({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),this.outputBuffer.copyWithin(0,this.bufferSizeInSamples),this.outputBuffer.fill(0,this.outputBuffer.length-this.bufferSizeInSamples),this.maxWrittenFrame=this.maxWrittenFrame>=this.bufferSizeInFrames?this.maxWrittenFrame-this.bufferSizeInFrames:null}async finalize(){for(;this.maxWrittenFrame!==null;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames}}var _p=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},Ip=(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)}
10if(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 Fa{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._nominalBitrate=null}_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 Mi extends Fa{constructor(e){if(super(),!we.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${we.join(", ")}.`);this._codec=e}}const Gs=(r,e)=>{if(r.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class $s extends Mi{constructor(e){super(e)}add(e,t){if(!(e instanceof te))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(),Gs(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class Ra{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
10dedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new kn,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?.flip!==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"&&(p(this.outputWidth),p(this.outputHeight),p(a!=="deny"),d=this.outputWidth,f=this.outputHeight,h=a);const g=await e.transform({width:d,height:f,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,flip:s.transform?.flip,fit:h,alpha:s.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=g.displayWidth,this.outputHeight=g.displayHeight),t&&e.close(),e=g,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=Wa(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(v(s)&&(s=await s),s===null)return;Array.isArray(s)||(s=[s]);const a=[];try{for(const o of s)o instanceof _e?a.push(o):typeof VideoFrame<"u"&&o instanceof VideoFrame?a.push(new _e(o)):a.push(new _e(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 _e&&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),p(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{p(this.encoder);const u=s.toVideoFrame(),d=X(this.preciseTimings,u.timestamp,h=>h.microsecondTimestamp),f=d!==-1?this.preciseTimings[d]:null;if(f&&f.microsecondTimestamp===u.timestamp?(f.timestamp!==s.timestamp&&(f.timestampIsValid=!1),f.duration!==s.duration&&(f.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:u.timestamp,timestamp:s.timestamp,duration:s.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(!!u.format&&!u.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(u,l)}finally{u.close()}}else{this.splitter||(this.splitter=new Ep);const{colorFrame:g,alphaFrame:m}=await this.splitter.split(u);this.alphaFrameQueue.push(m);try{this.encoder.encode(g,l)}finally{g.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;p(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=_p(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{Ip(a)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const t=Or(this.encodingConfig.quality,this.encodingConfig.bitrate);p(t!==void 0);const i=Zl({...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=hn.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(Tn("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=tu(this.encodingConfig.codec,n.quantizer):this.source._nominalBitrate=a.bitrate??null,s)this.customEncoder=new s,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(o,c)=>{if(!(o instanceof te))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.");Gs(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,g,m)=>{const w={};if(g){const T=new Uint8Array(g.byteLength);g.copyTo(T),w.alpha=T}let y=te.fromEncodedChunk(h,w);const b=X(this.preciseTimings,h.timestamp,T=>T.microsecondTimestamp),k=b!==-1?this.preciseTimings[b]:null;let S=null;this.emittedEncoderPackets===0&&y.type==="delta"&&m?.decoderConfig&&(S=_n(this.encodingConfig.codec,m.decoderConfig,y.data)),(k&&k.microsecondTimestamp===h.timestamp||S!==null)&&(y=y.clone({t
10imestamp:k?.timestampIsValid?k.timestamp:void 0,duration:k?.durationIsValid?k.duration:void 0,type:S??void 0})),Gs(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,g)=>{if(!this.alphaEncoder){d(h,null,g);return}const m=this.alphaFrameQueue.shift();p(m!==void 0),m?(this.alphaEncoder.encode(m,{...this.defaultEncodeOptions,keyFrame:h.type==="key"}),u++,m.close(),o.push({chunk:h,meta:g})):u===0?d(h,null,g):(c.push(l+u),o.push({chunk:h,meta:g}))},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:(g,m)=>{u--;const w=o.shift();for(p(w!==void 0),d(w.chunk,g,w.meta),l++;c.length>0&&c[0]===l;){c.shift();const y=o.shift();p(y!==void 0),d(y.chunk,null,y.meta)}},error:g=>{g.stack=h,this.setError(g)}}),this.alphaEncoder.configure(a)}}p(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=Wa(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 wi(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 cs=null;class Ep{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!cs){const n=new Blob([`(${vp.toString()})()`],{type:"application/javascript"});cs=URL.createObjectURL(n)}this.worker=new Worker(cs),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=ne();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 vp=()=>{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.coded
10Height,u=c*l,d=Math.ceil(c/2),f=Math.ceil(l/2),h=u+d*f*2,g=new Uint8Array(h);for(let b=0,k=3;b<u;b++,k+=4)g[b]=s[k];g.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}),w={format:"I420",codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[g.buffer]},y=new VideoFrame(g,w);return{colorFrame:m,alphaFrame:y}},n=(s,a,o)=>{const c=o.visibleRect?.width??o.codedWidth,l=o.visibleRect?.height??o.codedHeight,u=a.includes("P10"),d=a.includes("P12"),f=u||d?2:1;let h,g;a.startsWith("I420")?(h=Math.ceil(c/2),g=Math.ceil(l/2)):a.startsWith("I422")?(h=Math.ceil(c/2),g=l):(h=c,g=l);const m=c*l,w=h*g,y=m*f,b=w*f,k=m*f,S=y+b*2,T=a.replace("A",""),A=Math.ceil(c/2),P=Math.ceil(l/2),C=A*P,x=C*f,I=k+2*x,E=new Uint8Array(I),F=S;E.set(s.subarray(F,F+k),0);const D=k,z=u?512:d?2048:128;f===1?E.fill(z,D):new Uint16Array(E.buffer,D,2*C).fill(z);const V=u?"I420P10":d?"I420P12":"I420",j=new VideoFrame(s.subarray(0,S),{format:T,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0}),oe={format:V,codedWidth:c,codedHeight:l,timestamp:o.timestamp,duration:o.duration??void 0,transfer:[E.buffer]},re=new VideoFrame(E,oe);return{colorFrame:j,alphaFrame:re}}};class dc extends Mi{constructor(e){Sa(e),super(e.codec),this._encoder=new Ra(this,e)}add(e,t){if(!(e instanceof _e))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class gg extends Mi{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.");Sa(t),super(t.codec),this._encoder=new Ra(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e))throw new TypeError("timestamp must be a finite number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const n=new _e(this._canvas,{timestamp:e,duration:t});return this._encoder.add(n,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class wg extends Mi{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(Sa(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.frameRate!=null&&(typeof i.frameRate!="number"||i.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");t={...t,latencyMode:"realtime"},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=ne(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=i,this._encoder=new Ra(this,t),this._track=e}async _start(){this._errorPromiseAccessed||O._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");const e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let t=null,i=null,n=0,s=!1,a=null,o=0;const c=()=>{if(p(e!==null),!this._lastVideoFrame)return;p(i!==null),p(t!==null);const d=performance.now();for(;d-i>1e3/e;){i+=1e3/e;const f=t+n/e,h=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*f,duration:1e6/e});u(h,d)}};e!==null&&(this._timerHandle=ju(c,4));const l=d=>{if(e===null)u(d);else{const f=performance.now();this._lastVideoFrame?(c(),this._lastVideoFrame?.close(),this._lastVideoFrame=d):(u(d.clone(),f),i=f,this._lastVideoFrame=d)}},u=(d,f=performance.now())=>{if(s){d.close();return}n++;const h=d.timestamp/1e6;if(this._paused){if(t!==null){if(a!==null&&this._options.timestampBase!=="unix"){const w=h-a;o-=w}a=h}d.close();return}if(t===null){t=h;let m;const w=this._options.timestampBase??"synced-zero";if(w==="unix")m=Date.now()/1e3;else if(w==="zero")m=0;else{const y=this._connectedTrack.output;y._firstMediaStreamTimestamp===null?(y._firstMediaStreamTimestamp=f/1e3,m=0):m=f/1e3-y._firstMediaStreamTimestamp}o=m-t}if(a=h,this._encoder.getQueueSize()>=8){d.close();return}const g=new _e(d,{timestamp:h+o});this._encoder.add(g,!0).catch(m=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(m),this._workerTrackId!==null&&us({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const d=new MediaStreamTrackProcessor({track:this._track}),f=new WritableStream({write:l});d.readable.pipeTo(f,{signal:this._abortController.signal}).catch(h=>{h instanceof DOMException&&h.name==="AbortError"||this._promiseWithResolvers.reject(h)})}else if(await Dp())this._workerTrackId=Rp++,us({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=f=>{const h=f.data;h.type==="videoFrame"&&h.trackId===this._workerTrackId?l(h.videoFrame):h.type==="error"&&h.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(h.error)},et.addEventListener("message",this._workerListener);else if(e!==null){const f=document.createElement("video");f.style.position="fixed",f.style.left="-10000px",f.style.top="-10000px",f.style.width="1px",f.style.height="1px",f.style.opacity="0",f.style.pointerEvents="none",f.muted=!0,f.srcObject=ne
10w MediaStream([this._track]),document.body.appendChild(f),this._videoElement=f,f.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;const h=new VideoFrame(f,{timestamp:1e3*performance.now()});l(h),h.close()},{once:!0}),f.play().catch(h=>{s=!0,this._promiseWithResolvers.reject(h)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not available in this environment.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&Ku(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(p(this._workerListener),us({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(t=>{const i=n=>{const s=n.data;s.type==="trackStopped"&&s.trackId===this._workerTrackId&&(p(this._workerListener),et.removeEventListener("message",this._workerListener),et.removeEventListener("message",i),t())};et.addEventListener("message",i)}))}finally{await this._encoder.flushAndClose(e)}}}class Di extends Fa{constructor(e){if(super(),!xe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${xe.join(", ")}.`);this._codec=e}}class Xs extends Di{constructor(e){super(e)}add(e,t){if(!(e instanceof te))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 Ma{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 kn,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 Cp({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&&dh(e.format)!==i.transform.sampleFormat){const n=hh(e,i.transform.sampleFormat);t&&e.close(),e=n,t=!0}if(i.transform?.process)try{let n=i.transform.process(e);if(v(n)&&(n=await n),n===null)return;Array.isArray(n)||(n=[n]);try{for(const s of n)if(!(s instanceof be))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 be&&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),p(this.encoderInitialized),this.closed)return;
10{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 be({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{p(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){p(this.outputSampleSize),p(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:n,sampleRate:s,timestamp:a}=e,o=2048,c=[];for(let m=0;m<n;m+=o){const w=Math.min(o,e.numberOfFrames-m),y=w*i*this.outputSampleSize,b=new ArrayBuffer(y),k=new DataView(b);c.push({frameCount:w,view:k})}const l=e.format==="s32"||e.format==="s32-planar",u=l?"s32-planar":"f32-planar",d=l?1/2147483648:1,f=e.allocationSize({planeIndex:0,format:u}),h=l?new Int32Array(f/4):new Float32Array(f/4);for(let m=0;m<i;m++){e.copyTo(h,{planeIndex:m,format:u});for(let w=0;w<c.length;w++){const{frameCount:y,view:b}=c[w];for(let k=0;k<y;k++)this.writeOutputValue(b,(k*i+m)*this.outputSampleSize,h[w*o+k]*d)}}t&&e.close();const g={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let m=0;m<c.length;m++){const{frameCount:w,view:y}=c[m],b=y.buffer,k=m*o,S=new te(new Uint8Array(b),"key",a+k/s,w/s);this.encodingConfig.onEncodedPacket?.(S,g),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,S,g)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:i}=e,n=Or(this.encodingConfig.quality,this.encodingConfig.bitrate),s=eu({numberOfChannels:t,sampleRate:i,...this.encodingConfig,quality:n});this.encodingConfig.onEncoderConfig?.(s),this.source._nominalBitrate=s.bitrate??null;const a=mn.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 te))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(ke.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error(Tn("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=Bi(se(u.decoderConfig.description)).objectType===0,f){const h=Number(ue(s.codec.split(".")));u.decoderConfig.description=na({objectType:h,outputNumberOfChannels:u.decoderConfig.numberOfChannels,outputSampleRate:u.decoderConfig.sampleRate})}}let d=te.fromEncodedChunk(l);
10d=d.clone({timestamp:Dr(d.timestamp,s.sampleRate),duration:l.duration!=null?Dr(d.duration,s.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(d,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,u).catch(f=>{this.setError(f)})},error:l=>{l.stack=c,this.setError(l)}}),this.encoder.configure(s)}p(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}=rt(e);switch(this.outputSampleSize=i,i){case 1:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint8(a,le(Math.round(o*128)+128,0,255)):t==="signed"?this.writeOutputValue=(s,a,o)=>{s.setInt8(a,le(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(s,a,o)=>{const c=le(Math.round(o*32768),-32768,32767);s.setUint8(a,Sh(c))}:t==="alaw"?this.writeOutputValue=(s,a,o)=>{const c=le(Math.round(o*32768),-32768,32767);s.setUint8(a,xh(c))}:p(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint16(a,le(Math.round(o*32768)+32768,0,65535),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt16(a,le(Math.round(o*32768),-32768,32767),n):p(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(s,a,o)=>bn(s,a,le(Math.round(o*8388608)+8388608,0,16777215),n):t==="signed"?this.writeOutputValue=(s,a,o)=>Ru(s,a,le(Math.round(o*8388608),-8388608,8388607),n):p(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(s,a,o)=>s.setUint32(a,le(Math.round(o*2147483648)+2147483648,0,4294967295),n):t==="signed"?this.writeOutputValue=(s,a,o)=>s.setInt32(a,le(Math.round(o*2147483648),-2147483648,2147483647),n):t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat32(a,o,n):p(!1);break;case 8:t==="float"?this.writeOutputValue=(s,a,o)=>s.setFloat64(a,o,n):p(!1);break;default:Ae(i),p(!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 Bp extends Di{constructor(e){Aa(e),super(e.codec),this._encoder=new Ma(this,e)}add(e){if(!(e instanceof be))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class yg extends Di{constructor(e,t={}){if(Aa(e),typeof t!="object"||!t)throw new TypeError("options must be an object.");if(t.startTimestamp!==void 0&&!Number.isFinite(t.startTimestamp))throw new TypeError("options.startTimestamp, when provided, must be a finite number.");super(e.codec),this._encoder=new Ma(this,e),this._accumulatedTime=t.startTimestamp??0}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=be._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 bg extends Di{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(Aa(t),typeof i!="object"||!i)throw new TypeError("options must be an object.");if(i.timestampBase!==void 0&&i.timestampBase!=="synced-zero"&&i.timestampBase!=="zero"&&i.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=ne(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=i,this._encoder=new Ma(this,t),this._track=e}async _start(){this._errorPromiseAccessed||O._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,i=null,n=0;const s=a=>
10{if(t){a.close();return}const o=a.timestamp;if(this._paused){if(e!==null){if(i!==null&&this._options.timestampBase!=="unix"){const l=o-i;n-=l}i=o}a.close();return}if(e===null){e=a.timestamp;let c;const l=this._options.timestampBase??"synced-zero";if(l==="unix")c=Date.now()/1e3;else if(l==="zero")c=0;else{const u=this._connectedTrack.output;u._firstMediaStreamTimestamp===null?(u._firstMediaStreamTimestamp=performance.now()/1e3,c=0):c=performance.now()/1e3-u._firstMediaStreamTimestamp}n=c-e}if(i=o,this._encoder.getQueueSize()>=8){a.close();return}a.setTimestamp(o+n),this._encoder.add(a,!0).catch(c=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(c),this._audioContext?.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){const a=new MediaStreamTrackProcessor({track:this._track}),o=new WritableStream({write:c=>s(new be(c))});a.readable.pipeTo(o,{signal:this._abortController.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||this._promiseWithResolvers.reject(c)})}else{const a=window.AudioContext||window.webkitAudioContext;this._audioContext=new a({sampleRate:this._track.getSettings().sampleRate});const o=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),o.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let c=0;this._scriptProcessorNode.onaudioprocess=l=>{const u=be._fromAudioBuffer(l.inputBuffer,c);c+=l.inputBuffer.duration;for(const d of u)s(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){try{this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(p(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend())}finally{await this._encoder.flushAndClose(e)}}}const Fp=()=>{const r=(i,n)=>{n?self.postMessage(i,{transfer:n}):self.postMessage(i)};r({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",i=>{const n=i.data;switch(n.type){case"videoTrack":{t.set(n.trackId,n.track);const s=new MediaStreamTrackProcessor({track:n.track}),a=new WritableStream({write:c=>{if(!t.has(n.trackId)){c.close();return}r({type:"videoFrame",trackId:n.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(n.trackId,o),s.readable.pipeTo(a,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||r({type:"error",trackId:n.trackId,error:c})})}break;case"stopTrack":{const s=e.get(n.trackId);s&&(s.abort(),e.delete(n.trackId)),t.get(n.trackId)?.stop(),t.delete(n.trackId),r({type:"trackStopped",trackId:n.trackId})}break;default:Ae(n)}})};let Rp=0,et=null;const Mp=()=>{const r=new Blob([`(${Fp.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(r);et=new Worker(e)};let ls=null;const Dp=async()=>ls!==null?ls:(et||Mp(),new Promise(r=>{p(et);const e=t=>{const i=t.data;i.type==="support"&&(ls=i.supported,et.removeEventListener("message",e),r(i.supported))};et.addEventListener("message",e)})),us=(r,e)=>{p(et),et.postMessage(r)};class ku extends Fa{constructor(e){if(super(),!mt.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${mt.join(", ")}.`);this._codec=e}}class kg extends ku{constructor(e){super(e),this._error=null,this._errorSet=!1,this._lastMuxerPromise=Promise.resolve(),this._parser=new Kh({codec:e,output:(t,i)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,t,i).catch(n=>{this._setError(n)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}}class zp extends Mt{constructor(e,t){if(!(e._target instanceof Vt))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=t._options.getPlaylistPath??(({n:i})=>`playlist-${i}
10.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(i=>i.isSingleFile?`segments-${i.playlist.n}${i.format.fileExtension}`:`segment-${i.playlist.n}-${i.n}${i.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(i=>`init-${i.n}${i.segmentFormat.fileExtension}`)}async start(){const e=await this.mutex.acquire(),t=this.output.tracks.some(w=>w.metadata.isRelativeToUnixEpoch),i=this.output.tracks.some(w=>!w.metadata.isRelativeToUnixEpoch);if(t&&i)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;const n=new Map,s=[];let a=!1,o=!1,c=!1;for(const w of this.output.tracks){w.type==="video"&&(a=!0);const y=new Map;for(const b of this.output.tracks){if(w===b||!w.canBePairedWith(b))continue;if(w.type===b.type){o||(O._warn(`Illegal pairing of two ${w.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),o=!0);continue}if(w.isVideoTrack()&&w.metadata.hasOnlyKeyPackets||b.isVideoTrack()&&b.metadata.hasOnlyKeyPackets){c||(O._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),c=!0);continue}let k=y.get(b.source._codec);k||y.set(b.source._codec,k=[]),k.push(b)}for(const[,b]of y){const k=b.map(A=>A.id).join("-");s.find(A=>A.key===k)||s.push({name:b[0].type+"-"+(s.length+1),key:k,tracks:b,needsEmit:!1,firstNoUri:!1});let T=n.get(w);T||n.set(w,T=[]),T.push(k)}}const l=a?"video":"audio",u=[],d=[],f=[];for(const w of this.output.tracks){const y=n.get(w);if(y){if(p(y.length>0),w.type!==l)continue;for(const b of y){const k=s.find(S=>S.key===b);if(p(k),y.length===1&&k.tracks.length===1){const S=n.get(k.tracks[0]);if(p(S!==void 0),S.length===1){const T=s.find(A=>A.key===S[0]);if(T.tracks.length===1){p(T.tracks[0]===w),u.push({tracks:[w,k.tracks[0]],linkedGroup:null});continue}}}u.push({tracks:[w],linkedGroup:k}),k.needsEmit=!0}}else w.type==="video"?d.push(w):w.type==="audio"&&f.push(w)}const h=({metadata:w})=>{let y="";return y+=`${w.languageCode??Ie}-`,y+=`${w.name??""}-`,y+=`${w.disposition?.default??!0}-`,y+=`${w.disposition?.primary??!1}-`,y+=`${w.disposition?.forced??!1}-`,y};if(d.length>0)if(new Set(d.map(h)).size>1){const y={key:d.map(b=>b.id).join("-"),name:"video-"+(s.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};s.push(y),u.push({tracks:[d[0]],linkedGroup:y})}else for(const y of d)u.push({tracks:[y],linkedGroup:null});if(f.length>0)if(new Set(f.map(h)).size>1){const y={key:f.map(b=>b.id).join("-"),name:"audio-"+(s.length+1),tracks:f,needsEmit:!0,firstNoUri:!0};s.push(y),u.push({tracks:[f[0]],linkedGroup:y})}else for(const y of f)u.push({tracks:[y],linkedGroup:null});const g=w=>{const y=[];let b=0,k=0,S=!1,T=null,A=-1/0;for(const P of w)P.isVideoTrack()?(b++,S||=(P.metadata.rotation??0)!==0||!!P.metadata.flip||!!P.metadata.transformationMatrix):P.isAudioTrack()&&k++,y.push(P.source._codec);for(const P of rr(this.format._options.segmentFormat)){const C=P.getSupportedCodecs(),x=P.getSupportedTrackCounts();if(y.some(E=>!C.includes(E))||b<x.video.min||b>x.video.max||k<x.audio.min||k>x.audio.max)continue;let I=0;S&&P.supportsVideoTransformationMetadata&&I++,I>A&&(T=P,A=I)}return p(T),T},m=async w=>{if(w.some(T=>this.playlists.some(A=>A.tracks.includes(T))))throw new Error("Internal error: track is already registered in a playlist.");const y=g(w),b=this.playlists.length+1,k=await this.getPlaylistPath({n:b,tracks:w,segmentFormat:y});Op(k);const S={id:this.playlists.length+1,path:k,tracks:w,segmentFormat:y,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new pr};return this.playlists.push(S),S};for(const w of s)if(w.needsEmit)for(let y=0;y<w.tracks.length;y++){const b=w.tracks[y];let k=this.playlists.find(S=>S.tracks[0].id===b.id);k??=await m([b]),this.playlistDeclarations.push({playlist:k,groupId:w.name,noUri:w.firstNoUri&&y===0,references:[]})}for(const w of u){let y=this.playlists.find(b=>b.tracks[0].id===w.tracks[0].id);y??=await m(w.tracks),this.playlistDeclarations.push({playlist:y,groupId:null,noUri:!1,references:w.linkedGroup?this.playlistDeclarations.filter(b=>b.groupId===w.linkedGroup.name):[]})}for(const w of this.output.tracks)w.isVideoTrack()&&w.metadata.decoderConfig?this.getVideoTrackData(w,w.metadata.primingPacket??null,{decoderConfig:w.metadata.decoderConfig}):w.isAudioTrack()&&w.metadata.decoderConfig&&this.getAudioTrackData(w,w.metadata.primingPacket??null,{decoderConfig:w.metadata.decoderConfig});e()}async getMimeType(){return Rr}allTracksAreKnown(e){for(const t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(i=>i.track===t))return!1;return!0}async onTrackClose(e){const t=this.trackDatas.find(s=>s.track===e);t&&(t.closed=!0);const i=this.playlists.find(s=>s.tracks.includes(e));p(i);const n=await i.mutex.acquire();try{await this.advancePlaylist(i)}finally{n()}}getVideoTrackData(e,t,i){let n=this.trackDatas.find(a=>a.track===e);if(n)return n;Fi(i,e.source._codec),p(i),p(i?.decoderConfig);const s=this.playlists.filter(a=>a.tracks.includes(e));return p(s.length===1),n={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:i.decoderConfig,primingPacket:t}},this.trackDatas.push(n),n}getAudioTrackData(e,t,i){let n=this.trackDatas.find(a=>a.track===e);if(n)return n;it(i,e.source._codec),p(i),p(i?.decoderConfig);const s=this.playlists.filter(a=>a.tracks.includes(e));return p(s.length===1),n={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:i.decoderConfig,primingPacket:t}},this.trackDatas.push(n),n}async addEncodedVideoPacket(e,t,i){const n=this.getVideoTrackData(e,t,i),s=n.playlist,a=await s.mutex.acquire();
10try{this.validateTimestamp(e,t.timestamp,t.type==="key"),n.packets.push(t),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=t.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(s)}finally{a()}}async addEncodedAudioPacket(e,t,i){const n=this.getAudioTrackData(e,t,i),s=n.playlist,a=await s.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),n.packets.push(t),s.currentSegmentStartTimestamp===null?s.currentSegmentStartTimestamp=t.timestamp:s.currentSegmentStartTimestampIsFixed||(s.currentSegmentStartTimestamp=Math.min(s.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(s)}finally{a()}}async addSubtitleCue(e,t,i){throw new Error("Unreachable.")}async advancePlaylist(e){if(p(!e.done),!this.allTracksAreKnown(e))return;const t=this.trackDatas.filter(s=>e.tracks.includes(s.track));if(e.currentSegmentStartTimestamp===null){t.every(s=>s.closed)&&await this.onPlaylistDone(e);return}const i=t.find(s=>s.info.type==="video"),n=t.find(s=>s.info.type==="audio");for(;;){const s=e.currentSegmentStartTimestamp+this.targetSegmentDuration;let a=0,o=0;if(i&&(!i.closed||i.packets.length>0)){const T=i.packets.every(C=>C.timestamp<s);let A=null,P=null;if(T){if(!i.closed)return}else for(let C=0;C<i.packets.length;C++){const x=i.packets[C];if(A!==null&&x.timestamp>s)break;C>0&&x.type==="key"&&(A=x,P=C)}if(P!==null){if(a=P,n){const C=n.packets.findIndex(x=>x.timestamp>=A.timestamp);if(C!==-1)o=C;else if(n.closed)o=n.packets.length;else return}}else{if(!i.closed)return;a=i.packets.length;const C=Lu(i.packets,I=>I.timestamp),x=i.packets[C];if(p(x),n)if(x.timestamp<s){const I=n.packets.findIndex(E=>E.timestamp>=s);if(I!==-1)o=I;else if(n.closed)o=n.packets.length;else return}else{const I=n.packets.findIndex(E=>E.timestamp>x.timestamp);if(I!==-1)o=I;else if(n.closed)o=n.packets.length;else return}}}else if(n&&(!n.closed||n.packets.length>0))if(n.packets.every(A=>A.timestamp<s))if(n.closed)o=n.packets.length;else return;else{const A=wn(n.packets,P=>P.timestamp<=s);o=Math.max(A,1)}if(a===0&&o===0){t.every(A=>A.closed)&&await this.onPlaylistDone(e);return}let c=null,l,u;p(this.output._target instanceof Vt);const d=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){const T={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Hi(e)};
10l=await this.getSegmentPath(T),fc(l),u=Be(Be(d.rootPath,e.path),l);const A=await this.output._getTarget({path:u,isRoot:!1,mimeType:e.segmentFormat.mimeType});let P=null;if(e.segmentFormat._isFragmentedIsobmff()){P={output:new gn({format:e.segmentFormat,target:A}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},A.on("write",({end:I})=>{P.currentFileSize=Math.max(P.currentFileSize,I)});const C=P.output._muxer;C.minimumFragmentDuration=1/0;const x=C.formatOptions.onMoof;C.formatOptions.onMoof=(I,E,F)=>{P.firstMoofPosition=E,x?.(I,E,F),C.formatOptions.onMoof=x},i&&(P.videoSource=new $s(i.track.source._codec),P.output.addVideoTrack(P.videoSource,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),n&&(P.audioSource=new Xs(n.track.source._codec),P.output.addAudioTrack(P.audioSource,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),await P.output.start()}else A._start();e.singleFile={target:A,path:l,nextOffset:0,info:T,fragmentedIsobmffOutput:P}}else l=e.singleFile.path,u=Be(Be(d.rootPath,e.path),l);else c={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Hi(e)}
10,l=await this.getSegmentPath(c),fc(l),u=Be(Be(d.rootPath,e.path),l),e.nextSegmentId++;let f=0,h=null,g=-1/0,m=null,w=null,y=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(m=e.singleFile.fragmentedIsobmffOutput.output,w=e.singleFile.fragmentedIsobmffOutput.videoSource,y=e.singleFile.fragmentedIsobmffOutput.audioSource):(m=new gn({format:e.segmentFormat,target:new Vt(u,async T=>{const A={...T,isRoot:!1};if(T.isRoot)if(e.singleFile){const P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:C})=>f=Math.max(f,C)),P}else{const P=await this.output._getTarget(A);return h=P,P.on("write",({end:C})=>f=Math.max(f,C)),P}return this.output._getTarget(A)}),initTarget:async()=>{if(e.initSegment)return new gu;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};const T=e.singleFile.target.slice(e.singleFile.nextOffset);return T.on("write",({end:A})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,A)}),T.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),T}else{const T=Hi(e),A=await this.getInitPath(T);Up(A),e.initSegment={path:A,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};const P=Be(Be(d.rootPath,e.path),A),C=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return C.on("write",({end:x})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,x)}),C.on("finalized",()=>{this.format._options.onInit?.(C,T)}),C}}}),i&&(w=new $s(i.track.source._codec),m.addVideoTrack(w,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),n&&(y=new Xs(n.track.source._codec),m.addAudioTrack(y,{...n.track.metadata,decoderConfig:n.info.decoderConfig,primingPacket:n.info.primingPacket??void 0})),await m.start()),i){p(w);const T={decoderConfig:i.info.decoderConfig};for(let A=0;A<a;A++){const P=i.packets[A];await w.add(P,T),g=Math.max(g,P.timestamp+P.duration)}}if(n){p(y);const T={decoderConfig:n.info.decoderConfig};for(let A=0;A<o;A++){const P=n.packets[A];await y.add(P,T),g=Math.max(g,P.timestamp+P.duration)}}e.singleFile?.fragmentedIsobmffOutput?(await e.singleFile.fragmentedIsobmffOutput.output._muxer.forceFragmentFinalization(),e.singleFile.fragmentedIsobmffOutput.firstMoofPosition!==null&&!e.initSegment&&(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),f=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset):await m.finalize()}catch(T){throw await m?.cancel(),T}c&&(p(h),this.format._options.onSegment?.(h,c)),a>0&&(p(i),i.packets.splice(0,a)),o>0&&(p(n),n.packets.splice(0,o));let b=1/0;i&&i.packets.length>0&&(b=i.packets[0].timestamp),n&&n.packets.length>0&&(b=Math.min(b,n.packets[0].timestamp));const k=b<1/0?b:g;p(Number.isFinite(k));const S=k-e.currentSegmentStartTimestamp;if(p(S>=0),e.writtenSegments.push({path:l,duration:S,timestamp:e.currentSegmentStartTimestamp,byteSize:f,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:c??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,S),e.currentSegmentStartTimestamp=k,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=f),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){const T=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(p(T.info),this.format._options.onSegmentPopped?.(T.path,T.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){p(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){const t=e.writtenSegments;let i=0,n=0,s=0;for(let a=0;a<t.length;
10a++){s+=t[a].duration;let o=0,c=0;for(let l=a;l<t.length&&(o+=t[l].byteSize,c+=t[l].duration,c>=.5*this.globalTargetDuration&&c<=1.5*this.globalTargetDuration&&(i=Math.max(i,8*o/c)),!(c>1.5*this.globalTargetDuration));l++);}if(i===0)for(const a of t){const o=a.duration||1;i=Math.max(i,8*a.byteSize/o)}for(const a of t)n+=8*a.byteSize;e.peakBitrate=i,e.averageBitrate=n/(s||1)}async writePlaylist(e){p(this.output._target instanceof Vt);const t=this.output._target;this.updatePlaylistBitrates(e);let i=!1;for(const d of e.writtenSegments)i||=d.byteOffset!==null;const n=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;let s=3;(n||i)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!n&&(s=6);const a=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,o=Be(t.rootPath,e.path),c=`#EXTM3U
11#EXT-X-VERSION:${s}
12`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
13`)+`#EXT-X-TARGETDURATION:${Math.ceil(a)}
14`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}
15`:"")+`#EXT-X-INDEPENDENT-SEGMENTS
16`+(n?`#EXT-X-I-FRAMES-ONLY
17`:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+`
18`:"")+`
19`+e.writtenSegments.map(d=>`#EXTINF:${+d.duration.toFixed(12)},
20`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*d.timestamp).toISOString()}
21`:"")+(d.byteOffset!==null?`#EXT-X-BYTERANGE:${d.byteSize}@${d.byteOffset}
22`:"")+`${d.path}
23`).join("")+(e.done?(e.writtenSegments.length>0?`
24`:"")+`#EXT-X-ENDLIST
25`:"");this.format._options.onPlaylist?.(c,Hi(e));const l=await this.output._getTarget({path:o,isRoot:!1,mimeType:Rr}),u=new Ii(l,!0);u.start(),u.write(Z.encode(c)),await u.flush(),await u.finalize()}async writeMasterPlaylist(){p(this.output._target instanceof Vt);const e=this.output._target;let t=`#EXTM3U
26`,i=!1,n=null,s=0,a=!1;for(const c of this.playlistDeclarations)if(c.groupId===null){const l=c.playlist.tracks[0].isVideoTrack()&&c.playlist.tracks[0].metadata.hasOnlyKeyPackets,u=[];for(const w of c.playlist.tracks){const b=this.trackDatas.find(k=>k.track===w)?.info.decoderConfig.codec??w.source._codec;u.push(b)}let d=0,f=0;if(c.references.length>0){const y=c.references[0].playlist.tracks[0],k=this.trackDatas.find(S=>S.track===y)?.info.decoderConfig.codec??y.source._codec;u.push(k);for(const S of c.references)p(S.playlist.peakBitrate!==null),d=Math.max(d,S.playlist.peakBitrate),f=Math.max(f,S.playlist.averageBitrate??0)}p(c.playlist.peakBitrate!==null);const h=c.playlist.peakBitrate+d,g=(c.playlist.averageBitrate??0)+f;i||(t+=`
27`,i=!0),l?t+="#EXT-X-I-FRAME-STREAM-INF:":t+="#EXT-X-STREAM-INF:",t+=`BANDWIDTH=${Math.ceil(h)}`,g>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(g)}`),t+=`,CODECS="${u.join(",")}"`;const m=c.playlist.tracks.find(w=>w.isVideoTrack());if(m?.isVideoTrack()){const y=this.trackDatas.find(b=>b.track===m)?.info.decoderConfig;if(y){let b=y.displayAspectWidth??y.codedWidth,k=y.displayAspectHeight??y.codedHeight;b!==void 0&&k!==void 0&&(m.metadata.rotation!==void 0&&m.metadata.rotation%180===90&&([b,k]=[k,b]),t+=`,RESOLUTION=${b}x${k}`)}!l&&m.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+m.metadata.frameRate.toFixed(3)}`)}if(!l){const w=new Map;for(const y of c.references){p(y.groupId!==null);const b=y.playlist.tracks[0].type;w.set(b,y.groupId)}for(const[y,b]of w)t+=`,${y.toUpperCase()}="${b}"`}l?(t+=`,URI="${c.playlist.path}"`,t+=`
28`):(t+=`
29`,t+=`${c.playlist.path}
30`)}else{p(c.playlist.tracks.length===1);const l=c.playlist.tracks[0],u=l.type;let d=l.metadata.name??null;const f=l.metadata.languageCode,h=l.metadata.disposition;(n===null||c.groupId!==n)&&(s=0,t+=`
31`,a=!1),n=c.groupId,s++,t+=`#EXT-X-MEDIA:TYPE=${u.toUpperCase()},GROUP-ID="${c.groupId}"`,d!==null&&/[\n\r"]/.test(d)&&(O._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),d=null),d??=`${f??c.groupId}-${s}`,t+=`,NAME="${d}"`,f!==void 0&&(t+=`,LANGUAGE="${f}"`);const g=h?.primary??!1,m=h?.default??!0,w=h?.forced??!1;if(g&&!a&&(t+=",DEFAULT=YES",a=!0),(g||m)&&(t+=",AUTOSELECT=YES"),w&&(t+=",FORCED=YES"),u==="audio"){const b=this.trackDatas.find(k=>k.track===l)?.info.decoderConfig;b&&(t+=`,CHANNELS="${b.numberOfChannels}"`)}c.noUri||(t+=`,URI="${c.playlist.path}"`),t+=`
32`}this.format._options.onMaster?.(t);const o=await this.mutex.acquire();try{let c;if(this.numWrittenMasterPlaylists===0)c=await this.output._getRootWriter(!0);else{const l=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:Rr});c=new Ii(l,!0),c.start()}c.write(Z.encode(t)),await c.flush(),await c.finalize(),this.numWrittenMasterPlaylists++}finally{o()}}async tryWriteMasterPlaylist(){p(this.isLive);for(const e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(t=>
32t.mutex.acquire()))).forEach(t=>t());for(const t of this.trackDatas)t.closed=!0;await Promise.all(this.playlists.map(t=>t.done?Promise.resolve():this.advancePlaylist(t))),this.isLive||await this.writeMasterPlaylist()}}const Op=r=>{if(typeof r!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},fc=r=>{if(typeof r!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},Up=r=>{if(typeof r!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(r))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},Hi=r=>({n:r.id,tracks:r.tracks,segmentFormat:r.segmentFormat});class Xe{get supportsVideoRotationMetadata(){return this.supportsVideoTransformationMetadata}getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>we.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>xe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>mt.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class Da extends Xe{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&&(!Ke(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:0,max:4294967295}}}get supportsVideoTransformationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"full"}_createMuxer(e){return new up(e,this)}_isFragmentedIsobmff(){return this._options.fastStart==="fragmented"}}class Tu extends Da{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...we,...Lt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...mt]}_codecUnsupportedHint(e){return new Su().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class hc extends Da{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...we,...Lt,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...mt]}}class Su extends Da{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...we,...xe]}_codecUnsupportedHint(e){return new Tu().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class mc extends Xe{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&&(!Ke(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.");
vendor: 7,542 bytes, line 32
32if(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 mp(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[...we,...Lt,...ke.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...mt]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class ds extends mc{constructor(e){super(e)}getSupportedCodecs(){return[...we.filter(e=>["vp8","vp9","av1"].includes(e)),...xe.filter(e=>["opus","vorbis"].includes(e)),...mt]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new mc().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class Tg extends Xe{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new gp(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Sg extends Xe{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Pp(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...ke.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Ag extends Xe{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!Ke(e.maximumPageDuration)||e.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new yp(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:0,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...xe.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class xg extends Xe{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Wh(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Pg extends Xe{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=e}_createMuxer(e){return new Hh(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}get negativeTimestampSupport(){return null}}class Cg extends Xe{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onPacket!==void 0&&typeof e.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Tp(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...we.filter(e=>["avc","hevc"].includes(e)),...xe.filter(e=>["aac","mp3","ac3","eac3","dts"].includes(e))]}get supportsVideoTransformationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){return"prefer-non-negative"}}class _g extends Xe{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof Xe)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof Xe)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(e.targetDuration!==void 0&&(typeof e.targetDuration!="number"||e.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(e.live!==void 0&&typeof e.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!="number"||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");
32if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(e.getInitPath!==void 0&&typeof e.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(e.onMaster!==void 0&&typeof e.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(e.onPlaylist!==void 0&&typeof e.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(e.onSegment!==void 0&&typeof e.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(e.onInit!==void 0&&typeof e.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new zp(e,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return Rr}getSupportedCodecs(){return[...new Set(rr(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,i=!1;for(const n of rr(this._options.segmentFormat)){const s=n.getSupportedTrackCounts();e||=s.video.max>0,t||=s.audio.max>0,i||=s.subtitle.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoTransformationMetadata(){return rr(this._options.segmentFormat).some(e=>e.supportsVideoTransformationMetadata)}get supportsTimestampedMediaData(){return!0}get negativeTimestampSupport(){const e=rr(this._options.segmentFormat);return e.some(t=>t.negativeTimestampSupport==="none")?"none":e.some(t=>t.negativeTimestampSupport==="prefer-non-negative")?"prefer-non-negative":e.some(t=>t.negativeTimestampSupport==="full")?"full":null}_codecUnsupportedHint(e){return" Using different segment formats may grant support for this codec."}}const pc=["video","audio","subtitle"];class zi{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 zi))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=rr(this.metadata.group),i=rr(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 Np extends zi{constructor(e,t,i,n){super(e,t,"video",i,n)}}class Vp extends zi{constructor(e,t,i,n){super(e,t,"audio",i,n)}}class Wp extends zi{constructor(e,t,i,n){super(e,t,"subtitle",i,n)}}class st{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof st))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const fs=r=>{if(!r||typeof r!="object")throw new TypeError("metadata must be an object.");if(r.languageCode!==void 0&&!gi(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&&Qu(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.bitrate!==void 0&&(!Number.isFinite(r.bitrate)||r.bitrate<0))throw new TypeError("metadata.bitrate, when provided, must be a non-negative number.");if(r.averageBitrate!==void 0&&(!Number.isFinite(r.averageBitrate)||r.averageBitrate<0))throw new TypeError("metadata.averageBitrate, when provided, must be a non-negative number.");if(r.group!==void 0&&!(r.group instanceof st)&&(!Array.isArray(r.group)||r.group.some(e=>!(e instanceof st))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class gn extends vi{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(v(t))throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new st,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new pr,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 Xe))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof qe||e.target instanceof Vt))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof qe&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof qe)&&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 qe&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){p(this._target instanceof Vt);const t=this._target.getTarget(e),i=n=>{if(!(n instanceof qe))throw new TypeError("getTarget must return a Target.");return n};return v(t)?t.then(i):i(t)}async _getTarget(e){p(this._target instanceof Vt);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})}
vendor: 4,290 bytes, line 32
32async _getInitTarget(){if(p(this._initTarget!==null),this._initTarget instanceof qe)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 qe)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 v(t)?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const t=await this._getRootTarget(),i=new Ii(t,typeof e=="boolean"?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof Mi))throw new TypeError("source must be a VideoSource.");if(fs(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(t.flip!==void 0&&typeof t.flip!="boolean")throw new TypeError("metadata.flip, when provided, must be a boolean.");if(t.transformationMatrix!==void 0&&(!Array.isArray(t.transformationMatrix)||t.transformationMatrix.length!==9||!t.transformationMatrix.every(n=>Number.isFinite(n))))throw new TypeError("metadata.transformationMatrix, when provided, must be an array of 9 finite numbers.");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&&Fi({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof te))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 Np(this.tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof Di))throw new TypeError("source must be an AudioSource.");if(fs(t),t.decoderConfig!==void 0&&it({decoderConfig:t.decoderConfig},e._codec),t.primingPacket!==void 0){if(!(t.primingPacket instanceof te))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 Vp(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof ku))throw new TypeError("source must be a SubtitleSource.");fs(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Wp(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(Ss(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const t=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),n=t[e.type].max;if(i===n)throw new Error(n===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${n} ${e.type} track${n===1?"":"s"}.`);const s=t.total.max;if(this.tracks.length===s)throw new Error(`${this.format._name} does not support more than ${s} tracks${s===1?"":"s"} in total.`);if(e.isVideoTrack()){const a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}
32else 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 pc){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 pc){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?(O._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.state==="canceled")return this._cancelPromise??void 0;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&O._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?(O._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"}catch(t){throw this.state="canceled",t}finally{await Promise.all([...this._unfinalizedTargets].map(t=>t._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}var ri=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},ji=(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)}
32if(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 Ki=r=>{if(!r||typeof r!="object")throw new TypeError("options.video, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!we.includes(r.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${we.join(", ")}.`);const e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof he))throw new TypeError("options.video.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof he)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(r?.width!==void 0&&(!Number.isInteger(r.width)||r.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(r?.height!==void 0&&(!Number.isInteger(r.height)||r.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(r?.fit!==void 0&&!["fill","contain","cover"].includes(r.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");
32if(r?.width!==void 0&&r.height!==void 0&&r.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(r?.rotate!==void 0&&![0,90,180,270].includes(r.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(r?.flip!==void 0&&typeof r.flip!="boolean")throw new TypeError("options.video.flip, when provided, must be a boolean.");if(r?.allowTransformationMetadata!==void 0&&typeof r.allowTransformationMetadata!="boolean")throw new TypeError("options.video.allowTransformationMetadata, when provided, must be a boolean.");if(r?.allowRotationMetadata!==void 0&&typeof r.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(r?.crop!==void 0&&Pi(r.crop,"options.video."),r?.frameRate!==void 0&&(!Number.isFinite(r.frameRate)||r.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(r?.alpha!==void 0&&!["discard","keep"].includes(r.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(r?.keyFrameInterval!==void 0&&(!Number.isFinite(r.keyFrameInterval)||r.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if(r?.processedWidth!==void 0&&(!Number.isInteger(r.processedWidth)||r.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(r?.processedHeight!==void 0&&(!Number.isInteger(r.processedHeight)||r.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(r?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(r.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(r?.group!==void 0&&!(r.group instanceof st||Array.isArray(r.group)&&r.group.every(t=>t instanceof st)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},Qi=r=>{if(!r||typeof r!="object")throw new TypeError("options.audio, when provided, must be an object.");if(r?.discard!==void 0&&typeof r.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(r?.forceTranscode!==void 0&&typeof r.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(r?.codec!==void 0&&!xe.includes(r.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${xe.join(", ")}.`);const e=r?.bitrate;if(r?.quality!==void 0&&!(r.quality instanceof he))throw new TypeError("options.audio.quality, when provided, must be a Quality.");if(r?.quality!==void 0&&e!==void 0)throw new TypeError("options.audio.quality and options.audio.bitrate cannot both be provided.");if(e!==void 0&&!(e instanceof he)&&(!Number.isInteger(e)||e<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(r?.numberOfChannels!==void 0&&(!Number.isInteger(r.numberOfChannels)||r.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(r?.sampleRate!==void 0&&(!Number.isInteger(r.sampleRate)||r.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(r?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(r.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(r?.process!==void 0&&typeof r.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if(r?.processedNumberOfChannels!==void 0&&(!Number.isInteger(r.processedNumberOfChannels)||r.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(r?.processedSampleRate!==void 0&&(!Number.isInteger(r.processedSampleRate)||r.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(r?.group!==void 0&&!(r.group instanceof st||Array.isArray(r.group)&&r.group.every(t=>t instanceof st)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},hs=2,ms=48e3;class Au{get state(){return this._state}static async init(e){const t=new Au(e);return await t._init(),t}constructor(e){if(this._state="idle",this._timestampOffset=0,this._timestampOffsetAdjusted=!1,this._copyTimestampPossible=new Map,this._copyStartPackets=new Map,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new Lp(this),this._totalDuration=null,this._maxTimestamps=new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof Mn))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof gn))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.composable!==void 0&&typeof e.composable!="boolean")throw new TypeError("options.composable, when provided, must be a boolean.");if(e.copy!==void 0&&e.copy!==!1){if(!e.copy||typeof e.copy!="object")throw new TypeError("options.copy, when provided, must be an object or false.");if(e.copy.mode!==void 0&&!["forced","preferred"].includes(e.copy.mode))throw new TypeError("options.copy.mode, when provided, must be 'forced' or 'preferred'.");if(e.copy.shiftTolerance!==void 0&&(!Ke(e.copy.shiftTolerance)||e.copy.shiftTolerance<0))throw new TypeError("options.copy.shiftTolerance, when provided, must be a non-negative number.");if(e.copy.boundaryPolicy!==void 0&&!["expand","shrink"].includes(e.copy.boundaryPolicy))throw new TypeError("options.copy.boundaryPolicy, when provided, must be 'expand' or 'shrink'.");if(e.copy.boundaryTolerance!==void 0&&(!Ke(e.copy.boundaryTolerance)||e.copy.boundaryTolerance<0))throw new TypeError("options.copy.boundaryTolerance, when provided, must be a non-negative number.")}const t=e.composable??!1;if(t){if(e.tags!==void 0)throw new TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if(e.output.state!=="pending")throw new TypeError("options.output must not have been started yet.")}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");
32if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const i of e.video)Ki(i);else Ki(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const i of e.audio)Qi(i);else Qi(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Ke(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a number.");if(e.trim?.start!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&Ss(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this._copyMode=e.copy===!1?!1:e.copy?.mode??"preferred",this._copyTimestampShiftTolerance=e.copy===!1?0:e.copy?.shiftTolerance??0,this._copyBoundaryPolicy=e.copy===!1?"expand":e.copy?.boundaryPolicy??"expand",this._copyBoundaryTolerance=e.copy===!1?1/0:e.copy?.boundaryTolerance??1/0,this._composable=t,this.input=e.input,this.output=e.output}async _init(){const e=await this.input.getFormat();let t,i=this._options.tracks;if(i===void 0&&(i=e.name.includes("(HLS)")?"primary":"all"),i==="all")t=await this.input.getTracks();else if(i==="primary"){const l=await this.input.getPrimaryVideoTrack(),u=await this.input.getPrimaryAudioTrack();t=[l,u].filter(d=>d!==null)}else Ae(i),p(!1);const n=this.output.format.getSupportedTrackCounts();let s=1,a=1;const o=[],c=[];for(const l of t){let u;if(l.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const h=await this._options.video(l,s)??{};if(Array.isArray(h))for(const g of h)Ki(g);else Ki(h);u=Array.isArray(h)?h:[h],s++}else u=Array.isArray(this._options.video)?this._options.video:[this._options.video];else u=[{}];else if(l.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const h=await this._options.audio(l,a)??{};if(Array.isArray(h))for(const g of h)Qi(g);else Qi(h);u=Array.isArray(h)?h:[h],a++}else u=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else u=[{}];else p(!1);const d=u.filter(h=>h.discard);for(const h of d)this.discardedTracks.push({track:l,reason:"discarded_by_user",trackOptions:h});if(u.length===d.length){u.length===0&&this.discardedTracks.push({track:l,reason:"discarded_by_user",trackOptions:{}});continue}const f=u.filter(h=>!h.discard);o.push(l),c.push(f)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp),this._timestampOffset=-this._startTimestamp;for(let l=0;l<o.length;l++){const u=o[l],d=c[l];for(const f of d){if(this.output.tracks.length===n.total.max){this.discardedTracks.push({track:u,reason:"max_track_count_reached",trackOptions:f});continue}if(this.output.tracks.reduce((m,w)=>m+(w.type===u.type?1:0),0)===n[u.type].max){this.discardedTracks.push({track:u,reason:"max_track_count_of_type_reached",trackOptions:f});continue}const g=this._nextOutputTrackId++;u.isVideoTrack()?await this._processVideoTrack(u,f,g):u.isAudioTrack()?await this._processAudioTrack(u,f,g):p(!1)}}for(let l=0;l<this.utilizedTracks.length-1;l++)for(let u=l+1;u<this.utilizedTracks.length;u++){const d=this.utilizedTracks[l],f=this.utilizedTracks[u],h=this._outputOwnTrackGroups[l],g=this._outputOwnTrackGroups[u];p(h!==void 0),p(g!==void 0),h&&g&&d.canBePairedWith(f)&&h.pairWith(g)}if(!this._composable){const l=await this.input.getMetadataTags();let u;if(this._options.tags){const h=typeof this._options.tags=="function"?await this._options.tags(l):this._options.tags;Ss(h),u=h}else u=l;const d=e.mimeType===this.output.format.mimeType;l.raw===u.raw&&!d&&delete u.raw,this.output.setMetadataTags(u)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){const l=[],u=this.discardedTracks.filter(d=>d.reason!=="discarded_by_user");u.length>0&&l.push("Some tracks had to be discarded from the conversion:",u),this.isValid||(l.length>0&&l.push(`
33
34`),l.push(this._getInvalidityExplanation().join(""))),l.length>0&&O._warn(...l)}}_getInvalidityExplanation(){const e=[];
34if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(i=>i.reason==="discarded_by_user"||i.reason==="no_encodable_target_codec")&&this.discardedTracks.some(i=>i.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const i=this.discardedTracks.flatMap(s=>{if(s.reason==="discarded_by_user")return[];let a;return s.track.type==="video"?a=this.output.format.getSupportedVideoCodecs():s.track.type==="audio"?a=this.output.format.getSupportedAudioCodecs():a=this.output.format.getSupportedSubtitleCodecs(),a.filter(o=>!s.trackOptions.codec||o===s.trackOptions.codec)}),n=[...new Set(i)];n.length===1?e.push(`
35Tracks were discarded because your environment is not able to encode '${n[0]}' with the provided parameters.`):e.push(`
36Tracks were discarded because your environment is not able to encode any of the codecs ${n.map(s=>`'${s}'`).join(", ")} with the provided parameters.`),n.includes("mp3")&&e.push(`
37The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),n.includes("aac")&&e.push(`
38The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(n.includes("ac3")||n.includes("eac3"))&&e.push(`
39The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),n.includes("flac")&&e.push(`
40The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
41Check the discardedTracks field for more info.`)}return e}async execute(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.until!==void 0&&(typeof e.until!="number"||Number.isNaN(e.until)))throw new TypeError("options.until, when provided, must be a number.");if(e.pauseSignal!==void 0&&!(e.pauseSignal instanceof AbortSignal))throw new TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw new Error(`Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.
42`+this._getInvalidityExplanation().join(""));if(this._state==="executing")throw new Error("Cannot call execute() while a previous call to execute() is still running.");if(this._state==="canceled")throw new gc;if(this._state==="done")return;if(this._composable&&this.output.state==="pending")throw new Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this._state="executing",this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;const t=()=>{this._state==="executing"&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};e.pauseSignal?.addEventListener("abort",t);for(const n of this._trackPumps)n.done||(n.resolvers=ne());if(this._executed)for(const n of this._trackPumps)n.wake?.();else{this._executed=!0;for(const n of this._outputTrackIds)this._synchronizer.declareTrack(n);if(this.onProgress){const s=[...new Set(this.utilizedTracks)].map(async o=>await o.isLive()?1/0:await o.getDurationFromMetadata()??await o.computeDuration()),a=Math.max(0,...await Promise.all(s));this._computeProgress=!0,this._totalDuration=Math.min(a-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const o of this._outputTrackIds)this._maxTimestamps.set(o,0);this.onProgress?.(0,0)}this._composable||await this.output.start();for(const n of this._trackPumps)n.start()}try{await Promise.all(this._trackPumps.map(n=>n.resolvers.promise))}catch(n){throw this._state!=="canceled"&&this.cancel(),n}finally{e.pauseSignal?.removeEventListener("abort",t)}if(this._state==="canceled")throw new gc;const i=this._trackPumps.every(n=>n.done);if(this._state=i?"done":"idle",i&&(this._composable||await this.output.finalize(),this._computeProgress)){const n=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,n)}}async cancel(){if(this._state!=="done"){if(this._state==="canceled"){O._warn("Conversion already canceled.");return}this._state="canceled";for(const e of this._trackPumps)e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,i){const n=await e.getCodec();if(!n){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let s;const a=await e.getRotation(),o=await e.getFlip(),{rotation:c,flip:l}=Tc(a,o,t.rotate??0,t.flip??!1);let u=c,d=l,f=t.rotate||t.flip?null:await e.getTransformationMatrix();const h=this.output.format.supportsVideoTransformationMetadata&&(t.allowTransformationMetadata??t.allowRotationMetadata??
42!0),g=await e.getSquarePixelWidth(),m=await e.getSquarePixelHeight(),[w,y]=c%180===0?[g,m]:[m,g];let b=t.crop;b&&(b=fn(b,w,y));const[k,S]=b?[b.width,b.height]:[w,y];let T=k,A=S;const P=T/A;t.width!==void 0&&t.height===void 0?(T=yr(t.width),A=yr(Math.round(T/P))):t.width===void 0&&t.height!==void 0?(A=yr(t.height),T=yr(Math.round(A*P))):t.width!==void 0&&t.height!==void 0&&(T=yr(t.width),A=yr(t.height));let C=this.output.format.getSupportedVideoCodecs();const x=t.alpha??"discard";let I=!this._copyMode||!!t.forceTranscode||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.quality!==void 0||t.bitrate!==void 0||!C.includes(n)||t.codec&&t.codec!==n||T!==k||A!==S||c!==0&&!h||l&&!h||!!b,E=null;if(!I){const re=new Ht(e);let $=await re.getKeyPacket(this._startTimestamp,{verifyKeyPackets:!0})??await re.getFirstKeyPacket({verifyKeyPackets:!0});if($&&$.timestamp<this._startTimestamp&&$.timestamp+$.duration<=this._startTimestamp&&this._copyBoundaryPolicy==="shrink"&&($=await re.getNextKeyPacket($,{verifyKeyPackets:!0})),E=$,$){const G=this._copyBoundaryPolicy==="shrink"?Math.max($.timestamp,this._startTimestamp):$.timestamp;if((this._copyBoundaryPolicy==="shrink"?G-this._startTimestamp:Math.max(this._startTimestamp-G,0))>this._copyBoundaryTolerance)I=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&G<this._startTimestamp){const me=Math.min(this._startTimestamp-G,this._copyTimestampShiftTolerance);G+me>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+me):I=!0}}else if(this._timestampOffsetAdjusted)G+this._timestampOffset===0||(I=!0);else{const me=le(this._startTimestamp-G,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);G+me===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+me,this._timestampOffsetAdjusted=!0):I=!0}}}if(I&&this._copyMode==="forced"){this.discardedTracks.push({track:e,reason:"cannot_copy",trackOptions:t});return}if(I){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(C=C.filter(pe=>pe===t.codec));const $=Or(t.quality,t.bitrate)??new he("high"),G=await wh(C,{width:t.process&&t.processedWidth?t.processedWidth:T,height:t.process&&t.processedHeight?t.processedHeight:A,quality:$});if(!G){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const J={codec:G,quality:$,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:x,hardwareAcceleration:t.hardwareAcceleration,transform:{}};p(J.transform);let me=T!==k||A!==S||c!==0&&(!h||t.process!==void 0)||l&&(!h||t.process!==void 0)||!!b||g!==await e.getCodedWidth()||m!==await e.getCodedHeight();if(!me){const pe={stack:[],error:void 0,hasError:!1};try{const Fe=new gn({format:new Tu,target:new gu}),Dt=new dc(J);Fe.addVideoTrack(Dt),await Fe.start();const Ve=new js(e),Pe=ri(pe,await Ve.getSample(await e.getFirstTimestamp()),!1);if(Pe)try{await Dt.add(Pe),Pe.close(),await Fe.finalize()}catch(zt){O._warn("An error occurred when probing encoder support. Falling back to rerender path.",zt),Fe.cancel(),me=!0,J.transform.force=!0}else await Fe.cancel()}catch(Fe){pe.error=Fe,pe.hasError=!0}finally{ji(pe)}}t.frameRate&&(J.transform.frameRate=t.frameRate),t.process&&(J.transform.process=t.process),me&&(u=0,d=!1,f=null,J.transform.width=T,J.transform.height=A,J.transform.fit=t.fit??"fill",J.transform.rotate=t.rotate,J.transform.flip=t.flip,J.transform.crop=b,J.transform.alpha=x);let Te=null;J.onEncodedSample=pe=>{Te=pe.timestamp};const Ee=new dc(J);s=Ee,this._registerTrackPump(async pe=>{const Fe=new js(e);for await(const Dt of Fe.samples(this._startTimestamp,this._endTimestamp)){const Ve={stack:[],error:void 0,hasError:!1};try{const Pe=ri(Ve,Dt,!1);if(this._state==="canceled")break;
42const zt=Math.max(this._startTimestamp,Pe.timestamp),Oi=Math.min(this._endTimestamp,Pe.timestamp+Pe.duration);if(zt>=Oi)continue;Pe.setTimestamp(zt+this._timestampOffset),Pe.setDuration(Oi-zt),this._reportProgress(i,Pe.timestamp+Pe.duration),await Ee.add(Pe),Pe.close(),Te!==null&&(this._synchronizer.shouldWait(i,Te)&&await this._synchronizer.wait(Te),await this._checkpoint(pe,Te))}catch(Pe){Ve.error=Pe,Ve.hasError=!0}finally{ji(Ve)}}Ee.close(),this._synchronizer.closeTrack(i)})}else{const re=new $s(n);s=re,this._registerTrackPump(async $=>{const G=new Ht(e),me={decoderConfig:await e.getDecoderConfig()??void 0};let Te=null;if(E)for await(const Ee of G.packets(E,void 0,{verifyKeyPackets:!0})){if(this._state==="canceled")break;if(Ee.timestamp>=this._endTimestamp){if(this._copyBoundaryPolicy==="shrink")break;{let Pe=Ee,zt=!1;const Oi=6;for(let za=0;za<Oi;za++){const zn=await G.getNextPacket(Pe,{metadataOnly:!0});if(!zn)break;if(zn.timestamp<this._endTimestamp){zt=!0;break}Pe=zn}if(!zt)break}}let pe=Ee.timestamp,Fe=Ee.timestamp+Ee.duration;this._copyBoundaryPolicy==="shrink"&&(pe=Math.max(pe,this._startTimestamp),Fe=Math.min(Fe,this._endTimestamp),Fe=Math.max(Fe,pe)),pe+=this._timestampOffset,Fe+=this._timestampOffset;let Dt=Ee.type;Dt==="key"&&Te!==null&&pe<Te&&(Dt="delta"),Te=Math.max(Te??-1/0,pe);
42const Ve=Ee.clone({timestamp:pe,duration:Fe-pe,sideData:x==="discard"?{}:Ee.sideData,type:Dt});this._reportProgress(i,Ve.timestamp+Ve.duration),await re.add(Ve,me),this._synchronizer.shouldWait(i,Ve.timestamp)&&await this._synchronizer.wait(Ve.timestamp),await this._checkpoint($,Ve.timestamp)}re.close(),this._synchronizer.closeTrack(i)})}let F=null;!t.group&&!this._composable&&(F=new st);const D=await e.getLanguageCode(),z=await e.getName(),V=await e.getDisposition(),j=I?null:await e.getBitrate(),oe=I?null:await e.getAverageBitrate();this.output.addVideoTrack(s,{frameRate:t.frameRate,languageCode:gi(D)?D:void 0,name:z??void 0,disposition:V,rotation:u,flip:d,transformationMatrix:f??void 0,group:F??t.group,bitrate:j??void 0,averageBitrate:oe??void 0}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(F)}async _processAudioTrack(e,t,i){const n=await e.getCodec();if(!n){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let s;const a=await e.getNumberOfChannels(),o=await e.getSampleRate();let c=t.numberOfChannels??a,l=t.sampleRate??o,u=this.output.format.getSupportedAudioCodecs(),d=!this._copyMode||!!t.forceTranscode||!!t.quality||!!t.bitrate||c!==a||l!==o||
42!u.includes(n)||!!t.codec&&t.codec!==n||t.process!==void 0||t.sampleFormat!==void 0,f=null;if(!d){const k=new Ht(e);let S=await k.getKeyPacket(this._startTimestamp)??await k.getFirstKeyPacket();S&&(this._copyBoundaryPolicy==="shrink"&&S.timestamp<this._startTimestamp||this._copyBoundaryPolicy==="expand"&&S.timestamp+S.duration<=this._startTimestamp)&&(S=await k.getNextKeyPacket(S));const T=Lt.includes(n)&&n!=="flac";if(S&&this._copyBoundaryPolicy==="expand"&&T){const A=await k.getKeyPacket(S.timestamp-1/await e.getTimeResolution());A&&(S=A)}if(f=S,S)if((this._copyBoundaryPolicy==="shrink"?Math.max(S.timestamp-this._startTimestamp,0):Math.max(this._startTimestamp-S.timestamp,0))>this._copyBoundaryTolerance)d=!0;else if(this.output.format.supportsTimestampedMediaData){if(this.output.format.negativeTimestampSupport!=="full"&&S.timestamp<this._startTimestamp){const P=Math.min(this._startTimestamp-S.timestamp,this._copyTimestampShiftTolerance);S.timestamp+P>=this._startTimestamp||this.output.format.negativeTimestampSupport==="prefer-non-negative"&&this._copyMode==="forced"?this._timestampOffset=Math.max(this._timestampOffset,-this._startTimestamp+P):d=!0}}else if(this._timestampOffsetAdjusted)S.timestamp+this._timestampOffset===0||(d=!0);else{const P=le(this._startTimestamp-S.timestamp,-this._copyTimestampShiftTolerance,this._copyTimestampShiftTolerance);S.timestamp+P===this._startTimestamp?(this._timestampOffset=-this._startTimestamp+P,this._timestampOffsetAdjusted=!0):d=!0}}if(d&&this._copyMode==="forced"){this.discardedTracks.push({track:e,reason:"cannot_copy",trackOptions:t});return}if(d){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}let S=null;t.codec&&(u=u.filter(I=>I===t.codec));const T=Or(t.quality,t.bitrate)??new he("high"),A=await Hs(u,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:c,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:l,quality:T});if(!A.some(I=>Lt.includes(I))&&u.some(I=>Lt.includes(I))&&(c!==hs||l!==ms)){const E=(await Hs(u,{numberOfChannels:hs,sampleRate:ms,quality:T})).find(F=>Lt.includes(F));E&&(S=E,c=hs,l=ms)}else S=A[0]??null;if(S===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const P={codec:S,quality:T,transform:{sampleFormat:t.sampleFormat,process:t.process}};p(P.transform),c!==a&&(P.transform.numberOfChannels=c),l!==o&&(P.transform.sampleRate=l);let C=null;P.onEncodedSample=I=>{C=I.timestamp};const x=new Bp(P);s=x,this._registerTrackPump(async I=>{let E=null;const F=new nu(e);for await(const D of F.samples(this._startTimestamp,this._endTimestamp)){const z={stack:[],error:void 0,hasError:!1};try{const V=ri(z,D,!1);if(this._state==="canceled")break;let j=0,oe=V.numberOfFrames;if(V.timestamp<this._startTimestamp&&(j=Math.round((this._startTimestamp-V.timestamp)*V.sampleRate)),V.timestamp+V.duration>this._endTimestamp&&(oe=Math.round((this._endTimestamp-V.timestamp)*V.sampleRate)),j>=oe){V.close();continue}let re;if(j>0||oe<V.numberOfFrames){const G=V.trim(j,oe);if(V.close(),re=G,G.numberOfFrames===0){G.close();continue}}else re=V;const $=ri(z,re,!1);if($.setTimestamp($.timestamp+this._timestampOffset),E===null&&(E=$.timestamp>0&&!this.output.format.supportsTimestampedMediaData),E){const G={stack:[],error:void 0,hasError:!1};try{const J=$.timestamp,me=Math.round(J*o),Te=Tt(V.format),Ee=new Uint8Array(Te*me*a);(V.format==="u8"||V.format==="u8-planar")&&Ee.fill(2**7);const pe=ri(G,new be({data:Ee,format:V.format,numberOfChannels:a,sampleRate:o,timestamp:0}),!1);await this._registerAudioSample(I,pe,x,i,()=>C),E=!1}catch(J){G.error=J,G.hasError=!0}finally{ji(G)}}await this._registerAudioSample(I,$,x,i,()=>C)}catch(V){z.error=V,z.hasError=!0}finally{ji(z)}}x.close(),this._synchronizer.closeTrack(i)})}else{const k=new Xs(n);s=k,this._registerTrackPump(async S=>{const T=new Ht(e),P={decoderConfig:await e.getDecoderConfig()??void 0};let C=null;if(f)for await(const x of T.packets(f)){if(this._state==="canceled"||x.timestamp>=this._endTimestamp||this._copyBoundaryPolicy==="shrink"&&x.timestamp+x.duration>this._endTimestamp)break;const I=x.timestamp+this._timestampOffset;if(C!==null&&I<C)continue;C=I;
42const E=x.clone({timestamp:I,duration:x.duration});this._reportProgress(i,E.timestamp+E.duration),await k.add(E,P),this._synchronizer.shouldWait(i,E.timestamp)&&await this._synchronizer.wait(E.timestamp),await this._checkpoint(S,E.timestamp)}k.close(),this._synchronizer.closeTrack(i)})}let h=null;!t.group&&!this._composable&&(h=new st);const g=await e.getLanguageCode(),m=await e.getName(),w=await e.getDisposition(),y=d?null:await e.getBitrate(),b=d?null:await e.getAverageBitrate();this.output.addAudioTrack(s,{languageCode:gi(g)?g:void 0,name:m??void 0,disposition:w,group:h??t.group,bitrate:y??void 0,averageBitrate:b??void 0}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(h)}async _registerAudioSample(e,t,i,n,s){this._reportProgress(n,t.timestamp+t.duration),await i.add(t),t.close();const a=s();a!==null&&(this._synchronizer.shouldWait(n,a)&&await this._synchronizer.wait(a),await this._checkpoint(e,a))}_registerTrackPump(e){const t={done:!1,resolvers:ne(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},i=>{t.resolvers.reject(i)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;this._state!=="canceled"&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();const{promise:i,resolve:n}=ne();e.wake=n,await i}}_reportProgress(e,t){if(!this._computeProgress)return;p(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const i=Math.min(...this._maxTimestamps.values()),n=le(i/this._totalDuration,0,1);n!==this._lastProgress&&(this._lastProgress=n,this.onProgress?.(n,i))}}class gc extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const wc=1;class Lp{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,-1/0)}shouldWait(e,t){const i=this.maxTimestamps.get(e);p(i!==void 0),this.maxTimestamps.set(e,Math.max(t,i));const n=this.computeMinAndMaybeResolve();return this.conversion._state==="canceled"||this.conversion._pauseRequested||t>=this.conversion._executionUntil?!1:t-n>wc}wait(e){const{promise:t,resolve:i}=ne();return this.resolvers.push({timestamp:e,resolve:i}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(const e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){const i=this.resolvers[t];i.timestamp-e<wc&&(i.resolve(),this.resolvers.splice(t,1),t--)}return e}}const xu=Symbol.for("mediabunny loaded");globalThis[xu]&&O._error(`[WARNING]
43Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[xu]=!0;export{Hl as ADTS,$p as ALL_FORMATS,pc as ALL_TRACK_TYPES,xe as AUDIO_CODECS,jf as AdtsInputFormat,xg as AdtsOutputFormat,mg as AppendOnlyStreamTarget,ia as AttachedFile,fg as AudioBufferSink,yg as AudioBufferSource,be as AudioSample,$r as AudioSampleResource,nu as AudioSampleSink,Bp as AudioSampleSource,Di as AudioSource,ru as BaseMediaSampleSink,Qp as BlobSource,Kp as BufferSource,os as BufferTarget,dg as CanvasSink,gg as CanvasSource,hc as CmafOutputFormat,jp as ConcurrentRunner,Au as Conversion,gc as ConversionCanceledError,bh as CustomAudioDecoder,Th as CustomAudioEncoder,Ef as CustomPathedSource,Rl as CustomSource,yh as CustomVideoDecoder,kh as CustomVideoEncoder,Xs as EncodedAudioPacketSource,te as EncodedPacket,Ht as EncodedPacketSink,$s as EncodedVideoPacketSource,vi as EventEmitter,Yf as FLAC,Fl as FilePathSource,pg as FilePathTarget,Hf as FlacInputFormat,Pg as FlacOutputFormat,Kl as HLS,Xp as HLS_FORMATS,Vl as HlsInputFormat,_g as HlsOutputFormat,Mn as Input,Rn as InputAudioTrack,Me as InputDisposedError,pt as InputFormat,Ri as InputTrack,Fn as InputVideoTrack,Ul as IsobmffInputFormat,Da as IsobmffOutputFormat,lt as LogLevel,O as Logging,Qf as MATROSKA,ql as MP3,Wl as MP4,jl as MPEG_TS,Nl as MatroskaInputFormat,Fa as MediaSource,bg as MediaStreamAudioTrackSource,wg as MediaStreamVideoTrackSource,mc as MkvOutputFormat,Su as MovOutputFormat,Wf as Mp3InputFormat,Tg as Mp3OutputFormat,Uf as Mp4InputFormat,Tu as Mp4OutputFormat,Kf as MpegTsInputFormat,Cg as MpegTsOutputFormat,Lt as NON_PCM_AUDIO_CODECS,gu as NullTarget,Xf as OGG,qf as OggInputFormat,Ag as OggOutputFormat,gn as Output,Vp as OutputAudioTrack,Xe as OutputFormat,Wp as OutputSubt
43itleTrack,zi as OutputTrack,st as OutputTrackGroup,Np as OutputVideoTrack,ke as PCM_AUDIO_CODECS,gr as PathedSource,Vt as PathedTarget,Ll as QTFF,ig as QUALITY_HIGH,tg as QUALITY_LOW,rg as QUALITY_MEDIUM,ng as QUALITY_VERY_HIGH,eg as QUALITY_VERY_LOW,he as Quality,Nf as QuickTimeInputFormat,Mf as RangedSource,op as RangedTarget,Ml as ReadableStreamSource,Br as RichImageData,mt as SUBTITLE_CODECS,$e as Source,ba as SourceRef,Gp as StreamSource,pu as StreamTarget,ku as SubtitleSource,qe as Target,kg as TextSubtitleSource,Go as UnsupportedInputFormatError,Bl as UrlSource,we as VIDEO_CODECS,Vs as VIDEO_SAMPLE_PIXEL_FORMATS,_e as VideoSample,Xn as VideoSampleColorSpace,$t as VideoSampleResource,js as VideoSampleSink,dc as VideoSampleSource,Mi as VideoSource,$f as WAVE,Gf as WEBM,Sg as WavOutputFormat,Lf as WaveInputFormat,Vf as WebMInputFormat,ds as WebMOutputFormat,hg as asc,Yp as canDecode,Gl as canDecodeAudio,Ql as canDecodeVideo,sg as canEncode,Pa as canEncodeAudio,Ca as canEncodeSubtitles,xa as canEncodeVideo,Ko as desc,rh as getDecodableAudioCodecs,Zp as getDecodableCodecs,th as getDecodableVideoCodecs,Hs as getEncodableAudioCodecs,ag as getEncodableCodecs,gh as getEncodableSubtitleCodecs,ph as getEncodableVideoCodecs,og as getFirstEncodableAudioCodec,cg as getFirstEncodableSubtitleCodec,wh as getFirstEncodableVideoCodec,Yr as prefer,lg as registerDecoder,ug as registerEncoder,Jp as registerVideoSampleTransformer};

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.