@qratilabs/qrati-connect 2.22.0-beta.1 → 2.22.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ import{r as e,t}from"./DdACKOZr.js";function i(e){if(!e)throw new Error("Assertion failed.")}var r,a=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},s=e=>e&&e[e.length-1],n=e=>e>=0&&e<2**32,o=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},c=e=>{const t=o(e);return 1&t?t+1>>1:-(t>>1)},l=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),d=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),u=/* @__PURE__ */new TextDecoder,h=/* @__PURE__ */new TextEncoder,m=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),f={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},p=/* @__PURE__ */m(f),g={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},k=/* @__PURE__ */m(g),w={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},b=/* @__PURE__ */m(w),y=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e),T=class{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}},S=/^[0-9a-fA-F]+$/,v=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),P=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,C=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o<t?r=n+1:a=n-1}return s},x=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},I=(e,t,i)=>{const r=x(e,i(t),i);e.splice(r+1,0,t)},E=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},_=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},B=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},A=e=>{throw new Error(`Unexpected value: ${e}`)},R=(e,t,i)=>{const r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},F=(e,t,i,r)=>{i>>>=0,i&=16777215,r?(e.setUint8(t,255&i),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,i>>>16&255)):(e.setUint8(t,i>>>16&255),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,255&i))},M=(e,t)=>({async next(){const i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),D=(e,t,i)=>Math.max(t,Math.min(i,e)),z=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},O=(e,t)=>Math.round(e/t)*t,N=(e,t)=>Math.round(e*t)/t,L=(e,t)=>Math.floor(e/t)*t,U=(e,t)=>Math.floor(e*t)/t,W=/^[a-z]{3}$/,V=e=>W.test(e),q=1e6*(1+Number.EPSILON),H=class{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}},j=null,$=()=>null!==j?j:j=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),K=null,X=()=>null!==K?K:K="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),G=null,Q=()=>null!==G?G:G=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),Y=null,J=()=>{if(null!==Y)return Y;if("undefined"==typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?Y=Number(e[1]):null},Z=(e,t)=>-1!==e?e:t,ee=(e,t,i,r)=>e<=r&&i<=t,te=function*(e){for(const t in e){const i=e[t];void 0!==i&&(yield{key:t,value:i})}},ie=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return i},re=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},ae=e=>"number"==typeof e&&!Number.isNaN(e),se=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const a=e.indexOf("/",r+3);i=-1===a?e+t:e.slice(0,a)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const a=i.indexOf("://");if(-1!==a){const e=i.indexOf("/",a+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),n=[];for(const o of s)".."===o?n.pop():"."!==o&&n.push(o);return r+n.join("/")},ne=(e,t)=>{let i=0;for(let r=0;r<e.length;r++)t(e[r])&&i++;return i},oe=(e,t)=>{let i=-1,r=1/0;for(let a=0;a<e.length;a++){const s=t(e[a]);s<r&&(r=s,i=a)}return i},ce=e=>{i(Number.isInteger(e.num)),i(Number.isInteger(e.den)),i(0!==e.den);let t=Math.abs(e.num),r=Math.abs(e.den);for(;0!==r;){const e=t%r;t=r,r=e}const a=t||1;return{num:e.num/a,den:e.den/a}},le=(e,t)=>{if("object"!=typeof e||!e)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},de=e=>Array.isArray(e)?e:[e],ue=class{constructor(){this._listeners=/* @__PURE__ */new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,/* @__PURE__ */new Set);const r={fn:t,once:i?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(a){console.error(a)}s.once&&r.delete(s)}}},he=e=>2*Math.ceil(e/2),me=e=>null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>"string"==typeof e),fe=class{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!=typeof t)throw new TypeError("mimeType must be a string.")}},pe=class{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw new TypeError("description, when provided, must be a string.")}},ge=e=>{if(!e||"object"!=typeof e)throw new TypeError("tags must be an object.");if(void 0!==e.title&&"string"!=typeof e.title)throw new TypeError("tags.title, when provided, must be a string.");if(void 0!==e.description&&"string"!=typeof e.description)throw new TypeError("tags.description, when provided, must be a string.");if(void 0!==e.artist&&"string"!=typeof e.artist)throw new TypeError("tags.artist, when provided, must be a string.");if(void 0!==e.album&&"string"!=typeof e.album)throw new TypeError("tags.album, when provided, must be a string.");if(void 0!==e.albumArtist&&"string"!=typeof e.albumArtist)throw new TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==e.trackNumber&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==e.tracksTotal&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==e.discNumber&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==e.discsTotal&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==e.genre&&"string"!=typeof e.genre)throw new TypeError("tags.genre, when provided, must be a string.");if(void 0!==e.date&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==e.lyrics&&"string"!=typeof e.lyrics)throw new TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==e.images){if(!Array.isArray(e.images))throw new TypeError("tags.images, when provided, must be an array.");for(const t of e.images){if(!t||"object"!=typeof t)throw new TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof t.mimeType)throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==e.comment&&"string"!=typeof e.comment)throw new TypeError("tags.comment, when provided, must be a string.");if(void 0!==e.raw){if(!e.raw||"object"!=typeof e.raw)throw new TypeError("tags.raw, when provided, must be an object.");for(const t of Object.values(e.raw))if(!(null===t||"string"==typeof t||t instanceof Uint8Array||t instanceof fe||t instanceof pe||me(t)))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},ke={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},we=class e{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-(7&this.pos),r=(t&1<<i)>>i;return this.pos++,r}readBits(e){if(1===e)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 r=this.pos;r<i;r++){const e=Math.floor(r/8);let a=this.bytes[e];const s=7-(7&r);a&=~(1<<s),a|=(t&1<<i-r-1)>>i-r-1<<s,this.bytes[e]=a}this.pos=i}readAlignedByte(){if(this.pos%8!=0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const t=new e(this.bytes);return t.pos=this.pos,t}},be=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],ye=[-1,1,2,3,4,5,6,8],Te=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new we(e);let i=t.readBits(5);31===i&&(i=32+t.readBits(6));const r=t.readBits(4);let a=null;15===r?a=t.readBits(24):r<be.length&&(a=be[r]);const s=t.readBits(4);let n=null;return s>=1&&s<=7&&(n=ye[s]),{objectType:i,frequencyIndex:r,sampleRate:a,channelConfiguration:s,numberOfChannels:n}},Se=e=>{let t=be.indexOf(e.sampleRate),i=null;-1===t&&(t=15,i=e.sampleRate);const r=ye.indexOf(e.numberOfChannels);if(-1===r)throw new TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let a=13;e.objectType>=32&&(a+=6),15===t&&(a+=24);const s=Math.ceil(a/8),n=new Uint8Array(s),o=new we(n);return e.objectType<32?o.writeBits(5,e.objectType):(o.writeBits(5,31),o.writeBits(6,e.objectType-32)),o.writeBits(4,t),15===t&&o.writeBits(24,i),o.writeBits(4,r),n},ve=["avc","hevc","vp9","av1","vp8"],Pe=["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"],Ce=["aac","opus","mp3","vorbis","flac","ac3","eac3"],xe=[...Ce,...Pe],Ie=["webvtt"],Ee=[{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}],_e=[{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}],Be=[{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}],Ae=[{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}],Re=(e,t,i,r)=>{if("avc"===e){const e=100,a=Math.ceil(t/16)*Math.ceil(i/16),n=Ee.find(e=>a<=e.maxMacroblocks&&r<=e.maxBitrate)??s(Ee),o=n?n.level:0;return`avc1.${e.toString(16).padStart(2,"0")}00${o.toString(16).padStart(2,"0")}`}if("hevc"===e){const e="",a=1,n="6",o=t*i,c=_e.find(e=>o<=e.maxPictureSize&&r<=e.maxBitrate)??s(_e);return`hev1.${e}${a}.${n}.${c.tier}${c.level}.B0`}if("vp8"===e)return"vp8";if("vp9"===e){const e=t*i;return`vp09.00.${(Be.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??s(Be)).level.toString().padStart(2,"0")}.08`}if("av1"===e){const e=0,a=t*i,n=Ae.find(e=>a<=e.maxPictureSize&&r<=e.maxBitrate)??s(Ae);return`av01.${e}.${n.level.toString().padStart(2,"0")}${n.tier}.08`}throw new TypeError(`Unhandled codec '${e}'.`)},Fe=e=>{const{codec:t,codecDescription:r,colorSpace:a,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:c,av1CodecInfo:l}=e;if("avc"===t){if(i(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${v(t)}`}if(!r||r.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${v(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,i=P(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=d(r),c=o.getUint8(1);e=c>>6&3,t=31&c,i=P(o.getUint32(2)),a=c>>5&1,s=o.getUint8(12),n=[];for(let e=0;e<6;e++)n.push(o.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=i.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(c+=".",c+=n.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!c){const t=e.width*e.height;let i=s(Be).level;for(const e of Be)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${c.profile.toString().padStart(2,"0")}.${c.level.toString().padStart(2,"0")}.${c.bitDepth.toString().padStart(2,"0")}.${c.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${c.colourPrimaries.toString().padStart(2,"0")}.${c.transferCharacteristics.toString().padStart(2,"0")}.${c.matrixCoefficients.toString().padStart(2,"0")}.${c.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(".01.01.01.01.00")&&(t=t.slice(0,-15)),t}if("av1"===t){if(!l){const t=e.width*e.height;let i=s(Be).level;for(const e of Be)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=l.profile,i=l.level.toString().padStart(2,"0"),r=l.tier?"H":"M",n=l.bitDepth.toString().padStart(2,"0"),o=l.monochrome?"1":"0",c=100*l.chromaSubsamplingX+10*l.chromaSubsamplingY+1*(l.chromaSubsamplingX&&l.chromaSubsamplingY?l.chromaSamplePosition:0),d=a?.primaries?f[a.primaries]:1,u=a?.transfer?g[a.transfer]:1,h=a?.matrix?w[a.matrix]:1,m=a?.fullRange?1:0;let p=`av01.${t}.${i}${r}.${n}`;return p+=`.${o}.${c.toString().padStart(3,"0")}`,p+=`.${d.toString().padStart(2,"0")}`,p+=`.${u.toString().padStart(2,"0")}`,p+=`.${h.toString().padStart(2,"0")}`,p+=`.${m}`,p.endsWith(".0.110.01.01.01.0")&&(p=p.slice(0,-17)),p}throw new TypeError(`Unhandled codec '${t}'.`)},Me=(e,t,i)=>{if("aac"===e)return t>=2&&i<=24e3?"mp4a.40.29":i<=24e3?"mp4a.40.5":"mp4a.40.2";if("mp3"===e)return"mp3";if("opus"===e)return"opus";if("vorbis"===e)return"vorbis";if("flac"===e)return"flac";if("ac3"===e)return"ac-3";if("eac3"===e)return"ec-3";if(Pe.includes(e))return e;throw new TypeError(`Unhandled codec '${e}'.`)},De=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;return e=null!==r.objectType?r.objectType:Te(i).objectType,`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if(t&&Pe.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},ze=48e3,Oe=/^pcm-([usf])(\d+)(be)?$/,Ne=e=>{if(i(Pe.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=Oe.exec(e);let r;return i(t),r="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float",{dataType:r,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},Le=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Oe.test(e)?e:"webvtt"===e?"webvtt":null,Ue=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],We=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ve=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,qe=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,He=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,je=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],$e=[44100,48e3,32e3],Ke=[-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],Xe=(e,t)=>3===e?3===t?21:36:3===t?13:21,Ge=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224&~r)return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,d=(a>>2&3)%3,u=s>>6&3,h=s>>4&3,m=s>>3&1,f=s>>2&1,p=3&s,g=Ke[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,w=$e[d]>>n+o,b=((e,t,i,r,a)=>0===t?0:1===t?Math.floor(144*i/(r<<e))+a:2===t?Math.floor(144*i/r)+a:4*(Math.floor(12*i/r)+a))(n,l,k,w,a>>1&1);if(null!==t&&t<b)return{header:null,bytesAdvanced:1};let y;return y=3===c?3===l?384:1152:3===l?384:2===l?1152:576,{header:{totalSize:b,mpegVersionId:c,lowSamplingFrequency:n,layer:l,bitrate:k,frequencyIndex:d,sampleRate:w,channel:u,modeExtension:h,copyright:m,original:f,emphasis:p,audioSamplesInFrame:y},bytesAdvanced:1}},Qe=e=>{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};!function(e){e[e.FrameCount=1]="FrameCount",e[e.FileSize=2]="FileSize",e[e.Toc=4]="Toc"}(r||(r={}));var Ye,Je,Ze=[48e3,44100,32e3],et=[24e3,22050,16e3];!function(e){e[e.NON_IDR_SLICE=1]="NON_IDR_SLICE",e[e.SLICE_DPA=2]="SLICE_DPA",e[e.SLICE_DPB=3]="SLICE_DPB",e[e.SLICE_DPC=4]="SLICE_DPC",e[e.IDR=5]="IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.SPS_EXT=13]="SPS_EXT"}(Ye||(Ye={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(Je||(Je={}));var tt,it=function*(e){let t=0,i=-1;for(;t<e.length-2;){const r=e.indexOf(0,t);if(-1===r||r>=e.length-2)break;t=r;let a=0;t+3<e.length&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]?a=4:0===e[t+1]&&1===e[t+2]&&(a=3),0!==a?(-1!==i&&t>i&&(yield{offset:i,length:t-i}),i=t+a,t=i):t++}-1!==i&&i<e.length&&(yield{offset:i,length:e.length-i})},rt=function*(e,t){let r=0;const a=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;r+t<=e.length;){let e;1===t?e=a.getUint8(r):2===t?e=a.getUint16(r,!1):3===t?e=R(a,r,!1):(i(4===t),e=a.getUint32(r,!1)),r+=t,yield{offset:r,length:e},r+=e}},at=(e,t)=>t.description?rt(e,1+(3&l(t.description)[4])):it(e),st=e=>31&e,nt=e=>{const t=[],i=e.length;for(let r=0;r<i;r++)r+2<i&&0===e[r]&&0===e[r+1]&&3===e[r+2]?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},ot=new Uint8Array([0,0,0,1]),ct=e=>{const t=e.reduce((e,t)=>e+ot.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(ot,r),r+=ot.byteLength,i.set(a,r),r+=a.byteLength;return i},lt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let a=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(a,s.byteLength);break;case 2:e.setUint16(a,s.byteLength,!1);break;case 3:F(e,a,s.byteLength,!1);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},dt=e=>{try{const t=[],r=[],a=[];for(const i of it(e)){const s=e.subarray(i.offset,i.offset+i.length),n=st(s[0]);n===Ye.SPS?t.push(s):n===Ye.PPS?r.push(s):n===Ye.SPS_EXT&&a.push(s)}if(0===t.length)return null;if(0===r.length)return null;const s=t[0],n=ht(s);i(null!==n);const o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},ut={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}},ht=e=>{try{const t=new we(nt(e));if(t.skipBits(1),t.skipBits(2),7!==t.readBits(5))return null;const r=t.readAlignedByte(),a=t.readAlignedByte(),n=t.readAlignedByte();o(t);let l=1,d=0,u=0,h=0;if((100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r)&&(l=o(t),3===l&&(h=t.readBits(1)),d=o(t),u=o(t),t.skipBits(1),t.readBits(1)))for(let e=0;e<(3!==l?8:12);e++)if(t.readBits(1)){const i=e<6?16:64;let r=8,a=8;for(let e=0;e<i;e++)0!==a&&(a=(r+c(t)+256)%256),r=0===a?r:a}o(t);const m=o(t);if(0===m)o(t);else if(1===m){t.skipBits(1),c(t),c(t);const e=o(t);for(let i=0;i<e;i++)c(t)}o(t),t.skipBits(1);const f=o(t),p=o(t),g=16*(f+1),k=16*(p+1);let w=g,b=k;const y=t.readBits(1);if(y||t.skipBits(1),t.skipBits(1),t.readBits(1)){const e=o(t),i=o(t),r=o(t),a=o(t);let s,n;0===(0===h?l:0)?(s=1,n=2-y):(s=3===l?1:2,n=(1===l?2:1)*(2-y)),w-=s*(e+i),b-=n*(r+a)}let T=2,S=2,v=2,P=0,C={num:1,den:1},x=null,I=null;if(t.readBits(1)){if(t.readBits(1)){const e=t.readBits(8);if(255===e)C={num:t.readBits(16),den:t.readBits(16)};else{const t=ut[e];t&&(C=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),P=t.readBits(1),t.readBits(1)&&(T=t.readBits(8),S=t.readBits(8),v=t.readBits(8))),t.readBits(1)&&(o(t),o(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));const e=t.readBits(1);e&&mt(t);const i=t.readBits(1);i&&mt(t),(e||i)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),o(t),o(t),o(t),o(t),x=o(t),I=o(t))}if(null===x)if(i(null===I),(44===r||86===r||100===r||110===r||122===r||244===r)&&16&a)x=0,I=0;else{const e=f+1,t=(2-y)*(p+1),i=Ee.find(e=>e.level>=n)??s(Ee),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);x=r,I=r}return i(null!==I),{profileIdc:r,constraintFlags:a,levelIdc:n,frameMbsOnlyFlag:y,chromaFormatIdc:l,bitDepthLumaMinus8:d,bitDepthChromaMinus8:u,codedWidth:g,codedHeight:k,displayWidth:w,displayHeight:b,pixelAspectRatio:C,colourPrimaries:T,matrixCoefficients:v,transferCharacteristics:S,fullRangeFlag:P,numReorderFrames:x,maxDecFrameBuffering:I}}catch(t){return console.error("Error parsing AVC SPS:",t),null}},mt=e=>{const t=o(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)o(e),o(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},ft=(e,t)=>t.description?rt(e,1+(3&l(t.description)[21])):it(e),pt=e=>e>>1&63,gt=e=>{try{const t=new we(nt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:c,general_constraint_indicator_flags:l,general_level_idc:d}=wt(t,i);o(t);const u=o(t);let h=0;3===u&&(h=t.readBits(1));const m=o(t),f=o(t);let p=m,g=f;if(t.readBits(1)){const e=o(t),i=o(t),r=o(t),a=o(t);let s=1,n=1;const c=0===h?u:0;1===c?(s=2,n=2):2===c&&(s=2,n=1),p-=(e+i)*s,g-=(r+a)*n}const k=o(t),w=o(t);o(t);const b=t.readBits(1)?0:i;let y=0;for(let e=b;e<=i;e++)o(t),y=o(t),o(t);if(o(t),o(t),o(t),o(t),o(t),o(t),t.readBits(1)&&t.readBits(1)&&bt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),o(t),o(t),t.skipBits(1)),yt(t,o(t)),t.readBits(1)){const e=o(t);for(let i=0;i<e;i++)o(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let T=2,S=2,v=2,P=0,C=0,x={num:1,den:1};if(t.readBits(1)){const e=St(t,i);x=e.pixelAspectRatio,T=e.colourPrimaries,S=e.transferCharacteristics,v=e.matrixCoefficients,P=e.fullRangeFlag,C=e.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:x,colourPrimaries:T,transferCharacteristics:S,matrixCoefficients:v,fullRangeFlag:P,maxDecFrameBuffering:y+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:n,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:d,chromaFormatIdc:u,bitDepthLumaMinus8:k,bitDepthChromaMinus8:w,minSpatialSegmentationIdc:C}}catch(t){return console.error("Error parsing HEVC SPS:",t),null}},kt=e=>{try{const t=[],i=[],r=[],a=[];for(const o of it(e)){const s=e.subarray(o.offset,o.offset+o.length),n=pt(s[0]);n===Je.VPS_NUT?t.push(s):n===Je.SPS_NUT?i.push(s):n===Je.PPS_NUT?r.push(s):n!==Je.PREFIX_SEI_NUT&&n!==Je.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=gt(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new we(nt(e));t.skipBits(16),o(t),o(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),o(t),o(t),c(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&o(t),c(t),c(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const l=[...t.length?[{arrayCompleteness:1,nalUnitType:Je.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Je.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Je.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:pt(a[0][0]),nalUnits:a}]:[]];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:n,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:l}}catch(t){return console.error("Error building HEVC Decoder Configuration Record:",t),null}},wt=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let d=0;d<32;d++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let d=0;d<6;d++)n[d]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let d=0;d<t;d++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let d=t;d<8;d++)e.skipBits(2);for(let d=0;d<t;d++)c[d]&&e.skipBits(88),l[d]&&e.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},bt=e=>{for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++)if(e.readBits(1)){const i=Math.min(64,1<<4+(t<<1));t>1&&c(e);for(let t=0;t<i;t++)c(e)}else o(e)},yt=(e,t)=>{const i=[];for(let r=0;r<t;r++)i[r]=Tt(e,r,t,i)},Tt=(e,t,i,r)=>{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){n=t===i?t-(o(e)+1):t-1,e.readBits(1),o(e);const s=r[n]??0;for(let t=0;t<=s;t++)e.readBits(1)||e.readBits(1);a=r[n]}else{const t=o(e),i=o(e);for(let r=0;r<t;r++)o(e),e.readBits(1);for(let r=0;r<i;r++)o(e),e.readBits(1);a=t+i}return a},St=(e,t)=>{let i=2,r=2,a=2,s=0,n=0,c={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)c={num:e.readBits(16),den:e.readBits(16)};else{const e=ut[t];e&&(c=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(o(e),o(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(o(e),o(e),o(e),o(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&o(e),e.readBits(1)&&vt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=o(e),o(e),o(e),o(e),o(e)),{pixelAspectRatio:c,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},vt=(e,t,i)=>{let r=!1,a=!1,s=!1;t&&(r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let n=0;n<=i;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?o(e):i=1===e.readBits(1);let n=1;i||(n=o(e)+1),r&&Pt(e,n,s),a&&Pt(e,n,s)}},Pt=(e,t,i)=>{for(let r=0;r<t;r++)o(e),o(e),i&&(o(e),o(e)),e.readBits(1)};!function(e){e[e.audAllowed=0]="audAllowed",e[e.beforeFirstVcl=1]="beforeFirstVcl",e[e.afterFirstVcl=2]="afterFirstVcl",e[e.eoBitstreamAllowed=3]="eoBitstreamAllowed",e[e.noMoreDataAllowed=4]="noMoreDataAllowed"}(tt||(tt={}));var Ct,xt=e=>{const t=new we(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;if(3===r&&t.skipBits(1),1===t.readBits(1))return null;if(0!==t.readBits(1))return null;if(t.skipBits(2),4817730!==t.readBits(24))return null;let a=8;r>=2&&(a=t.readBits(1)?12:10);const n=t.readBits(3);let o=0,c=0;if(7!==n)if(c=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);o=e||i?e&&!i?2:1:3,t.skipBits(1)}else o=1;else o=3,c=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let d=s(Be).level;for(const s of Be)if(l<=s.maxPictureSize){d=s.level;break}return{profile:r,level:d,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:2===n?1:1===n?6:2,transferCharacteristics:2===n?1:1===n?6:2,matrixCoefficients:7===n?0:2===n?1:1===n?6:2}},It=function*(e){const t=new we(e),r=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const a=t.readBits(4),s=t.readBits(1),n=t.readBits(1);let o;if(t.skipBits(1),s&&t.skipBits(8),n){const e=r();if(null===e)return;o=e}else o=Math.floor(t.getBitsLeft()/8);i(t.pos%8==0),yield{type:a,data:e.subarray(t.pos/8,t.pos/8+o)},t.skipBits(8*o)}},Et=e=>{for(const{type:t,data:i}of It(e)){if(1!==t)continue;const e=new we(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);const i=e.readBits(5);if(0===r&&(s=i),i>7){const t=e.readBits(1);0===r&&(n=t)}if(t&&e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}const c=e.readBits(4),l=e.readBits(4),d=c+1;e.skipBits(d);const u=l+1;e.skipBits(u);let h=0;if(h=a?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;i=e.readBits(1)?2:e.readBits(1),i>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const m=e.readBits(1);let f=8;2===r&&m?f=e.readBits(1)?12:10:r<=2&&(f=m?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=1,k=1,w=0;return p||(0===r?(g=1,k=1):1===r?(g=0,k=0):12===f&&(g=e.readBits(1),g&&(k=e.readBits(1))),g&&k&&(w=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:f,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:w}}return null},_t=e=>{const t=d(e),i=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}},Bt=[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],At=e=>{if(e.length<7)throw new Error("Setup header is too short.");if(5!==e[0])throw new Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw new Error("Invalid packet signature in Setup header.");const t=e.length,i=new Uint8Array(t);for(let d=0;d<t;d++)i[d]=e[t-1-d];const r=new we(i);let a=0;for(;r.getBitsLeft()>97;)if(1===r.readBits(1)){a=r.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;r.getBitsLeft()>=97;){const e=r.pos,t=r.readBits(8),i=r.readBits(16),a=r.readBits(16);if(t>63||0!==i||0!==a){r.pos=e;break}if(r.skipBits(1),s++,s>64)break;r.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;r.pos=0,r.skipBits(a);const l=Array(c).fill(0);for(let d=c-1;d>=0;d--)r.skipBits(40),l[d]=r.readBits(1);return{modeBlockflags:l}},Rt=(e,t,r)=>{switch(e){case"avc":for(const e of at(r,t)){const t=r[e.offset],i=st(t);if(i>=Ye.NON_IDR_SLICE&&i<=Ye.SLICE_DPC)return"delta";if(i===Ye.IDR)return"key";if(i===Ye.SEI&&(!Q()||J()>=144)){const t=nt(r.subarray(e.offset,e.offset+e.length));let i=1;do{let e=0;for(;;){const r=t[i++];if(void 0===r)break;if(e+=r,r<255)break}let r=0;for(;;){const e=t[i++];if(void 0===e)break;if(r+=e,e<255)break}if(6===e){const e=new we(t);e.pos=8*i;const r=o(e),a=e.readBits(1);if(0===r&&1===a)return"key"}i+=r}while(i<t.length-1)}}return"delta";case"hevc":for(const e of ft(r,t)){const t=pt(r[e.offset]);if(t<Je.BLA_W_LP)return"delta";if(t<=Je.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 1&r[0]?"delta":"key";case"vp9":{const e=new we(r);if(2!==e.readBits(2))return null;const t=e.readBits(1);return(e.readBits(1)<<1)+t===3&&e.skipBits(1),e.readBits(1)?null:0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:i}of It(r))if(1===t){const t=new we(i);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new we(i);return t.readBits(1)?null:0===t.readBits(2)?"key":"delta"}return null}default:A(e),i(!1)}};!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(Ct||(Ct={}));var Ft,Mt=(e,t)=>{const i=d(e);let r=0;const a=i.getUint32(r,!0);r+=4;const s=u.decode(e.subarray(r,r+a));r+=a,a>0&&(t.raw??={},t.raw.vendor??=s);const n=i.getUint32(r,!0);r+=4;for(let o=0;o<n;o++){const a=i.getUint32(r,!0);r+=4;const s=u.decode(e.subarray(r,r+a));r+=a;const n=s.indexOf("=");if(-1===n)continue;const o=s.slice(0,n).toUpperCase(),c=s.slice(n+1);switch(t.raw??={},t.raw[o]??=c,o){case"TITLE":t.title??=c;break;case"DESCRIPTION":t.description??=c;break;case"ARTIST":t.artist??=c;break;case"ALBUM":t.album??=c;break;case"ALBUMARTIST":t.albumArtist??=c;break;case"COMMENT":t.comment??=c;break;case"LYRICS":t.lyrics??=c;break;case"TRACKNUMBER":{const e=c.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.trackNumber??=i),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case"TRACKTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{const e=c.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.discNumber??=i),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case"DISCTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{const e=new Date(c);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=c;break;case"METADATA_BLOCK_PICTURE":{const e=ie(c),i=d(e),r=i.getUint32(0,!1),a=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=i.getUint32(8+a,!1),o=u.decode(e.subarray(12+a,12+a+n)),l=i.getUint32(a+n+28),h=e.subarray(a+n+32,a+n+32+l);t.images??=[],t.images.push({data:h,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},Dt=[2,1,2,3,3,4,4,5],zt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new we(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),a=t.readBits(5);if(a>8)return null;const s=t.readBits(3),n=t.readBits(3);return 1&n&&1!==n&&t.skipBits(2),4&n&&t.skipBits(2),2===n&&t.skipBits(2),{fscod:i,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Ot=[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,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840],Nt=(new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]),[1,2,3,6]),Lt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new we(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),a=t.readBits(2);let s,n=0;3===a?(n=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;const d=Nt[s];let u;return u=a<3?Ze[a]/1e3:et[n]/1e3,{dataRate:Math.round((r+1)*u/(16*d)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},Ut=e=>{const t=e.substreams[0];return i(t),t.fscod<3?Ze[t.fscod]:null!==t.fscod2&&t.fscod2<3?et[t.fscod2]:null},Wt=e=>{const t=e.substreams[0];i(t);let r=Dt[t.acmod]+t.lfeon;if(t.numDepSub>0){const e=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)t.chanLoc&1<<8-i&&(r+=e[i])}return r},Vt=class{constructor(e){this.input=e}dispose(){}},qt=/* @__PURE__ */new Uint8Array(0),Ht=class e{constructor(e,t,i,r,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=a,e===qt&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)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(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!=typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===qt}get microsecondTimestamp(){return Math.trunc(q*this.timestamp)}get microsecondDuration(){return Math.trunc(q*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(t,i){if(!(t instanceof EncodedVideoChunk||t instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(t.byteLength);return t.copyTo(r),new e(r,t.type,t.timestamp/1e6,(t.duration??0)/1e6,void 0,void 0,i)}clone(t){if(void 0!==t&&("object"!=typeof t||null===t))throw new TypeError("options, when provided, must be an object.");if(void 0!==t?.data&&!(t.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==t?.type&&"key"!==t.type&&"delta"!==t.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==t?.timestamp&&!Number.isFinite(t.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&!Number.isFinite(t.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==t?.sequenceNumber&&!Number.isFinite(t.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==t?.sideData&&("object"!=typeof t.sideData||null===t.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new e(t?.data??this.data,t?.type??this.type,t?.timestamp??this.timestamp,t?.duration??this.duration,t?.sequenceNumber??this.sequenceNumber,this.byteLength,t?.sideData??this.sideData)}},jt=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");return e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`),t},$t=e=>{const t=d(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=v(e.subarray(i,i+16));i+=16;let s=null;if(r>0){const r=t.getUint32(i);if(i+=4,r>0){s=[];for(let t=0;t<r;t++)s.push(v(e.subarray(i,i+16))),i+=16}}const n=t.getUint32(i);return i+=4,{systemId:a,keyIds:s,data:e.slice(i,i+n)}},Kt=(e,t)=>e.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0})(e.data,t.data),Xt=e=>{let t=mn(e);const i=Sn(e,4);let r=8;1===t&&(t=kn(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},Gt=e=>pn(e)/65536,Qt=e=>pn(e)/1073741824,Yt=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=on(e);if(t|=127&i,!(128&i))break}return t},Jt=e=>{let t=ln(e);return e.skip(2),t=Math.min(t,e.remainingLength),u.decode(nn(e,t))},Zt=e=>{const t=Xt(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=mn(e);e.skip(4);const r=nn(e,t.contentSize-8);switch(i){case 1:return u.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new fe(r,"image/jpeg");case 14:return new fe(r,"image/png");case 27:return new fe(r,"image/bmp");default:return r}},ei=new Uint32Array(256),ti=new Uint32Array(256),ii=new Uint32Array(256),ri=new Uint32Array(256),ai=new Uint32Array(256),si=new Uint32Array(256),ni=new Uint32Array(10),oi=!1,ci=class{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(16),this.out=new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){i(16===e.byteLength),i(16===t.byteLength),oi||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,n=1;s<256;s++)i[s]=n,t[n]=s,n=n^n<<1^(128&n?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let a=r^r<<1^r<<2^r<<3^r<<4;a=a>>>8^255&a^99,e[s]=a}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);ei[s]=t<<24|t<<16|t<<8|t,si[s]=i<<24|i<<16|i<<8|i;const a=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);ti[s]=a,ii[s]=a>>>8|a<<24,ri[s]=a>>>16|a<<16,ai[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)ni[s]=a<<24,a=a<<1^(128&a?283:0);oi=!0})();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),a=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=a.getUint32(0,!1),this.iv[1]=a.getUint32(4,!1),this.iv[2]=a.getUint32(8,!1),this.iv[3]=a.getUint32(12,!1);for(let i=4;i<44;i+=4){const e=this.roundkey[i-1];this.roundkey[i]=this.roundkey[i-4]^4278190080&ei[e>>>16&255]^16711680&ei[e>>>8&255]^65280&ei[e>>>0&255]^255&ei[e>>>24&255]^ni[i/4-1],this.roundkey[i+1]=this.roundkey[i-3]^this.roundkey[i],this.roundkey[i+2]=this.roundkey[i-2]^this.roundkey[i+1],this.roundkey[i+3]=this.roundkey[i-1]^this.roundkey[i+2]}for(let i=0,s=40;i<s;i+=4,s-=4)for(let e=0;e<4;e++){const t=this.roundkey[i+e];this.roundkey[i+e]=this.roundkey[s+e],this.roundkey[s+e]=t}for(let i=4;i<40;i+=4)for(let e=0;e<4;e++){const t=this.roundkey[i+e];this.roundkey[i+e]=ti[255&ei[t>>>24&255]]^ii[255&ei[t>>>16&255]]^ri[255&ei[t>>>8&255]]^ai[255&ei[t>>>0&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],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,d,u;for(let g=1;g<10;g++){const a=4*g;c=ti[e>>>24]^ii[r>>>16&255]^ri[i>>>8&255]^ai[255&t]^this.roundkey[a],l=ti[t>>>24]^ii[e>>>16&255]^ri[r>>>8&255]^ai[255&i]^this.roundkey[a+1],d=ti[i>>>24]^ii[t>>>16&255]^ri[e>>>8&255]^ai[255&r]^this.roundkey[a+2],u=ti[r>>>24]^ii[i>>>16&255]^ri[t>>>8&255]^ai[255&e]^this.roundkey[a+3],e=c,t=l,i=d,r=u}const h=4278190080&si[e>>>24&255]^16711680&si[r>>>16&255]^65280&si[i>>>8&255]^255&si[t>>>0&255]^this.roundkey[40],m=4278190080&si[t>>>24&255]^16711680&si[e>>>16&255]^65280&si[r>>>8&255]^255&si[i>>>0&255]^this.roundkey[41],f=4278190080&si[i>>>24&255]^16711680&si[t>>>16&255]^65280&si[e>>>8&255]^255&si[r>>>0&255]^this.roundkey[42],p=4278190080&si[r>>>24&255]^16711680&si[i>>>16&255]^65280&si[t>>>8&255]^255&si[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,m^this.iv[1],!1),this.outView.setUint32(8,f^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}},li=class e extends Vt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=/* @__PURE__ */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(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return jt({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let t=0,r=!1;for(;;){let a=this.reader.requestSliceRange(t,8,16);if(a instanceof Promise&&(a=await a),!a)break;const s=t,n=Xt(a);if(!n)break;if("ftyp"===n.name||"styp"===n.name){const e=Sn(a,4);this.isQuickTime="qt "===e}else{if("moov"===n.name){let e=this.reader.requestSlice(a.filePos,n.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}r=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>s+n.totalSize;break}if("moof"===n.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');const t=await this.input._initInput._getDemuxer();if(t.constructor!==e)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const e of t.tracks){const t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};e.trackBacking&&(i(t.info),"video"===t.info.type&&-1!==t.info.width?(t.trackBacking=new ui(t),this.tracks.push(t)):"audio"===t.info.type&&-1!==t.info.numberOfChannels&&(t.trackBacking=new hi(t),this.tracks.push(t)))}r=!1;break}}t=s+n.totalSize}if(r){i(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),i(e);const t=mn(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(e instanceof Promise&&(e=await e),e){const t=Xt(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);i instanceof Promise&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})()}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,null===e.sampleTableByteOffset)return t;i(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,"audio"===e.info?.type&&e.info.codec&&Pe.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){i("audio"===e.info?.type);const r=Ne(e.info.codec),a=[],n=[];for(let i=0;i<t.sampleToChunk.length;i++){const o=t.sampleToChunk[i],c=t.sampleToChunk[i+1],l=(c?c.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let i=0;i<l;i++){const c=o.startSampleIndex+i*o.samplesPerChunk,l=c+o.samplesPerChunk,d=x(t.sampleTimingEntries,c,e=>e.startIndex),u=t.sampleTimingEntries[d],h=x(t.sampleTimingEntries,l,e=>e.startIndex),m=t.sampleTimingEntries[h],f=u.startDecodeTimestamp+(c-u.startIndex)*u.delta,p=m.startDecodeTimestamp+(l-m.startIndex)*m.delta-f,g=s(a);g&&g.delta===p?g.count++:a.push({startIndex:o.startChunkIndex+i,startDecodeTimestamp:f,count:1,delta:p});const k=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;n.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=n}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let i=0;i<e.count;i++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+i*e.delta,sampleIndex:e.startIndex+i});for(const e of t.sampleCompositionTimeOffsets)for(let i=0;i<e.count;i++){const r=e.startIndex+i,a=t.presentationTimestamps[r];a&&(a.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),i(t);const r=Xt(t);i("moof"===r?.name);let a=this.reader.requestSlice(e,r.totalSize);a instanceof Promise&&(a=await a),i(a),this.traverseBox(a);const s=this.lastReadFragment;i(s&&s.moofOffset===e);for(const[,i]of s.trackData){const e=i.track,{fragmentPositionCache:t}=e;if(!i.startTimestampIsFinal){const r=e.fragmentLookupTable.find(e=>e.moofOffset===s.moofOffset);if(r)ki(i,r.timestamp);else{const e=x(t,s.moofOffset-1,e=>e.moofOffset);if(-1!==e){const r=t[e];ki(i,r.endTimestamp)}}i.startTimestampIsFinal=!0}const r=x(t,i.startTimestamp,e=>e.startTimestamp);if(-1!==r&&t[r].moofOffset===s.moofOffset||t.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:i.startTimestamp,endTimestamp:i.endTimestamp}),i.encryptionAuxInfo&&e.encryptionInfo){const t=await Ti(this.reader,e.encryptionInfo,i.encryptionAuxInfo);for(let e=0;e<Math.min(i.samples.length,t.length);e++){const r=t[e];i.samples[e].encryption=r}}}return s}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,i=Xt(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=t+i.totalSize}}traverseBox(e){const t=e.filePos,r=Xt(e);if(!r)return!1;const n=e.filePos,o=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":case"wave":this.readContiguousBoxes(e.slice(n,r.contentSize));break;case"mvhd":{const t=on(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=mn(e),this.movieDurationInTimescale=kn(e)):(e.skip(8),this.movieTimescale=mn(e),this.movieDurationInTimescale=mn(e))}break;case"trak":{const t={id:-1,demuxer:this,trackBacking:null,disposition:{...ke,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:"und",sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(n,r.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info&&("video"===t.info.type&&-1!==t.info.width?(t.trackBacking=new ui(t),this.tracks.push(t)):"audio"===t.info.type&&-1!==t.info.numberOfChannels&&(t.trackBacking=new hi(t),this.tracks.push(t))),this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const r=on(e),s=!!(1&dn(e));if(t.disposition.default=s,0===r)e.skip(8),t.id=mn(e),e.skip(4),t.durationInMovieTimescale=mn(e);else{if(1!==r)throw new Error(`Incorrect track header version ${r}.`);e.skip(16),t.id=mn(e),e.skip(4),t.durationInMovieTimescale=kn(e)}e.skip(16);const n=a(O(wi([Gt(e),Gt(e),Qt(e),Gt(e),Gt(e),Qt(e),Gt(e),Gt(e),Qt(e)]),90));i(0===n||90===n||180===n||270===n),t.rotation=n}break;case"elst":{const t=this.currentTrack;if(!t)break;const i=on(e);e.skip(3);let r=!1,a=0;const s=mn(e);for(let n=0;n<s;n++){const s=1===i?kn(e):mn(e),n=1===i?wn(e):pn(e),o=Gt(e);if(0!==s){if(r){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==n){if(1!==o){console.warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=a,t.editListOffset=n,r=!0}else a+=s}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const i=on(e);e.skip(3),0===i?(e.skip(8),t.timescale=mn(e),t.durationInMediaTimescale=mn(e)):1===i&&(e.skip(16),t.timescale=mn(e),t.durationInMediaTimescale=kn(e));let r=ln(e);if(r>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;V(t.languageCode)||(t.languageCode="und")}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Sn(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(n,r.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=on(e);e.skip(3);const r=mn(e);for(let a=0;a<r;a++){const r=e.filePos,a=Xt(e);if(!a)break;t.internalCodecId=a.name;const s=a.name.toLowerCase();if("video"===t.info.type){e.skip(24),t.info.width=ln(e),t.info.height=ln(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const i="encv"===s?t.frmaCodecString:s;t.frmaCodecString=null,"avc1"===i||"avc3"===i?(t.info.codec="avc",t.info.avcType="avc1"===i?1:3):"hvc1"===i||"hev1"===i?t.info.codec="hevc":"vp08"===i?t.info.codec="vp8":"vp09"===i?t.info.codec="vp9":"av01"===i?t.info.codec="av1":null===i?console.warn("Unknown encrypted video codec due to missing frma box."):console.warn(`Unsupported video codec (sample entry type '${a.name}').`)}else{e.skip(8);const n=ln(e);e.skip(6);let o=ln(e),c=ln(e);e.skip(4);let l=mn(e)/65536,d=null;0===i&&n>0&&(1===n?(e.skip(4),c=8*mn(e),e.skip(8)):2===n&&(e.skip(4),l=Tn(e),o=mn(e),e.skip(4),c=mn(e),d=mn(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const u="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===u);else if("opus"===u)t.info.codec="opus",t.info.sampleRate=ze;else if("flac"===u)t.info.codec="flac";else if("ulaw"===u)t.info.codec="ulaw";else if("alaw"===u)t.info.codec="alaw";else if("ac-3"===u)t.info.codec="ac3";else if("ec-3"===u)t.info.codec="eac3";else if("twos"===u)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===u)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===u)t.info.codec="pcm-u8";else if("in24"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===u){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):16===e?t.info.codec="pcm-s16be":24===e?t.info.codec="pcm-s24be":32===e?t.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===u){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===u&&null!==d){const e=c+7>>3,i=Boolean(1&d),r=Boolean(2&d),a=4&d?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=r?"pcm-s16be":"pcm-s16":3===e?t.info.codec=r?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=r?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&console.warn("Unsupported PCM format.")}else null===u?console.warn("Unknown encrypted audio codec due to missing frma box."):console.warn(`Unsupported audio codec (sample entry type '${a.name}').`)}e.filePos=r+a.totalSize}}break;case"frma":{const t=this.currentTrack;if(!t)break;t.frmaCodecString=Sn(e,4).toLowerCase()}break;case"schm":{const t=this.currentTrack;if(!t)break;e.skip(4);const i=Sn(e,4);"cenc"===i||"cens"===i||"cbcs"===i?t.encryptionInfo={scheme:i,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:console.warn(`Unsupported encryption scheme '${i}'.`)}break;case"tenc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=on(e);e.skip(3),e.skip(1);const r=on(e);if(i>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==on(e),t.encryptionInfo.defaultPerSampleIvSize=on(e),t.encryptionInfo.defaultKid=v(nn(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=on(e),r=new Uint8Array(16);r.set(nn(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=nn(e,r.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=nn(e,r.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(4);const r=on(e),a=on(e),s=on(e),n=s>>4,o=s>>1&7,c=1&s,l=on(e),d=on(e),u=on(e);t.info.vp9CodecInfo={profile:r,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:l,transferCharacteristics:d,matrixCoefficients:u}}break;case"av1C":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type),e.skip(1);const r=on(e),a=r>>5,s=31&r,n=on(e),o=n>>7,c=n>>6&1,l=n>>4&1,d=n>>3&1,u=n>>2&1,h=3&n,m=2===a&&c?n>>5&1?12:10:c?10:8;t.info.av1CodecInfo={profile:a,level:s,tier:o,bitDepth:m,monochrome:l,chromaSubsamplingX:d,chromaSubsamplingY:u,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;if(i("video"===t.info?.type),"nclx"!==Sn(e,4))break;const r=ln(e),a=ln(e),s=ln(e),n=Boolean(128&on(e));t.info.colorSpace={primaries:p[r],transfer:k[a],matrix:b[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;i("video"===t.info?.type);const r=mn(e),a=mn(e);r>0&&a>0&&(r>a?t.info.squarePixelWidth=Math.round(t.info.width*r/a):t.info.squarePixelHeight=Math.round(t.info.height*a/r))}break;case"esds":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4),i(3===on(e)),Yt(e),e.skip(2);const r=on(e),a=!!(64&r),s=!!(32&r);if(!!(128&r)&&e.skip(2),a){const t=on(e);e.skip(t)}s&&e.skip(2),i(4===on(e));const n=Yt(e),o=e.filePos,c=on(e);if(64===c||103===c?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===c,objectType:null}):105===c||107===c?t.info.codec="mp3":221===c?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),n>e.filePos-o){i(5===on(e));const r=Yt(e);if(t.info.codecDescription=nn(e,r),"aac"===t.info.codec){const e=Te(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&ln(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=on(e);t.info.pcmLittleEndian=Boolean(1&r),t.info.pcmSampleSize=on(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(1);const r=on(e),a=ln(e),s=mn(e),n=un(e),o=on(e);let c;c=0!==o?nn(e,2+r):new Uint8Array(0);const l=new Uint8Array(19+c.byteLength),d=new DataView(l.buffer);d.setUint32(0,1332770163,!1),d.setUint32(4,1214603620,!1),d.setUint8(8,1),d.setUint8(9,r),d.setUint16(10,a,!0),d.setUint32(12,s,!0),d.setInt16(16,n,!0),d.setUint8(18,o),l.set(c,19),t.info.codecDescription=l,t.info.numberOfChannels=r}break;case"dfLa":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type),e.skip(4);const r=127,a=128,s=e.filePos;for(;e.filePos<o;){const i=on(e),s=dn(e);if((i&r)===Ct.STREAMINFO){e.skip(10);const i=mn(e),r=i>>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(i&a)break}const n=e.filePos;e.filePos=s;const c=nn(e,n-s),l=new Uint8Array(4+c.byteLength);new DataView(l.buffer).setUint32(0,1716281667,!1),l.set(c,4),t.info.codecDescription=l}break;case"dac3":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const r=new we(nn(e,3)),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=Ze[a]),t.info.numberOfChannels=Dt[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;i("audio"===t.info?.type);const a=(e=>{if(e.length<2)return null;const t=new we(e),i=t.readBits(13),r=t.readBits(3),a=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),n=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let c=0;o>0?c=t.readBits(9):t.skipBits(1),a.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:n,numDepSub:o,chanLoc:c})}return 0===a.length?null:{dataRate:i,substreams:a}})(nn(e,r.contentSize));if(!a){console.warn("Invalid dec3 box contents, ignoring.");break}const s=Ut(a);null!==s&&(t.info.sampleRate=s),t.info.numberOfChannels=Wt(a)}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=mn(e);let r=0,a=0;for(let s=0;s<i;s++){const i=mn(e),s=mn(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:a,count:i,delta:s}),r+=i,a+=i*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=mn(e);let r=0;for(let a=0;a<i;a++){const i=mn(e),a=pn(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:i,offset:a}),r+=i}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=mn(e),r=mn(e);if(0===i)for(let a=0;a<r;a++){const i=mn(e);t.sampleTable.sampleSizes.push(i)}else t.sampleTable.sampleSizes.push(i)}break;case"stz2":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),e.skip(3);const i=on(e),r=mn(e),a=new we(nn(e,Math.ceil(r*i/8)));for(let e=0;e<r;e++){const e=a.readBits(i);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];const i=mn(e);for(let r=0;r<i;r++){const i=mn(e)-1;t.sampleTable.keySampleIndices.push(i)}0!==t.sampleTable.keySampleIndices[0]&&t.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=mn(e);for(let a=0;a<i;a++){const i=mn(e)-1,r=mn(e),a=mn(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:i,samplesPerChunk:r,sampleDescriptionIndex:a})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1&&(r+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk)}break;case"stco":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=mn(e);for(let r=0;r<i;r++){const i=mn(e);t.sampleTable.chunkOffsets.push(i)}}break;case"co64":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=mn(e);for(let r=0;r<i;r++){const i=kn(e);t.sampleTable.chunkOffsets.push(i)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,r.contentSize));break;case"mehd":{const t=on(e);e.skip(3);const i=1===t?kn(e):mn(e);this.movieDurationInTimescale=i}break;case"trex":{e.skip(4);const t=mn(e),i=mn(e),r=mn(e),a=mn(e),s=mn(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:i,defaultSampleDuration:r,defaultSampleSize:a,defaultSampleFlags:s})}break;case"tfra":{const t=on(e);e.skip(3);const i=mn(e),r=this.tracks.find(e=>e.id===i);if(!r)break;const a=mn(e),s=(12&a)>>2,n=3&a,o=[on,ln,dn,mn],c=o[(48&a)>>4],l=o[s],d=o[n],u=mn(e);for(let h=0;h<u;h++){const i=1===t?kn(e):mn(e),a=1===t?kn(e):mn(e);c(e),l(e),d(e),r.fragmentLookupTable.push({timestamp:i,moofOffset:a})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){const t=r.fragmentLookupTable[e],i=r.fragmentLookupTable[e+1];t.timestamp===i.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:/* @__PURE__ */new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(n,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(i(this.currentFragment),this.readContiguousBoxes(e.slice(n,r.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){this.currentFragment.implicitBaseDataOffset=e.currentOffset,e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let i=0;i<e.presentationTimestamps.length;i++){const t=e.presentationTimestamps[i],r=e.samples[t.sampleIndex];null===e.firstKeyFrameTimestamp&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),i<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[i+1].presentationTimestamp-t.presentationTimestamp)}const t=e.samples[e.presentationTimestamps[0].sampleIndex],r=e.samples[s(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=r.presentationTimestamp+r.duration;const{currentFragmentState:a}=this.currentTrack;i(a),null!==a.startTimestamp&&(ki(e,a.startTimestamp),e.startTimestampIsFinal=!0),a.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=a.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;const t=$t(nn(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case"tfhd":{i(this.currentFragment),e.skip(1);const t=dn(e),r=Boolean(1&t),a=Boolean(2&t),s=Boolean(8&t),n=Boolean(16&t),o=Boolean(32&t),c=Boolean(65536&t),l=Boolean(131072&t),d=mn(e),u=this.tracks.find(e=>e.id===d);if(!u)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===d);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},r?u.currentFragmentState.baseDataOffset=kn(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(u.currentFragmentState.sampleDescriptionIndex=mn(e)),s&&(u.currentFragmentState.defaultSampleDuration=mn(e)),n&&(u.currentFragmentState.defaultSampleSize=mn(e)),o&&(u.currentFragmentState.defaultSampleFlags=mn(e)),c&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;i(t.currentFragmentState);const r=on(e);e.skip(3);const a=0===r?mn(e):kn(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{const t=this.currentTrack;if(!t)break;i(this.currentFragment),i(t.currentFragmentState);const r=on(e),a=dn(e),s=Boolean(1&a),n=Boolean(4&a),o=Boolean(256&a),c=Boolean(512&a),l=Boolean(1024&a),d=Boolean(2048&a),u=mn(e);let h=null;s&&(h=pn(e));let m,f=null;if(n&&(f=mn(e)),this.currentFragment.trackData.has(t.id)?(m=this.currentFragment.trackData.get(t.id),null!==h&&(m.currentOffset=t.currentFragmentState.baseDataOffset+h)):(m={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(h??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,m)),0===u){this.currentFragment.implicitBaseDataOffset=m.currentOffset;break}for(let p=0;p<u;p++){let a,s,n;o?a=mn(e):(i(null!==t.currentFragmentState.defaultSampleDuration),a=t.currentFragmentState.defaultSampleDuration),c?s=mn(e):(i(null!==t.currentFragmentState.defaultSampleSize),s=t.currentFragmentState.defaultSampleSize),l?n=mn(e):(i(null!==t.currentFragmentState.defaultSampleFlags),n=t.currentFragmentState.defaultSampleFlags),0===p&&null!==f&&(n=f);let u=0;d&&(u=0===r?mn(e):pn(e));const h=!(65536&n);m.samples.push({presentationTimestamp:m.currentTimestamp+u,duration:a,byteOffset:m.currentOffset,byteSize:s,isKeyFrame:h,encryption:null}),m.currentOffset+=s,m.currentTimestamp+=a}}break;case"saiz":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),1&dn(e)){const i=Sn(e,4),r=mn(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const i=on(e),r=mn(e);let a=null;0===i&&r>0&&(a=nn(e,r));const s=yi(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=on(e);if(1&dn(e)){const i=Sn(e,4),r=mn(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=mn(e);if(0===r)break;r>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?mn(e):Number(kn(e));this.currentFragment&&(a+=this.currentFragment.moofOffset),yi(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;i(this.currentFragment);const r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);const a=dn(e),s=Boolean(2&a),n=mn(e),o=t.encryptionInfo.defaultPerSampleIvSize;i(null!==o);for(let i=0;i<Math.min(n,r.samples.length);i++){const a=new Uint8Array(16);o>0?a.set(nn(e,o),0):a.set(t.encryptionInfo.defaultConstantIv,0);let n=null;if(s){const t=ln(e);n=[];for(let i=0;i<t;i++){const t=ln(e),i=mn(e);n.push({clearLen:t,protectedLen:i})}}r.samples[i].encryption={iv:a,subsamples:n}}}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(n,r.contentSize));for(const{boxInfo:e,slice:i}of t){if("meta"!==e.name&&!this.currentTrack){const t=i.filePos;this.metadataTags.raw??={},"©"===e.name[0]?this.metadataTags.raw[e.name]??=Jt(i):this.metadataTags.raw[e.name]??=nn(i,e.contentSize),i.filePos=t}switch(e.name){case"meta":i.skip(-e.headerSize),this.traverseBox(i);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=u.decode(nn(i,e.contentSize)):this.metadataTags.title??=Jt(i);break;case"©des":this.currentTrack||(this.metadataTags.description??=Jt(i));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=Jt(i));break;case"©alb":this.currentTrack||(this.metadataTags.album??=Jt(i));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Jt(i));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=Jt(i));break;case"©day":if(!this.currentTrack){const e=new Date(Jt(i));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=Jt(i));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=Jt(i))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==mn(e);this.currentMetadataKeys=/* @__PURE__ */new Map,t?this.readContiguousBoxes(e.slice(n,r.contentSize)):this.readContiguousBoxes(e.slice(n+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=mn(e);for(let i=0;i<t;i++){const t=mn(e);e.skip(4);const r=u.decode(nn(e,t-8));this.currentMetadataKeys.set(i+1,r)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(n,r.contentSize));for(const{boxInfo:e,slice:i}of t){let t=e.name;const r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));const a=Zt(i);switch(this.metadataTags.raw??={},this.metadataTags.raw[t]??=a,t){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof a&&(this.metadataTags.title??=a);break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof a&&(this.metadataTags.description??=a);break;case"©ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof a&&(this.metadataTags.artist??=a);break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof a&&(this.metadataTags.album??=a);break;case"aART":case"album_artist":"string"==typeof a&&(this.metadataTags.albumArtist??=a);break;case"©cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof a&&(this.metadataTags.comment??=a);break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof a&&(this.metadataTags.genre??=a);break;case"©lyr":case"lyrics":"string"==typeof a&&(this.metadataTags.lyrics??=a);break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof a){const e=new Date(a);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"covr":case"com.apple.quicktime.artwork":a instanceof fe?(this.metadataTags.images??=[],this.metadataTags.images.push({data:a.data,kind:"coverFront",mimeType:a.mimeType})):a instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:a,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof a){const e=a.split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(this.metadataTags.tracksTotal??=i)}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=d(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),i>0&&(this.metadataTags.tracksTotal??=i)}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=d(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),i>0&&(this.metadataTags.discsTotal??=i)}}}}}return e.filePos=o,!0}},di=class{constructor(e){this.internalTrack=e,this.packetToSampleIndex=/* @__PURE__ */new WeakMap,this.packetToFragmentLocation=/* @__PURE__ */new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===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}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;return e.durationInMediaTimescale<=0?null:(i(e.trackBacking),((await e.trackBacking.getFirstPacket({metadataOnly:!0}))?.timestamp??0)+e.durationInMediaTimescale/e.timescale)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return z(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=mi(r,i),s=await this.fetchPacketForSampleIndex(a,t);return bi(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=x(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<t.endTimestamp}},i,i,t):s}async getNextPacket(e,t){const i=this.packetToSampleIndex.get(e);if(void 0!==i)return this.fetchPacketForSampleIndex(i+1,t);const r=this.packetToFragmentLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.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),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=fi(r,i),s=await this.fetchPacketForSampleIndex(a,t);return bi(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=B(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<t.endTimestamp}},i,i,t):s}async getNextKeyPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r){const e=gi(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r);return this.fetchPacketForSampleIndex(e,t)}const a=this.packetToFragmentLocation.get(e);if(void 0===a)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,e=>{if(e===a.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return i(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const r=pi(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!r)return null;let a;if(t.metadataOnly)a=qt;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(t instanceof Promise&&(t=await t),!t)return null;if(a=nn(t,r.sampleSize),this.internalTrack.encryptionAuxInfo){i(this.internalTrack.encryptionInfo);const t=await Ti(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<t.length&&(a=await Si(this.internalTrack,t[e],a,null))}}const s=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=r.duration/this.internalTrack.timescale,o=new Ht(a,r.isKeyFrame?"key":"delta",s,n,e,r.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).samples[t];let s;if(i(a),r.metadataOnly)s=qt;else{let t=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);if(t instanceof Promise&&(t=await t),!t)return null;s=nn(t,a.byteSize),a.encryption&&(s=await Si(this.internalTrack,a.encryption,s,e))}const n=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new Ht(s,a.isKeyFrame?"key":"delta",n,o,e.moofOffset+t,a.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:t}),c}async performFragmentedLookup(e,t,r,a,s){const n=this.internalTrack.demuxer;let o=null,c=null,l=-1;if(e){const{sampleIndex:i,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,i,s);-1!==i&&(c=e,l=i)}const d=x(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),u=-1!==d?this.internalTrack.fragmentLookupTable[d]:null,h=x(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),m=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(u?.moofOffset??0,m?.moofOffset??0)||null;let p;for(e?null===f||e.moofOffset>=f?(p=e.moofOffset+e.moofSize,o=e):p=f:p=f??0;;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=n.reader.requestSliceRange(p,8,16);if(e instanceof Promise&&(e=await e),!e)break;const i=p,r=Xt(e);if(!r)break;if("moof"===r.name){o=await n.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(o);if(r)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,l=e)}p=i+r.totalSize}if(u&&(!c||c.moofOffset<u.moofOffset)){const e=this.internalTrack.fragmentLookupTable[d-1];i(!e||e.timestamp<u.timestamp);const r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,a,s)}return c?this.fetchPacketInFragment(c,l,s):null}},ui=class extends di{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Et(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&xt(e.data)}const e={codec:Fe(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};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}},hi=class extends di{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:De(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},mi=(e,t)=>{if(e.presentationTimestamps){const i=x(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=x(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===i)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},fi=(e,t)=>{if(!e.keySampleIndices)return mi(e,t);if(e.presentationTimestamps){const i=x(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===i)return-1;for(let t=i;t>=0;t--){const i=e.presentationTimestamps[t].sampleIndex;if(-1!==C(e.keySampleIndices,i,e=>e))return i}return-1}{const i=mi(e,t),r=x(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},pi=(e,t)=>{const r=x(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let s=a.startDecodeTimestamp+(t-a.startIndex)*a.delta;const n=x(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndex<o.count&&(s+=o.offset);const c=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],l=x(e.sampleToChunk,t,e=>e.startSampleIndex),d=e.sampleToChunk[l];i(d);const u=d.startChunkIndex+Math.floor((t-d.startSampleIndex)/d.samplesPerChunk),h=e.chunkOffsets[u],m=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk;let f=0,p=h;if(1===e.sampleSizes.length)p+=c*(t-m),f+=c*d.samplesPerChunk;else for(let i=m;i<m+d.samplesPerChunk;i++){const r=e.sampleSizes[i];i<t&&(p+=r),f+=r}let g=a.delta;if(e.presentationTimestamps){const r=e.presentationTimestampIndexMap[t];i(void 0!==r),r<e.presentationTimestamps.length-1&&(g=e.presentationTimestamps[r+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:p,sampleSize:c,chunkOffset:h,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==C(e.keySampleIndices,t,e=>e)}},gi=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=x(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},ki=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const i of e.samples)i.presentationTimestamp+=t;for(const i of e.presentationTimestamps)i.presentationTimestamp+=t},wi=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},bi=e=>0===e.sampleSizes.length,yi=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},Ti=async(e,t,r)=>{if(r.resolved)return r.resolved;if(null===r.offset||0===r.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let a=0;if(r.defaultSampleInfoSize>0)a=r.defaultSampleInfoSize*r.sampleCount;else{i(r.sampleSizes);for(let e=0;e<r.sampleCount;e++)a+=r.sampleSizes[e]}let s=e.requestSlice(r.offset,a);if(s instanceof Promise&&(s=await s),!s)throw new Error("Failed to read auxiliary encryption info.");const n=t.defaultPerSampleIvSize;i(null!==n);const o=[];for(let i=0;i<r.sampleCount;i++){const e=r.defaultSampleInfoSize>0?r.defaultSampleInfoSize:r.sampleSizes[i],a=new Uint8Array(16);n>0?a.set(nn(s,n),0):a.set(t.defaultConstantIv,0);let c=null;if(e>n){const e=ln(s);c=[];for(let t=0;t<e;t++){const e=ln(s),t=mn(s);c.push({clearLen:e,protectedLen:t})}}o.push({iv:a,subsamples:c})}return r.resolved=o,o},Si=async(e,t,r,a)=>{i(e.encryptionInfo);const s=e.encryptionInfo;i(null!==s.defaultKid);const n=s.defaultKid;let o;const c=e.demuxer.decryptionKeyCache.get(n);if(c)o=await c;else{if(!e.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 t=(async()=>{let t=e.demuxer.psshBoxes;if(a){t=[...t,...a.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(n));for(let e=0;e<t.length-1;e++)for(let i=e+1;i<t.length;i++)Kt(t[e],t[i])&&(t.splice(i,1),i--)}const r=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:n,psshBoxes:t});if(!("string"==typeof r&&32===r.length&&S.test(r)||r instanceof Uint8Array&&16===r.byteLength))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return r instanceof Uint8Array?r:(e=>{i(e.length%2==0);const t=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)t[i/2]=parseInt(e.slice(i,i+2),16);return t})(r)})();e.demuxer.decryptionKeyCache.set(n,t),o=await t}return"cenc"===s.scheme||"cens"===s.scheme?vi(o,s,t,r):Pi(o,s,t,r)},vi=async(e,t,r,a)=>{const s=new Uint8Array(16);s.set(r.iv,0);const n=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),o=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,e);return new Uint8Array(t)};if(!r.subsamples)return o(a);i(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const c=Ci(r.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const i of c)for(const e of i.perSubsample)l+=e.length;const d=new Uint8Array(l);let u=0;for(const i of c)for(const e of i.perSubsample)d.set(a.subarray(e.offset,e.offset+e.length),u),u+=e.length;const h=await o(d),m=new Uint8Array(a);let f=0;for(const i of c)for(const e of i.perSubsample)m.set(h.subarray(f,f+e.length),e.offset),f+=e.length;return m},Pi=(e,t,r,a)=>{const s=new ci;s.init({key:e,iv:r.iv});const n=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(i(null!==n&&null!==o),!r.subsamples){const e=new Uint8Array(a),t=Math.floor(a.length/16);for(let i=0;i<t;i++){const t=16*i;s.in.set(a.subarray(t,t+16)),s.decrypt(),e.set(s.out,t)}return e}if(0===n&&0===o)throw new Error("cbcs with subsamples requires pattern encryption.");const c=new Uint8Array(a),l=Ci(r.subsamples,n,o),d=new DataView(r.iv.buffer,r.iv.byteOffset,16);for(const i of l){s.iv[0]=d.getUint32(0,!1),s.iv[1]=d.getUint32(4,!1),s.iv[2]=d.getUint32(8,!1),s.iv[3]=d.getUint32(12,!1);for(const e of i.perSubsample){const t=e.length/16;for(let i=0;i<t;i++){const t=e.offset+16*i;s.in.set(a.subarray(t,t+16)),s.decrypt(),c.set(s.out,t)}}}return c},Ci=(e,t,i)=>{const r=[],a=0!==t||0!==i;let s=0;for(const n of e){s+=n.clearLen;const e=[];if(a){let r=n.protectedLen,a=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:a,length:s}),a+=s,r-=s;const n=Math.min(16*i,r);a+=n,r-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;r.push({perSubsample:e})}return r};!function(e){e[e.EBML=440786851]="EBML",e[e.EBMLVersion=17030]="EBMLVersion",e[e.EBMLReadVersion=17143]="EBMLReadVersion",e[e.EBMLMaxIDLength=17138]="EBMLMaxIDLength",e[e.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",e[e.DocType=17026]="DocType",e[e.DocTypeVersion=17031]="DocTypeVersion",e[e.DocTypeReadVersion=17029]="DocTypeReadVersion",e[e.Void=236]="Void",e[e.Segment=408125543]="Segment",e[e.SeekHead=290298740]="SeekHead",e[e.Seek=19899]="Seek",e[e.SeekID=21419]="SeekID",e[e.SeekPosition=21420]="SeekPosition",e[e.Duration=17545]="Duration",e[e.Info=357149030]="Info",e[e.TimestampScale=2807729]="TimestampScale",e[e.MuxingApp=19840]="MuxingApp",e[e.WritingApp=22337]="WritingApp",e[e.Tracks=374648427]="Tracks",e[e.TrackEntry=174]="TrackEntry",e[e.TrackNumber=215]="TrackNumber",e[e.TrackUID=29637]="TrackUID",e[e.TrackType=131]="TrackType",e[e.FlagEnabled=185]="FlagEnabled",e[e.FlagDefault=136]="FlagDefault",e[e.FlagForced=21930]="FlagForced",e[e.FlagOriginal=21934]="FlagOriginal",e[e.FlagHearingImpaired=21931]="FlagHearingImpaired",e[e.FlagVisualImpaired=21932]="FlagVisualImpaired",e[e.FlagCommentary=21935]="FlagCommentary",e[e.FlagLacing=156]="FlagLacing",e[e.Name=21358]="Name",e[e.Language=2274716]="Language",e[e.LanguageBCP47=2274717]="LanguageBCP47",e[e.CodecID=134]="CodecID",e[e.CodecPrivate=25506]="CodecPrivate",e[e.CodecDelay=22186]="CodecDelay",e[e.SeekPreRoll=22203]="SeekPreRoll",e[e.DefaultDuration=2352003]="DefaultDuration",e[e.Video=224]="Video",e[e.PixelWidth=176]="PixelWidth",e[e.PixelHeight=186]="PixelHeight",e[e.DisplayWidth=21680]="DisplayWidth",e[e.DisplayHeight=21690]="DisplayHeight",e[e.DisplayUnit=21682]="DisplayUnit",e[e.AlphaMode=21440]="AlphaMode",e[e.Audio=225]="Audio",e[e.SamplingFrequency=181]="SamplingFrequency",e[e.Channels=159]="Channels",e[e.BitDepth=25188]="BitDepth",e[e.SimpleBlock=163]="SimpleBlock",e[e.BlockGroup=160]="BlockGroup",e[e.Block=161]="Block",e[e.BlockAdditions=30113]="BlockAdditions",e[e.BlockMore=166]="BlockMore",e[e.BlockAdditional=165]="BlockAdditional",e[e.BlockAddID=238]="BlockAddID",e[e.BlockDuration=155]="BlockDuration",e[e.ReferenceBlock=251]="ReferenceBlock",e[e.Cluster=524531317]="Cluster",e[e.Timestamp=231]="Timestamp",e[e.Cues=475249515]="Cues",e[e.CuePoint=187]="CuePoint",e[e.CueTime=179]="CueTime",e[e.CueTrackPositions=183]="CueTrackPositions",e[e.CueTrack=247]="CueTrack",e[e.CueClusterPosition=241]="CueClusterPosition",e[e.Colour=21936]="Colour",e[e.MatrixCoefficients=21937]="MatrixCoefficients",e[e.TransferCharacteristics=21946]="TransferCharacteristics",e[e.Primaries=21947]="Primaries",e[e.Range=21945]="Range",e[e.Projection=30320]="Projection",e[e.ProjectionType=30321]="ProjectionType",e[e.ProjectionPoseRoll=30325]="ProjectionPoseRoll",e[e.Attachments=423732329]="Attachments",e[e.AttachedFile=24999]="AttachedFile",e[e.FileDescription=18046]="FileDescription",e[e.FileName=18030]="FileName",e[e.FileMediaType=18016]="FileMediaType",e[e.FileData=18012]="FileData",e[e.FileUID=18094]="FileUID",e[e.Chapters=272869232]="Chapters",e[e.Tags=307544935]="Tags",e[e.Tag=29555]="Tag",e[e.Targets=25536]="Targets",e[e.TargetTypeValue=26826]="TargetTypeValue",e[e.TargetType=25546]="TargetType",e[e.TagTrackUID=25541]="TagTrackUID",e[e.TagEditionUID=25545]="TagEditionUID",e[e.TagChapterUID=25540]="TagChapterUID",e[e.TagAttachmentUID=25542]="TagAttachmentUID",e[e.SimpleTag=26568]="SimpleTag",e[e.TagName=17827]="TagName",e[e.TagLanguage=17530]="TagLanguage",e[e.TagString=17543]="TagString",e[e.TagBinary=17541]="TagBinary",e[e.ContentEncodings=28032]="ContentEncodings",e[e.ContentEncoding=25152]="ContentEncoding",e[e.ContentEncodingOrder=20529]="ContentEncodingOrder",e[e.ContentEncodingScope=20530]="ContentEncodingScope",e[e.ContentCompression=20532]="ContentCompression",e[e.ContentCompAlgo=16980]="ContentCompAlgo",e[e.ContentCompSettings=16981]="ContentCompSettings",e[e.ContentEncryption=20533]="ContentEncryption"}(Ft||(Ft={}));var xi,Ii,Ei,_i=[Ft.EBML,Ft.Segment],Bi=[Ft.SeekHead,Ft.Info,Ft.Cluster,Ft.Tracks,Ft.Cues,Ft.Attachments,Ft.Chapters,Ft.Tags],Ai=[..._i,...Bi],Ri=e=>{if(e.remainingLength<1)return null;const t=on(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength<i?null:i},Fi=e=>{if(e.remainingLength<1)return null;const t=on(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength<i-1)return null;let a=t&r-1;for(let s=1;s<i;s++)a*=256,a+=on(e);return a},Mi=(e,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r<t;r++)i*=256,i+=on(e);return i},Di=e=>{const t=Ri(e);return null===t||e.remainingLength<t?null:Mi(e,t)},zi=e=>{if(e.remainingLength<1)return null;if(255===on(e))return;e.skip(-1);const t=Fi(e);return null===t?null:72057594037927940!==t?t:void 0},Oi=e=>{i(e.remainingLength>=2);const t=Di(e);if(null===t)return null;const r=zi(e);return null===r?null:{id:t,size:r}},Ni=(e,t)=>{const i=nn(e,t);let r=0;for(;r<t&&0!==i[r];)r+=1;return String.fromCharCode(...i.subarray(0,r))},Li=(e,t)=>{const i=nn(e,t);let r=0;for(;r<t&&0!==i[r];)r+=1;return u.decode(i.subarray(0,r))},Ui=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?yn(e):Tn(e)},Wi=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||s<r;){let t=e.requestSliceRange(s,2,16);if(t instanceof Promise&&(t=await t),!t)break;const i=Oi(t);if(!i)break;if(a.has(i.id))return{pos:s,found:!0};qi(i.size),s=t.filePos+i.size}return{pos:null!==r&&r>s?r:s,found:!1}},Vi=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;s<r;){let t=e.requestSliceRange(s,0,Math.min(65536,r-s));if(t instanceof Promise&&(t=await t),!t)break;if(t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=s;const e=Di(t);if(null!==e&&a.has(e))return s;s++}}return null};function qi(e){if(void 0===e)throw new Error("Undefined element size is used in a place where it is not supported.")}!function(e){e[e.None=0]="None",e[e.Xiph=1]="Xiph",e[e.FixedSize=2]="FixedSize",e[e.Ebml=3]="Ebml"}(xi||(xi={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(Ii||(Ii={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(Ei||(Ei={}));var Hi=[{id:Ft.SeekHead,flag:"seekHeadSeen"},{id:Ft.Info,flag:"infoSeen"},{id:Ft.Tracks,flag:"tracksSeen"},{id:Ft.Cues,flag:"cuesSeen"}],ji=10485760,$i=class extends Vt{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(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");return e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`),t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&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,2,16);if(t instanceof Promise&&(t=await t),!t)break;const i=Oi(t);if(!i)break;const r=i.id;let a=i.size;const n=t.filePos;if(r===Ft.EBML){qi(a);let e=this.reader.requestSlice(n,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===Ft.Segment){if(await this.readSegment(n,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===Ft.Cluster){if(null===this.reader.fileSize)break;void 0===a&&(a=(await Wi(this.reader,n,Ai,this.reader.fileSize)).pos-n);const e=s(this.segments);e&&(e.elementEndPos=n+a)}qi(a),e=n+a}})()}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:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;null===this.currentSegment.elementEndPos||i<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(i,2,16);if(e instanceof Promise&&(e=await e),!e)break;const t=i,r=Oi(e);if(!r||!Bi.includes(r.id)&&r.id!==Ft.Void){const e=await Vi(this.reader,t,Bi,Math.min(this.currentSegment.elementEndPos??1/0,t+ji));if(e){i=e;continue}break}const{id:a,size:s}=r,n=e.filePos,o=Hi.findIndex(e=>e.id===a);if(-1!==o){const e=Hi[o].flag;this.currentSegment[e]=!0,qi(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===Ft.Tags||a===Ft.Attachments){a===Ft.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,qi(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===Ft.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Hi.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,16);if(i instanceof Promise&&(i=await i),!i)continue;const r=Oi(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;qi(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const n of this.currentSegment.tracks)null!==n.defaultDurationNs&&(n.defaultDuration=this.currentSegment.timestampFactor*n.defaultDurationNs/1e9);const r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const n of this.currentSegment.cuePoints){const e=r.get(n.trackId);e&&e.cuePoints.push(n)}for(const n of this.currentSegment.tracks){n.cuePoints.sort((e,t)=>e.time-t.time);for(let e=0;e<n.cuePoints.length-1;e++){const t=n.cuePoints[e],i=n.cuePoints[e+1];t.time===i.time&&(n.cuePoints.splice(e+1,1),e--)}}let a=null,s=-1/0;for(const n of this.currentSegment.tracks)n.cuePoints.length>s&&(s=n.cuePoints.length,a=n);for(const n of this.currentSegment.tracks)0===n.cuePoints.length&&(n.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,16);r instanceof Promise&&(r=await r),i(r);const a=e,n=Oi(r);i(n),i(n.id===Ft.Cluster);let o=n.size;const c=r.filePos;void 0===o&&(o=(await Wi(this.reader,c,Ai,t.elementEndPos)).pos-c);let l=this.reader.requestSlice(c,o);l instanceof Promise&&(l=await l);const d={segment:t,elementStartPos:a,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:/* @__PURE__ */new Map};this.currentCluster=d,l&&(d.elementEndPos=this.readContiguousElements(l,Ai));for(const[,u]of d.trackData){const e=u.track;i(u.blocks.length>0);let t=!1;for(let i=0;i<u.blocks.length;i++){const e=u.blocks[i];e.timestamp+=d.timestamp,t||=e.lacing!==xi.None}u.presentationTimestamps=u.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let i=0;i<u.presentationTimestamps.length;i++){const t=u.presentationTimestamps[i],r=u.blocks[t.blockIndex];null===u.firstKeyFrameTimestamp&&r.isKeyFrame&&(u.firstKeyFrameTimestamp=r.timestamp),i<u.presentationTimestamps.length-1?r.duration=u.presentationTimestamps[i+1].timestamp-r.timestamp:0===r.duration&&null!=e.defaultDuration&&r.lacing===xi.None&&(r.duration=e.defaultDuration)}t&&(this.expandLacedBlocks(u.blocks,e),u.presentationTimestamps=u.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=u.blocks[u.presentationTimestamps[0].blockIndex],n=u.blocks[s(u.presentationTimestamps).blockIndex];u.startTimestamp=r.timestamp,u.endTimestamp=n.timestamp+n.duration;const o=x(e.clusterPositionCache,u.startTimestamp,e=>e.startTimestamp);-1!==o&&e.clusterPositionCache[o].elementStartPos===a||e.clusterPositionCache.splice(o+1,0,{elementStartPos:d.elementStartPos,startTimestamp:u.startTimestamp})}return t.lastReadCluster=d,d}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){const a=e[r];if(a.lacing===xi.None)continue;a.decoded||(a.data=this.decodeBlockData(t,a.data),a.decoded=!0);const s=an.tempFromBytes(a.data),n=[],o=on(s)+1;switch(a.lacing){case xi.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;s.bufferPos<s.length;){const i=on(s);if(t+=i,i<255){n.push(t),e+=t;break}}}n.push(s.length-(s.bufferPos+e))}break;case xi.FixedSize:{const e=s.length-1,t=Math.floor(e/o);for(let i=0;i<o;i++)n.push(t)}break;case xi.Ebml:{const e=Fi(s);i(null!==e);let t=e;n.push(t);let r=t;for(let a=1;a<o-1;a++){const e=s.bufferPos,a=Fi(s);i(null!==a),t+=a-((1<<7*(s.bufferPos-e)-1)-1),n.push(t),r+=t}n.push(s.length-(s.bufferPos+r))}break;default:i(!1)}i(n.length===o),e.splice(r,1);const c=a.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){const i=n[t],l=nn(s,i),d=a.timestamp+c*t/o,u=c/o;e.splice(r+t,0,{timestamp:d,duration:u,isKeyFrame:a.isKeyFrame,data:l,lacing:xi.None,decoded:!0,mainAdditional:a.mainAdditional})}r+=o,r--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if((t.id!==Ft.Tags||e.tagsSeen)&&(t.id!==Ft.Attachments||e.attachmentsSeen))continue;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;const a=Oi(r);if(!a||a.id!==t.id)continue;const{size:s}=a;qi(s),i(!this.currentSegment),this.currentSegment=e;let n=this.reader.requestSlice(r.filePos,s);n instanceof Promise&&(n=await n),n&&this.readContiguousElements(n),this.currentSegment=null,t.id===Ft.Tags?e.tagsSeen=!0:t.id===Ft.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const r=Oi(e);if(!r)return!1;if(t&&t.includes(r.id))return!1;const{id:s,size:n}=r,o=e.filePos;switch(qi(n),s){case Ft.DocType:this.isWebM="webm"===Ni(e,n);break;case Ft.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(o,n)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Ft.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Mi(e,n)}break;case Ft.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Mi(e,n)}break;case Ft.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Mi(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Ft.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Ui(e,n);break;case Ft.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ke,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(o,n)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Ii.Block||e.data.algorithm!==Ei.HeaderStripping)&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}"V_MPEG4/ISO/AVC"===this.currentTrack.codecId?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"V_MPEGH/ISO/HEVC"===this.currentTrack.codecId?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"V_VP8"===t?this.currentTrack.info.codec="vp8":"V_VP9"===t?this.currentTrack.info.codec="vp9":"V_AV1"===t&&(this.currentTrack.info.codec="av1");const e=this.currentTrack;this.currentTrack.trackBacking=new Xi(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){"A_AAC"===t?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_MPEG/L3"===this.currentTrack.codecId?this.currentTrack.info.codec="mp3":"A_OPUS"===t?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=ze):"A_VORBIS"===t?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_FLAC"===t?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_AC3"===t?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_EAC3"===t?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Gi(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Ft.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Mi(e,n);break;case Ft.TrackType:{if(!this.currentTrack)break;const t=Mi(e,n);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case Ft.FlagEnabled:if(!this.currentTrack)break;Mi(e,n)||(this.currentTrack=null);break;case Ft.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Mi(e,n);break;case Ft.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Mi(e,n);break;case Ft.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Mi(e,n);break;case Ft.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Mi(e,n);break;case Ft.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Mi(e,n);break;case Ft.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Mi(e,n);break;case Ft.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ni(e,n);break;case Ft.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=nn(e,n);break;case Ft.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Mi(e,n);break;case Ft.Name:if(!this.currentTrack)break;this.currentTrack.name=Li(e,n);break;case Ft.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ni(e,n),V(this.currentTrack.languageCode)||(this.currentTrack.languageCode="und");break;case Ft.LanguageBCP47:{if(!this.currentTrack)break;const t=Ni(e,n).split("-")[0];this.currentTrack.languageCode=t||"und",this.currentTrack.hasLanguageBcp47=!0}break;case Ft.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ft.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Mi(e,n);break;case Ft.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Mi(e,n);break;case Ft.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Mi(e,n);break;case Ft.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Mi(e,n);break;case Ft.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Mi(e,n);break;case Ft.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Mi(e,n);break;case Ft.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,n));break;case Ft.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=b[Mi(e,n)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case Ft.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===Mi(e,n);break;case Ft.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=k[Mi(e,n)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case Ft.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=p[Mi(e,n)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case Ft.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ft.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-Ui(e,n);try{this.currentTrack.info.rotation=a(t)}catch{}}break;case Ft.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case Ft.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=Ui(e,n);break;case Ft.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Mi(e,n);break;case Ft.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Mi(e,n);break;case Ft.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case Ft.CueTime:this.currentCueTime=Mi(e,n);break;case Ft.CueTrackPositions:{if(null===this.currentCueTime)break;i(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(o,n)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Ft.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Mi(e,n)}break;case Ft.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;i(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Mi(e,n)}break;case Ft.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Mi(e,n);break;case Ft.SimpleBlock:{if(!this.currentCluster)break;const t=Fi(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=un(e),a=on(e),s=a>>1&3;let c=!!(128&a);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=nn(e,n-(e.filePos-o)),d=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:s,decoded:!d,mainAdditional:null})}break;case Ft.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case Ft.Block:{if(!this.currentCluster)break;const t=Fi(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=un(e),a=on(e)>>1&3,s=nn(e,n-(e.filePos-o)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:a,decoded:!c,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case Ft.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case Ft.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,n)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Ft.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=nn(e,n);break;case Ft.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Mi(e,n);break;case Ft.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Mi(e,n);break;case Ft.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Ft.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case Ft.Targets:this.readContiguousElements(e.slice(o,n));break;case Ft.TargetTypeValue:50!==Mi(e,n)&&(this.currentTagTargetIsMovie=!1);break;case Ft.TagTrackUID:case Ft.TagEditionUID:case Ft.TagChapterUID:case Ft.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Ft.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case Ft.TagName:this.currentSimpleTagName=Li(e,n);break;case Ft.TagString:{if(!this.currentSimpleTagName)break;const t=Li(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Ft.TagBinary:{if(!this.currentSimpleTagName)break;const t=nn(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case Ft.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,n));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new pe(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 e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case Ft.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;r<t;r++)i<<=8n,i+=BigInt(on(e));return i})(e,n);break;case Ft.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=Li(e,n);break;case Ft.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Ni(e,n);break;case Ft.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=nn(e,n);break;case Ft.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=Li(e,n);break;case Ft.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,n)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case Ft.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ii.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Ft.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Mi(e,n);break;case Ft.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Mi(e,n);break;case Ft.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Ei.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case Ft.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Mi(e,n);break;case Ft.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=nn(e,n);break;case Ft.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,t){i(e.decodingInstructions.length>0);let r=t;for(const a of e.decodingInstructions)if(i(a.data),"decompress"===a.data.type&&a.data.algorithm===Ei.HeaderStripping&&a.data.settings&&a.data.settings.length>0){const e=a.data.settings,t=new Uint8Array(e.length+r.length);t.set(e,0),t.set(r,e.length),r=t}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":i.title??=t;break;case"description":i.description??=t;break;case"artist":i.artist??=t;break;case"album":i.album??=t;break;case"album_artist":i.albumArtist??=t;break;case"genre":i.genre??=t;break;case"comment":i.comment??=t;break;case"lyrics":i.lyrics??=t;break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(i.date??=e)}break;case"track_number":case"part_number":{const e=t.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(i.trackNumber??=r),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{const e=t.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(i.discNumber??=r),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}}}},Ki=class{constructor(e){this.internalTrack=e,this.packetToClusterLocation=/* @__PURE__ */new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===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}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor;const i=await this.getFirstPacket({metadataOnly:!0});return t+=i?.timestamp??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return z(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=x(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i<t.endTimestamp}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,e=>{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1<t.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(e.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,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=B(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i<t.endTimestamp}},i,i,t)}async getNextKeyPacket(e,t){const r=this.packetToClusterLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.blocks.findIndex(e=>e.isKeyFrame);return i(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;const a=e.trackData.get(this.internalTrack.id).blocks[t];i(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0);const s=r.metadataOnly?qt:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,c={};a.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(c.alpha=r.metadataOnly?qt:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const l=new Ht(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,a.data.byteLength,c);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,a,s){const{demuxer:n,segment:o}=this.internalTrack;let c=null,l=null,d=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,s);-1!==i&&(l=e,d=i)}const u=x(this.internalTrack.cuePoints,r,e=>e.time),h=-1!==u?this.internalTrack.cuePoints[u]:null,m=x(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),f=-1!==m?this.internalTrack.clusterPositionCache[m]:null,p=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let g;for(e?null===p||e.elementStartPos>=p?(g=e.elementEndPos,c=e):g=p:g=p??o.clusterSeekStartPos;null===o.elementEndPos||g<=o.elementEndPos-2;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=n.reader.requestSliceRange(g,2,16);if(e instanceof Promise&&(e=await e),!e)break;const r=g,u=Oi(e);if(!u||!Bi.includes(u.id)&&u.id!==Ft.Void){const e=await Vi(n.reader,r,Bi,Math.min(o.elementEndPos??1/0,r+ji));if(e){g=e;continue}break}const h=u.id;let m=u.size;const f=e.filePos;if(h===Ft.Cluster){c=await n.readCluster(r,o),m=c.elementEndPos-f;const{blockIndex:e,correctBlockFound:i}=t(c);if(i)return this.fetchPacketInCluster(c,e,s);-1!==e&&(l=c,d=e)}void 0===m&&(i(h!==Ft.Cluster),m=(await Wi(n.reader,f,Ai,o.elementEndPos)).pos-f);const p=f+m;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(p,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(Di(e)===Ft.Segment){o.elementEndPos=p;break}}g=p}if(h&&(!l||l.elementStartPos<h.clusterPosition)){const e=this.internalTrack.cuePoints[u-1];i(!e||e.time<h.time);const r=e?.time??-1/0;return this.performClusterLookup(null,t,r,a,s)}return l?this.fetchPacketInCluster(l,d,s):null}},Xi=class extends Ki{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const t={codec:Fe({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?dt(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?kt(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?xt(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?Et(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})():null}},Gi=class extends Ki{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:De({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}},Qi=async(e,t,i)=>{let r=t;for(;null===i||r<i;){const t=null!==i?Math.min(65536,i-r):65536;let a=e.requestSliceRange(r,4,t);if(a instanceof Promise&&(a=await a),!a||a.length<4)break;for(;a.remainingLength>=4;){const t=a.filePos,i=Ge(mn(a),null!==e.fileSize?e.fileSize-r:null);if(i.header)return{header:i.header,startPos:r};a.filePos=t+i.bytesAdvanced,r=a.filePos}}return null},Yi=class extends Vt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new T,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)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Ji(this)]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=In(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Qi(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Xe(t.mpegVersionId,t.channel);let a=this.reader.requestSlice(e.startPos+i,4);if(a instanceof Promise&&(a=await a),a){const t=mn(a);if(1483304551===t||1231971951===t){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(t instanceof Promise&&(t=await t),t){const e=d(nn(t,12)),i=e.getUint32(0,!1);this.xingData={frameCount:i&r.FrameCount?e.getUint32(4,!1):null,fileSize:i&r.FileSize?e.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const s=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,n={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:s,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(n),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 e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,10);if(i instanceof Promise&&(i=await i),!i)break;const r=In(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(a instanceof Promise&&(a=await a),!a)break;En(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=128){let e=this.reader.requestSlice(this.reader.fileSize-128,128);e instanceof Promise&&(e=await e),i(e),"TAG"===Sn(e,3)&&Cn(e,this.metadataTags)}return this.metadataTags}finally{e()}}},Ji=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(i(null!==e.firstFrameHeader),i(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const i=(t=e.firstFrameHeader.lowSamplingFrequency,r=e.firstFrameHeader.layer,a=e.firstFrameHeader.bitrate,s=e.firstFrameHeader.sampleRate,0===r?0:1===r?144*a/(s<<t):2===r?144*a/s:12*a/s*4),n=(e.reader.fileSize-e.firstFrameHeaderPos)/i;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}var t,r,a,s;return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return"und"}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return i(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...ke}}async getDecoderConfig(){return i(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:3===this.demuxer.firstFrameHeader.channel?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=qt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=nn(e,i.dataSize)}return new Ht(r,"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 i=C(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=x(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},Zi=new Uint32Array(256);for(let ul=0;ul<256;ul++){let e=ul<<24;for(let t=0;t<8;t++)e=2147483648&e?e<<1^79764919:e<<1;Zi[ul]=e>>>0&4294967295}var er,tr=e=>{const t=d(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let a=0;a<e.length;a++){const t=e[a];r=(r<<8^Zi[r>>>24^t])>>>0}return t.setUint32(22,i,!0),r},ir=e=>{const t=e.filePos;if(1399285583!==fn(e))return null;e.skip(1);const i=on(e),r=bn(e),a=fn(e),s=fn(e),n=fn(e),o=on(e),c=new Uint8Array(o);for(let u=0;u<o;u++)c[u]=on(e);const l=27+o,d=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+d,dataStartPos:t+l,dataSize:d,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},rr=(e,t)=>{for(;e.filePos<t-3;){const t=fn(e),i=79;if((255&t)===i||(t>>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),1399285583===t)return!0;e.skip(1)}}return!1},ar=class extends Vt{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,27,282);if(t instanceof Promise&&(t=await t),!t)break;const i=ir(t);if(!i)break;if(!(2&i.headerType))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 e=await this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?await this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&await this.readOpusMetadata(e,t),null!==t.codecInfo.codec&&this.trackBackings.push(new sr(t,this)))}})()}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=await this.findNextPacketStart(r),!i)return;const a=await this.readPacket(i.startPage,i.startSegmentIndex);if(!a)return;if(3!==r.data[0]||5!==a.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const c=d(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&l),1<<(l>>4)],modeBlockflags:At(a.data).modeBlockflags},Mt(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const a=_t(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=ze,t.codecInfo.opusInfo={preSkip:a.preSkip},Mt(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){i(t<e.lacingValues.length);let r=0;for(let i=0;i<t;i++)r+=e.lacingValues[i];let a=e,s=r,n=t;const o=[];e:for(;;){let t=this.reader.requestSlice(a.dataStartPos,a.dataSize);t instanceof Promise&&(t=await t),i(t);const c=nn(t,a.dataSize);for(;;){if(n===a.lacingValues.length){o.push(c.subarray(r,s));break}const e=a.lacingValues[n];if(s+=e,e<255){o.push(c.subarray(r,s));break e}n++}let l=a.headerStartPos+a.totalSize;for(;;){let t=this.reader.requestSliceRange(l,27,282);if(t instanceof Promise&&(t=await t),!t)return null;const i=ir(t);if(!i)return null;if(a=i,a.serialNumber===e.serialNumber)break;l=a.headerStartPos+a.totalSize}r=0,s=0,n=0}const c=o.reduce((e,t)=>e+t.length,0);if(0===c)return null;const l=new Uint8Array(c);let d=0;for(let i=0;i<o.length;i++){const e=o[i];l.set(e,d),d+=e.length}return{data:l,endPage:a,endSegmentIndex:n}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(4&e.endPage.headerType)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(t,27,282);if(i instanceof Promise&&(i=await i),!i)return null;const r=ir(i);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),(e=>{let t="audio/ogg";return e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`),t})({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},sr=class{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=/* @__PURE__ */new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new T,this.internalSampleRate="opus"===e.codecInfo.codec?ze:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return i(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return i(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...ke,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(i(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:a,vorbisBlockSize:s}=((e,t,r)=>{let a=0,s=null;if(e.length>0)if("vorbis"===t.codec){i(t.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=r;const l=t.vorbisInfo.modeBlockflags[o];if(s=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|n),r=e[0]&i?1:0;c=t.vorbisInfo.blocksizes[r]}a=null!==c?c+s>>2:0}else"opus"===t.codec&&(a=(n=e,{durationInSamples:Bt[n[0]>>3]}).durationInSamples);var n;return{durationInSamples:a,vorbisBlockSize:s}})(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),n=new Ht(r.metadataOnly?qt:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,a/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(n,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:a,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:s}),n}async getFirstPacket(e){i(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(i(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,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 r=await this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const a=i.timestampInSamples+i.durationInSamples,s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const r=z(e*this.internalSampleRate);if(0===r)return this.getFirstPacket(t);if(r<0)return null;i(this.bitstream.lastMetadataPacket);const a=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!a)return null;let s=a.startPage,n=this.demuxer.reader.fileSize;const o=[s];e:for(;s.headerStartPos+s.totalSize<n;){const e=s.headerStartPos,t=Math.floor((e+n)/2);let a=t;for(;;){const e=Math.min(a+65307,n-27);let c=this.demuxer.reader.requestSlice(a,e-a);if(c instanceof Promise&&(c=await c),i(c),!rr(c,e)){n=t+27;continue e}let l=this.demuxer.reader.requestSliceRange(c.filePos,27,282);l instanceof Promise&&(l=await l),i(l);const d=ir(l);i(d);let u=!1;if(d.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(d.headerStartPos,d.totalSize);e instanceof Promise&&(e=await e),i(e),u=tr(nn(e,d.totalSize))===d.checksum}if(u)if(u&&d.serialNumber!==this.bitstream.serialNumber)a=d.headerStartPos+d.totalSize;else{if(-1!==d.granulePosition){this.granulePositionToTimestampInSamples(d.granulePosition)>r?n=d.headerStartPos:(s=d,o.push(d));continue e}a=d.headerStartPos+d.totalSize}else a=d.headerStartPos+4}}let c=a.startPage;for(const i of o){if(i.granulePosition===s.granulePosition)break;(!c||i.headerStartPos>c.headerStartPos)&&(c=i)}let l=c;const d=[l];for(;l.serialNumber!==this.bitstream.serialNumber||l.granulePosition!==s.granulePosition;){const e=l.headerStartPos+l.totalSize;let t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),i(t);const r=ir(t);i(r),l=r,l.serialNumber===this.bitstream.serialNumber&&d.push(l)}i(-1!==l.granulePosition);let u,h,m=null,f=l,p=0;if(l.headerStartPos===a.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),h=!0,m=0;else{u=0,h=!1;for(let t=l.lacingValues.length-1;t>=0;t--)if(l.lacingValues[t]<255){m=t+1;break}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");p=m-1;const e={data:qt,endPage:f,endSegmentIndex:p};if(await this.demuxer.findNextPacketStart(e)){const e=or(d,l,m);i(e);const t=nr(d,e.page,e.segmentIndex);t&&(l=t.page,m=t.segmentIndex)}else for(;;){const e=or(d,l,m);if(!e)break;const t=nr(d,e.page,e.segmentIndex);if(!t)break;if(l=t.page,m=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==l;){i(null!==m);const e=await this.demuxer.readPacket(l,m);if(!e)break;if(!(l.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u,vorbisLastBlocksize:k?.vorbisBlockSize??null},t);i(a);let s=this.encodedPacketToMetadata.get(a);if(i(s),h||e.endPage.headerStartPos!==f.headerStartPos||e.endSegmentIndex!==p?u+=s.durationInSamples:(u=this.granulePositionToTimestampInSamples(l.granulePosition),h=!0,a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u-s.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},t),i(a),s=this.encodedPacketToMetadata.get(a),i(s)),g=a,k=s,h&&(Math.max(u,0)>r||Math.max(s.timestampInSamples,0)===r))break}const s=await this.demuxer.findNextPacketStart(e);if(!s)break;l=s.startPage,m=s.startSegmentIndex}return g}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const r=z(e*this.internalSampleRate);e=r/this.internalSampleRate;const a=x(this.sequentialScanCache,r,e=>e.timestampInSamples);let n;if(-1!==a){const e=this.sequentialScanCache[a];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=await this.getFirstPacket(t);let o=0;for(;n&&n.timestamp<e;){const r=await this.getNextPacket(n,t);if(!r||r.timestamp>e)break;if(n=r,o++,100===o){o=0;const e=this.encodedPacketToMetadata.get(n);i(e),this.sequentialScanCache.length>0&&i(s(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},nr=(e,t,r)=>{let a=t,s=r;e:for(;;){for(s--;s>=0;s--)if(a.lacingValues[s]<255){s++;break e}if(i(-1===s),!(1&a.headerType)){s=0;break}const t=_(e,e=>e.headerStartPos<a.headerStartPos);if(!t)return null;a=t,s=a.lacingValues.length}if(i(-1!==s),s===a.lacingValues.length){const t=e[e.indexOf(a)+1];i(t),a=t,s=0}return{page:a,segmentIndex:s}},or=(e,t,i)=>{if(i>0)return{page:t,segmentIndex:i-1};const r=_(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};!function(e){e[e.PCM=1]="PCM",e[e.IEEE_FLOAT=3]="IEEE_FLOAT",e[e.ALAW=6]="ALAW",e[e.MULAW=7]="MULAW",e[e.EXTENSIBLE=65534]="EXTENSIBLE"}(er||(er={}));var cr=class extends Vt{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);e instanceof Promise&&(e=await e),i(e);const t=Sn(e,4),r="RIFX"!==t,a="RF64"===t,s=hn(e,r);let n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==Sn(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,l=e.filePos;for(;null===n||l<n;){let e=this.reader.requestSlice(l,8);if(e instanceof Promise&&(e=await e),!e)break;const t=Sn(e,4),i=hn(e,r),s=e.filePos;if(a&&0===o&&"ds64"!==t)throw new Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===t)await this.parseFmtChunk(s,i,r);else if("data"===t){if(c??=i,this.dataStart=e.filePos,this.dataSize=Math.min(c,(n??1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===t){let e=this.reader.requestSlice(s,i);if(e instanceof Promise&&(e=await e),!e)break;const t=gn(e,r);c=gn(e,r),n=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(s,i,r):"ID3 "!==t&&"id3 "!==t||await this.parseId3Chunk(s,i);l=s+i+(1&i),o++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(-1===this.dataStart)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 dr(this))})()}async parseFmtChunk(e,t,i){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let a=cn(r,i);const s=cn(r,i),n=hn(r,i);r.skip(4);const o=cn(r,i);let c;if(c=14===t?8:cn(r,i),t>=18&&357!==a){const e=cn(r,i),s=t-18;if(Math.min(s,e)>=22&&a===er.EXTENSIBLE){r.skip(6);const e=nn(r,16);a=e[0]|e[1]<<8}}a!==er.MULAW&&a!==er.ALAW||(c=8),this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;const a=Sn(r,4);if("INFO"!==a&&"INF0"!==a)return;let s=r.filePos;for(;s<=e+t-8;){r.filePos=s;const e=Sn(r,4),t=hn(r,i),a=nn(r,t);let n=0;for(let i=0;i<a.length&&0!==a[i];i++)n++;const o=String.fromCharCode(...a.subarray(0,n));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=o,e){case"INAM":case"TITL":this.metadataTags.title??=o;break;case"TIT3":this.metadataTags.description??=o;break;case"IART":this.metadataTags.artist??=o;break;case"IPRD":this.metadataTags.album??=o;break;case"IPRT":case"ITRK":case"TRCK":{const e=o.split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(this.metadataTags.tracksTotal??=i)}break;case"ICRD":case"IDIT":{const e=new Date(o);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"YEAR":{const e=Number.parseInt(o,10);Number.isInteger(e)&&e>0&&(this.metadataTags.date??=new Date(e,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=o;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=o}s+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const r=In(i);if(r){const a=t-10;r.size=Math.min(r.size,a),r.size>0&&En(i.slice(e+10,r.size),r,this.metadataTags)}}getCodec(){if(i(this.audioInfo),this.audioInfo.format===er.MULAW)return"ulaw";if(this.audioInfo.format===er.ALAW)return"alaw";if(this.audioInfo.format===er.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===er.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}},lr=2048,dr=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(i(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...ke}}async getPacketAtIndex(e,t){i(e>=0),i(this.demuxer.audioInfo);const r=e*lr*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const a=Math.min(lr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);if(e instanceof Promise&&(e=await e),!e)return null}let s;if(t.metadataOnly)s=qt;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,a);e instanceof Promise&&(e=await e),i(e),s=nn(e,a)}const n=e*lr/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Ht(s,"key",n,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){i(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/lr,(this.demuxer.dataSize-1)/(lr*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;i(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){const e=await this.getNextPacket(s,t);if(!e)break;s=e}return s}getNextPacket(e,t){i(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/lr);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},ur=e=>{const t=e.filePos,i=new we(nn(e,9));if(4095!==i.readBits(12))return null;if(i.skipBits(1),0!==i.readBits(2))return null;const r=i.readBits(1),a=i.readBits(2)+1,s=i.readBits(4);if(15===s)return null;i.skipBits(1);const n=i.readBits(3);if(0===n)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 o=i.readBits(13);i.skipBits(11);const c=i.readBits(2)+1;if(1!==c)throw new Error("ADTS frames with more than one AAC frame are not supported.");let l=null;return 1===r?e.filePos-=2:l=i.readBits(16),{objectType:a,samplingFrequencyIndex:s,channelConfiguration:n,frameLength:o,numberOfAacFrames:c,crcCheck:l,startPos:t}},hr=1024,mr=class extends Vt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new T,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();i(this.firstFrameHeader),this.trackBackings=[new fr(this)]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,10);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=In(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=ur(e);if(!t)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=t);const r=be[t.samplingFrequencyIndex];i(void 0!==r);const a=hr/r,s={timestamp:this.nextTimestampInSamples/r,duration:a,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(s),this.nextTimestampInSamples+=hr,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 e=0;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;const i=In(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(r instanceof Promise&&(r=await r),!r)break;En(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}},fr=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/hr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return"und"}getCodec(){return"aac"}getInternalCodecId(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){i(this.demuxer.firstFrameHeader);const e=ye[this.demuxer.firstFrameHeader.channelConfiguration];return i(void 0!==e),e}getSampleRate(){i(this.demuxer.firstFrameHeader);const e=be[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return i(void 0!==e),e}getDisposition(){return{...ke}}async getDecoderConfig(){return i(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=qt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=nn(e,i.dataSize)}return new Ht(r,"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 i=C(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=x(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}},pr=class extends Vt{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 T,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),i(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;null===this.reader.fileSize||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,null===t)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);i(t);const r=on(t),a=dn(t),s=!!(128&r);switch(127&r){case Ct.STREAMINFO:{let t=this.reader.requestSlice(e,a);if(t instanceof Promise&&(t=await t),i(t),null===t)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const r=nn(t,34),s=new we(r),n=s.readBits(16),o=s.readBits(16),c=s.readBits(24),l=s.readBits(24),d=s.readBits(20),u=s.readBits(3)+1;s.readBits(5);const h=s.readBits(36);s.skipBits(128);const m=new Uint8Array(42);m.set(new Uint8Array([102,76,97,67]),0),m.set(new Uint8Array([128,0,0,34]),4),m.set(r,8),this.audioInfo={numberOfChannels:u,sampleRate:d,totalSamples:h,minimumBlockSize:n,maximumBlockSize:o,minimumFrameSize:c,maximumFrameSize:l,description:m},this.trackBacking=new gr(this);break}case Ct.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,a);t instanceof Promise&&(t=await t),i(t),Mt(nn(t,a),this.metadataTags);break}case Ct.PICTURE:{let t=this.reader.requestSlice(e,a);t instanceof Promise&&(t=await t),i(t);const r=mn(t),s=mn(t),n=u.decode(nn(t,s)),o=mn(t),c=u.decode(nn(t,o));t.skip(16);const l=mn(t),d=nn(t,l);this.metadataTags.images??=[],this.metadataTags.images.push({data:d,mimeType:n,kind:3===r?"coverFront":4===r?"coverBack":"unknown",description:c});break}}if(e+=a,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){i(this.audioInfo);const r=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,a=this.audioInfo.minimumFrameSize||10,s=(this.audioInfo.maximumFrameSize||r)+16,n=await this.reader.requestSliceRange(e,16,s);if(!n)return null;const o=this.readFlacFrameHeader({slice:n,isFirstPacket:t});if(!o)return null;for(n.filePos=e+a;;){if(n.filePos>n.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n.end-e,isLastFrame:!0};if(255===on(n)){const t=n.filePos;if(on(n)!==(1===this.blockingBit?249:248)){n.filePos=t;continue}n.skip(-2);const i=n.filePos-e,r=this.readFlacFrameHeader({slice:n,isFirstPacket:!1});if(!r){n.filePos=t;continue}if(0===this.blockingBit){if(r.num-o.num!==1){n.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){n.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,a=new we(nn(e,4));if(32764!==a.readBits(15))return null;if(null===this.blockingBit){i(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){if(i(!t),1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");if(i(!t),0!==a.readBits(1))return null}const s=0===(n=a.readBits(4))?null:1===n?192:n>=2&&n<=5?144*2**n:6===n?"uncommon-u8":7===n?"uncommon-u16":n>=8&&n<=15?2**n:null;var n;if(!s)return null;i(this.audioInfo);const o=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(a.readBits(4),this.audioInfo.sampleRate);if(!o)return null;if(a.readBits(4),a.readBits(3),0!==a.readBits(1))return null;const c=(e=>{let t=0;const i=new we(nn(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new we(nn(e,a)),n=8-t-1;for(let o=0;o<n;o++)r.unshift(i.readBits(1));for(let o=0;o<a;o++)for(let e=0;e<8;e++){const t=s.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,i)=>e|t<<i,0)})(e),l=((e,t)=>"uncommon-u16"===t?ln(e)+1:"uncommon-u8"===t?on(e)+1:"number"==typeof t?t:(A(t),void i(!1)))(e,s),d=((e,t)=>"uncommon-u16"===t?ln(e):"uncommon-u16-10"===t?10*ln(e):"uncommon-u8"===t?on(e):"number"==typeof t?t:null)(e,o);if(null===d)return null;if(d!==this.audioInfo.sampleRate)return null;const u=e.filePos-r,h=on(e);return e.skip(-u),e.skip(-1),h!==(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)128&t?t=t<<1^7:t<<=1,t&=255}return t})(nn(e,u))?null:{num:c,blockSize:l,sampleRate:d}}async advanceReader(){await this.readMetadata(),i(null!==this.lastLoadedPos),i(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const r=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(a),t.isLastFrame&&(this.lastSampleLoaded=!0)}},gr=class{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return"und"}getTimeResolution(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ke}}async getDecoderConfig(){return i(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(i(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const i=x(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){await this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i];if(!(r.blockOffset/this.demuxer.audioInfo.sampleRate+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{r()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const r=this.demuxer.loadedSamples[e];if(!r)return null;let a;if(t.metadataOnly)a=qt;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;a=nn(e,r.byteSize)}i(this.demuxer.audioInfo);const s=r.blockOffset/this.demuxer.audioInfo.sampleRate,n=r.blockSize/this.demuxer.audioInfo.sampleRate;return new Ht(a,"key",s,n,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}},kr=9e4,wr="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.",br=/* @__PURE__ */new Set,yr=class extends Vt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),i(e);const t=nn(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=188;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let r=this.packetOffset,a=null,s=!1,n=!1;for(;;){const e=await this.readPacketHeader(r);if(!e)break;if(0===e.payloadUnitStartIndicator){r+=this.packetStride;continue}const t=await this.readSection(r,!0,!n);if(!t)break;const o=3,c=32;let l=!1;if(!n&&0!==t.pid&&(0!==t.payload[0]||0!==t.payload[1]||1!==t.payload[2])){const e=new we(t.payload),i=e.readAlignedByte();e.skipBits(8*i),l=2===e.readBits(8)}if(0!==t.pid||s)if(t.pid!==a&&!l||n){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const r=Sr(t,!0);if(!r)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(await this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const a=new Ir(e,r);if("video"===e.info.type){for(;;){if(a.suppliedPacket=null,await a.markNextPacket(),"avc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=dt(a.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];i(t);const r=ht(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;const s=r.pixelAspectRatio.num,n=r.pixelAspectRatio.den;s>0&&n>0&&(s>n?(e.info.squarePixelWidth=Math.round(e.info.width*s/n),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n/s))),e.info.colorSpace={primaries:p[r.colourPrimaries],transfer:k[r.transferCharacteristics],matrix:b[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!a.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=kt(a.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Je.SPS_NUT).nalUnits[0];i(t);const r=gt(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:p[r.colourPrimaries],transfer:k[r.transferCharacteristics],matrix:b[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:Fe({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await a.markNextPacket(),!a.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=ur(an.tempFromBytes(a.suppliedPacket.data));if(!t)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=ye[t.channelConfiguration],e.info.sampleRate=be[t.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Ge(mn(an.tempFromBytes(a.suppliedPacket.data)),a.suppliedPacket.data.byteLength);if(!t.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=3===t.header.channel?1:2,e.info.sampleRate=t.header.sampleRate}else if("ac3"===e.info.codec){const t=zt(a.suppliedPacket.data);if(!t)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(3===t.fscod)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Dt[t.acmod]+t.lfeon,e.info.sampleRate=Ze[t.fscod]}else{if("eac3"!==e.info.codec)throw new Error("Unhandled.");{const t=Lt(a.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Ut(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Wt(t),e.info.sampleRate=i}}e.info.decoderConfig={codec:De({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new we(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const a=e.readBits(10);for(e.skipBits(8*a);8*(r+o)-e.pos>c;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),a=e.pos+8*r;let s=!1,n=!1;for(;e.pos<a;){const t=e.readBits(8),i=e.readBits(8);106===t?s=!0:122!==t&&204!==t||(n=!0),e.skipBits(8*i)}let o=null;switch(t){case 27:case 36:o={type:"video",codec:27===t?"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:{let e;if(3===t||4===t)e="mp3";else if(15===t)e="aac";else if(129===t)e="ac3";else{if(135!==t)throw new Error("Unreachable.");e="eac3"}o={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:n?o={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:s&&(o={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:br.has(t)||(console.warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),br.add(t))}o&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:o,referencePesPackets:[]})}n=!0}else{const e=new we(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const r=e.readBits(10);for(e.skipBits(40);8*(r+o)-e.pos>c;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==a)throw new Error("Only files with a single program are supported.");a=i}}if(null===a)throw new Error("Program Association Table must link to a Program Map Table.");s=!0}if(n&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!n){if(!s)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const i of this.elementaryStreams)"video"===i.info.type?this.trackBackingEntries.push(new Pr(i)):this.trackBackingEntries.push(new Cr(i))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,d=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),u=!!(1&e.adaptationFieldControl);let h=0;if(n&&(h=1+e.body[0],e===c&&h>1&&(d=e.body[1]>>6&1)),u&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=a,!t&&o>=64){l=!1;break}if(-1!==C(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=x(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!c)return null;if(1===s.length)n=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);n=new Uint8Array(e);let t=0;for(const i of s)n.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:c.pid,payload:n,randomAccessIndicator:d}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(71!==on(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=ln(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:on(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;const i=nn(t,188);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}},Tr=(e,t)=>{if(e.payload.byteLength<3)return null;const i=new we(e.payload);if(1!==i.readBits(24))return null;const r=i.readBits(8);if(i.skipBits(16),188===r||190===r||191===r||240===r||241===r||255===r||242===r||248===r)return null;i.skipBits(8);const a=i.readBits(2);i.skipBits(14);let s=null;if(2===a||3===a)s=0,i.skipBits(4),s+=i.readBits(3)*(1<<30),i.skipBits(1),s+=32768*i.readBits(15),i.skipBits(1),s+=i.readBits(15);else if(t)throw new Error(wr);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},Sr=(e,t)=>{i(null!==e.endPos);const r=Tr(e,t);if(!r)return null;const a=new we(e.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const n=a.readBits(8),o=a.pos+8*n;a.pos=o;const c=o/8;i(Number.isInteger(c));const l=e.payload.subarray(c,s>0?6+s:e.payload.byteLength);return{...r,data:l}},vr=class e{constructor(e){this.elementaryStream=e,this.packetBuffers=/* @__PURE__ */new WeakMap,this.packetSectionStarts=/* @__PURE__ */new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const t=this.elementaryStream.demuxer,r=this.elementaryStream.info.type;let a=0;for(const s of t.trackBackingEntries)if(s.getType()===r&&a++,i(s instanceof e),s.elementaryStream===this.elementaryStream)break;return a}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...ke,primary:!1}}getTimeResolution(){return kr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Ht(i.metadataOnly?qt:e.data,r,e.pts/kr,Math.max(t/kr,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;i(t);const r=Sr(t,!0);i(r);const a=new Ir(this.elementaryStream,r),s=new Er(this,a),n=await s.readNext();if(!n)return null;const o=this.createEncodedPacket(n.packet,n.duration,e);return this.packetBuffers.set(o,s),this.packetSectionStarts.set(o,n.packet.sectionStartPos),o}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){const i=await r.readNext();if(!i)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(i.packet,i.duration,t);return this.packetBuffers.set(a,r),this.packetSectionStarts.set(a,i.packet.sectionStartPos),a}const a=this.packetSectionStarts.get(e);if(void 0===a)throw new Error("Packet was not created from this track.");const s=await this.elementaryStream.demuxer.readSection(a,!0);i(s);const n=Sr(s,!0);i(n);const o=new Ir(this.elementaryStream,n);r=new Er(this,o);const c=e.sequenceNumber;for(;;){const e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){const i=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,e.packet.sectionStartPos),i}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,r){const a=z(e*kr),n=this.elementaryStream.demuxer,{reader:o,seekChunkSize:c}=n,l=this.elementaryStream.pid,d=async(e,t,i)=>{let r=e;for(;r<t;){const e=await n.readPacketHeader(r);if(!e)return null;if(e.pid===l&&1===e.payloadUnitStartIndicator){const e=await n.readSection(r,i);if(!e)return null;const t=Tr(e,!1);if(t&&null!==t.pts)return{pesPacketHeader:t,section:e}}r+=n.packetStride}return null},u=this.elementaryStream.firstSection;i(u);const h=Tr(u,!0);if(i(h),a<h.pts)return null;let m;const f=this.elementaryStream.referencePesPackets,p=x(f,a,e=>e.pts),g=-1!==p?f[p]:null;if(g&&a-g.pts<45e3)m=g.sectionStartPos;else{let e=0;if(null!==o.fileSize){const t=Math.ceil(o.fileSize/c);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),s=L(t*c,n.packetStride)+h.sectionStartPos,o=await d(s,s+c,!1);o&&o.pesPacketHeader.pts<=a?(e=t,i=t+1):r=t-1}}}m=L(e*c,n.packetStride)+h.sectionStartPos}let k=(await d(m,o.fileSize??1/0,!1))?.pesPacketHeader??null;k||(k=h);const w=this.getReorderSize(),b=async(e,t)=>{const o=await n.readSection(e,!0);i(o);const c=Sr(o,!0);i(c);const l=new Ir(this.elementaryStream,c),d=new Er(this,l);for(;!((s(d.presentationOrderPackets)?.pts??-1/0)>=a)&&await d.readNextPacket(););const u=B(d.presentationOrderPackets,t);if(-1===u)return null;const h=d.presentationOrderPackets[u],m=0===u?0:h.pts-d.presentationOrderPackets[u-1].pts;for(;d.decodeOrderPackets[0]!==h;)d.decodeOrderPackets.shift();d.lastDuration=m;const f=await d.readNext();i(f);const p=this.createEncodedPacket(f.packet,f.duration,r);return this.packetBuffers.set(p,d),this.packetSectionStarts.set(p,f.packet.sectionStartPos),p};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=k.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Tr(t,!1);if(e&&null!==e.pts){if(e.pts>a)break e;k=e,xr(this.elementaryStream,k);break}}}e+=n.packetStride}}e:for(let e=0;e<w+1;e++){let e=k.sectionStartPos-n.packetStride;for(;e>=n.packetOffset;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,!1);if(t){const e=Tr(t,!1);if(e&&null!==e.pts){k=e;break}}}e-=n.packetStride}}return b(k.sectionStartPos,e=>e.pts<=a)}{let e=m,t=null;const r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let s=null;const m=e<=h.sectionStartPos;let f,p=null;if(m)f=h,p=u;else{const t=await d(e,o.fileSize??1/0,r);f=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;e:for(;f&&!(null!==t&&f.sectionStartPos>=t);){if(f.pts<=a){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===f.randomAccessIndicator;else{i(p);const t=Sr(p,!0);i(t);const r=new Ir(this.elementaryStream,t);await r.markNextPacket(),e=1===r.suppliedPacket?.randomAccessIndicator}e&&(s=f)}if(f.pts>a&&(g=!0),g&&(k++,k>w))break;let e=f.sectionStartPos+n.packetStride;for(;;){const t=await n.readPacketHeader(e);if(!t)break e;if(t.pid===l&&1===t.payloadUnitStartIndicator){const t=await n.readSection(e,r);if(t){const e=Tr(t,!1);if(e&&null!==e.pts){f=e,p=t,xr(this.elementaryStream,f);break}}}e+=n.packetStride}}if(s){let e=s;if(0===k)e:for(let i=0;i<w;i++){let t=e.sectionStartPos-n.packetStride;for(;t>=n.packetOffset;){const i=await n.readPacketHeader(t);if(!i)break e;if(i.pid===l&&1===i.payloadUnitStartIndicator){const i=await n.readSection(t,r);if(i){const t=Tr(i,!1);if(t&&null!==t.pts){e=t;break}}}t-=n.packetStride}}const t=await b(e.sectionStartPos,e=>e.pts<=a&&1===e.randomAccessIndicator);return i(t),t}if(m)return null;t=e,e=Math.max(L(e-h.sectionStartPos-c,n.packetStride)+h.sectionStartPos,h.sectionStartPos)}}}},Pr=class extends vr{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}},Cr=class extends vr{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}},xr=(e,t)=>{const i=e.referencePesPackets,r=x(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const a=i[r];if(t.pts<=a.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos<s)return!1;if(r<i.length-1){const e=i[r+1];if(e.pts<t.pts)return!1;if(e.sectionStartPos-t.sectionStartPos<s)return!1}}return i.splice(r+1,0,t),!0},Ir=class{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 i(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let e;if(0===this.pesPackets.length)e=this.startingPesPacket;else{let t=s(this.pesPackets).sectionEndPos;for(i(null!==t);;){const i=await this.demuxer.readPacketHeader(t);if(!i)return;if(i.pid===this.pid){const i=await this.demuxer.readSection(t,!0);if(!i)return;const r=Sr(i,!1);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,r=i+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(i,r);const a=new Uint8Array(e);a.set(t.data.subarray(i));let s=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();const t=this.getCurrentPesPacket(),i=e-s;if(i<=t.data.byteLength){a.set(t.data.subarray(0,i),s);break}a.set(t.data,s),s+=t.data.byteLength}return a}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 e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){const t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)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(){i(!this.suppliedPacket);const e=this.elementaryStream;if("video"===e.info.type){const t=e.info.codec,i=1024;if("avc"!==t&&"hevc"!==t)throw new Error("Unhandled.");let r=null;for(;;){let e=this.ensureBuffered(i);if(e instanceof Promise&&(e=await e),0===e)break;const a=this.currentPos,s=this.readBytes(e),n=s.byteLength;let o=0;for(;o<n;){const e=s.indexOf(0,o);if(-1===e||e>=n)break;o=e;const i=a+o;if(o+4>=n){this.seekTo(i);break}const c=s[o+1],l=s[o+2],d=s[o+3];let u=0,h=null;if(0===c&&0===l&&1===d?(u=4,h=s[o+4]):0===c&&1===l&&(u=3,h=d),0===u){o++;continue}const m=i;if(null!==r){if(null!==h){const e="avc"===t?st(h):pt(h);if("avc"===t?e===Ye.AUD:e===Je.AUD_NUT){const e=m-r;return this.seekTo(r),this.supplyPacket(e,0)}}o+=u}else r=m,o+=u}if(e<i)break}if(null!==r){const e=this.endPos-r;return this.seekTo(r),this.supplyPacket(e,0)}}else{const t=e.info.codec,r=128;for(;;){let a=this.ensureBuffered(r);a instanceof Promise&&(a=await a);const s=this.currentPos;for(;this.currentPos-s<a;){const r=this.readU8();if("aac"===t){if(255!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(9);if(i instanceof Promise&&(i=await i),i<9)return;const a=this.readBytes(9),s=ur(an.tempFromBytes(a));if(s){this.seekTo(t);let i=this.ensureBuffered(s.frameLength);return i instanceof Promise&&(i=await i),this.supplyPacket(i,Math.round(9216e4/e.info.sampleRate))}this.seekTo(t+1)}else{if("mp3"!==t){if("ac3"===t){if(11!==r)continue;this.skip(-1);const t=this.currentPos;let a=this.ensureBuffered(5);if(a instanceof Promise&&(a=await a),a<5)return;const s=this.readBytes(5);if(11!==s[0]||119!==s[1]){this.seekTo(t+1);continue}const n=s[4]>>6,o=63&s[4];if(3===n||o>37){this.seekTo(t+1);continue}const c=Ot[3*o+n];i(void 0!==c),this.seekTo(t),a=this.ensureBuffered(c),a instanceof Promise&&(a=await a);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(a,l)}if("eac3"===t){if(11!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;const a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}const s=2*(1+((7&a[2])<<8|a[3])),n=Nt[a[4]>>6==3?3:a[4]>>4&3];this.seekTo(t),i=this.ensureBuffered(s),i instanceof Promise&&(i=await i);const o=256*n,c=Math.round(o*kr/e.info.sampleRate);return this.supplyPacket(i,c)}throw new Error("Unhandled.")}{if(255!==r)continue;this.skip(-1);const t=this.currentPos;let i=this.ensureBuffered(4);if(i instanceof Promise&&(i=await i),i<4)return;const a=Ge(d(this.readBytes(4)).getUint32(0),null);if(a.header){this.seekTo(t);let i=this.ensureBuffered(a.header.totalSize);i instanceof Promise&&(i=await i);const r=a.header.audioSamplesInFrame*kr/e.info.sampleRate;return this.supplyPacket(i,Math.round(r))}this.seekTo(t+1)}}}if(a<r)break}}}supplyPacket(e,t){const r=this.getCurrentPesPacket();let a;if(this.lastSuppliedPesPacket===r)i(null!==this.nextPts),a=this.nextPts;else{if(null===r.pts)throw new Error(wr);a=r.pts,xr(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=a+t;const s=r.sectionStartPos,n=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=r.randomAccessIndicator;if(0===c&&!this.elementaryStream.canBeTrustedWithKeyPackets)if("audio"===this.elementaryStream.info.type)c=1;else if(this.elementaryStream.info.decoderConfig){const e="key"===Rt(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o);c=Number(e)}this.suppliedPacket={pts:a,data:o,sequenceNumber:n,sectionStartPos:s,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}},Er=class{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(),i(this.reorderSize>=0)}async readNext(){if(0===this.decodeOrderPackets.length&&!(await this.readNextPacket()))return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let r;for(i(-1!==t),t===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return 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(i(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(await this.readNextPacket()))break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[e].pts&&(e=i);const t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}},_r="application/vnd.apple.mpegurl",Br=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT"),Ar=class{constructor(e){this._attributes={};let t="",i="",r=!1,a=!1;for(let s=0;s<e.length;s++){const n=e[s];'"'===n?a=!a:"="!==n||r||a?","!==n||a?r?i+=n:t+=n:(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",r=!1):r=!0}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(null===t)return null;const i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}},Rr=class{constructor(e,t,i){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=/* @__PURE__ */new WeakMap,this.firstTimestampCache=/* @__PURE__ */new WeakMap,this.input=e,this.path=t,this.trackDeclarations=i}async getDurationFromMetadata(e){const t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=ne(e,e=>"video"===e.getType())+1;e.push(new Mr(this,t,i))}else if("audio"===t.type){const i=ne(e,e=>"audio"===e.getType())+1;e.push(new Dr(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const t=await this.getInputForSegment(this.firstSegment).getTracks();for(const i of t)if("video"===i.type){const t=ne(e,e=>"video"===e.getType())+1;e.push(new Mr(this,{id:e.length+1,type:"video"},t))}else if("audio"===i.type){const t=ne(e,e=>"audio"===e.getType())+1;e.push(new Dr(this,{id:e.length+1,type:"audio"},t))}}return e})()}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let r;if(this.firstSegmentFirstTimestamps.has(i))r=this.firstSegmentFirstTimestamps.get(i);else{const e=this.getInputForSegment(i);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(i,r)}if(i===e)return i.timestamp-r;const a=await this.getFirstTimestampForInput(t),s=e.timestamp-i.timestamp,n=a-r-s;return Math.abs(n)<=Math.min(.25,s)?i.timestamp-r:e.timestamp-a}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}},Fr=class{constructor(e,t,i){this.packetInfos=/* @__PURE__ */new WeakMap,this.hydrationPromise=null,this.firstInputTrack=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.");const e=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!e)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=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(),i(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,r){i(e.sequenceNumber>=0),i(this.segmentedInput.firstSegment);const a=await this.segmentedInput.getMediaOffset(t,r.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,n=e.clone({timestamp:N(e.timestamp+a,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(n,{segment:t,track:r,sourcePacket:e}),n}async getFirstPacket(e){await this.hydrate(),i(this.segmentedInput.firstSegment),i(this.firstInputTrack);const t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):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 r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const a=i?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(a)return this.createAdjustedPacket(a,r.segment,r.track);let s=r.segment;for(;;){const e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=(await this.segmentedInput.getInputForSegment(e).getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!i){s=e;continue}const a=await i._backing.getFirstPacket(t);return a?this.createAdjustedPacket(a,e,i):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 r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){const a=this.segmentedInput.getInputForSegment(r),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const n=e-await this.segmentedInput.getMediaOffset(r,a),o=i?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(o)return this.createAdjustedPacket(o,r,s);r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null}},Mr=class extends Fr{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}},Dr=class extends Fr{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())}};/* @__PURE__ */t((e,t)=>{t.exports={}})(),re();var zr=1/0,Or=class extends ue{constructor(){super(...arguments),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new tn;return this._sizePromise??=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,zr),e=this._getFileSize(),i(void 0!==e)),e})()}async getSize(){if(this._disposed)throw new tn;const e=await this.getSizeOrNull();if(null===e)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(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new $r(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Nr(this)}},Nr=class{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._refCount++,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;i(e._refCount>0),e._refCount--,0===e._refCount&&(e._dispose(),e._disposed=!0),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}},Lr=class extends Or{constructor(e,t){if("string"!=typeof e)throw new TypeError("rootPath must be a string.");if("function"!=typeof t)throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=e=>{if(!(e instanceof Or||e instanceof Nr))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const t=e instanceof Or?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(i):i(t)}},Ur=(e,t)=>e.path===t.path,Wr=class extends Lr{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,a){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof Or?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),i(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,r,a))}return this._root.source._read(e,t,r,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}},Vr=class extends Or{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ae(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!=typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=/* @__PURE__ */new WeakMap,this._blob=e,this._options=t,this._orchestrator=new jr({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Hr.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){i(e.strictTarget);let t=this._readers.get(e);void 0===t&&(t="stream"in this._blob&&!$()&&!1!==this._options.useStreamReader?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,t));for(;e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:i,value:r}=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+r.length),this._orchestrator.supplyWorkerData(e,r)}else{const t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await(t?.cancel())}_dispose(){this._orchestrator.dispose()}},qr=class extends Or{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ae(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._stream=e,this._maxCacheSize=t.maxCacheSize??33554432}_getFileSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=x(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let a=e;const s=new Uint8Array(t-e);if(-1!==i)for(let l=i;l<this._cache.length;l++){const i=this._cache[l];if(i.start>=t)break;const r=Math.max(e,i.start);r>a&&this._throwDueToCacheMiss();const n=Math.min(t,i.end);r<n&&(s.set(i.bytes.subarray(r-i.start,n-i.start),r-e),a=n)}if(a===t)return{bytes:s,view:d(s),offset:e};this._currentIndex>a&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:c}=E();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,!(this._pendingSlices.length>0))throw e;this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0})),n}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}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 e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const i=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(i,r);for(let a=0;a<this._pendingSlices.length;a++){const e=this._pendingSlices[a],s=Math.max(i,e.start),n=Math.min(r,e.end);s<n&&(e.bytes.set(t.subarray(s-i,n-i),s-e.start),n===e.end&&(e.resolve({bytes:e.bytes,view:d(e.bytes),offset:e.start}),this._pendingSlices.splice(a,1),a--))}for(this._cache.push({start:i,end:r,bytes:t,view:d(t),age:0});this._cache.length>0;){const e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}},Hr={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(ee(e,t,r,a.targetPos)){const e=a.targetPos-a.startPos,r=Math.ceil((e+1)/i)*i,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,r);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+524288)}}},jr=class{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,r,a){i(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),n=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,a);i(n<=e&&t<=o);let c=null;const l=x(this.cache,e,e=>e.start),u=-1!==l?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 h=x(this.cache,n,e=>e.start),m=c?null:new Uint8Array(t-e);let f=0,p=n;const g=[];if(-1!==h){for(let r=h;r<this.cache.length;r++){const a=this.cache[r];if(a.start>=o)break;if(a.end<=n)continue;const s=Math.max(n,a.start),c=Math.min(o,a.end);if(i(s<=c),p<s&&g.push({start:p,end:s}),p=c,m){const i=Math.max(e,a.start),r=Math.min(t,a.end);if(i<r){const t=i-e;m.set(a.bytes.subarray(i-a.start,r-a.start),t),t===f&&(f=r-e)}}a.age=this.nextAge++}p<o&&g.push({start:p,end:o})}else g.push({start:n,end:o});if(m&&f>=m.length&&(c={bytes:m,view:d(m),offset:e}),0===g.length)return i(c),c;const{promise:k,resolve:w,reject:b}=E(),y=[];for(const i of g){const r=Math.max(e,i.start),a=Math.min(t,i.end);r===i.start&&a===i.end?y.push(i):r<a&&y.push({start:r,end:a})}const T=m&&{start:e,bytes:m,holes:y,resolve:w,reject:b};e:for(const i of g){for(const r of this.workers)if(this.checkHoleAgainstWorker(r,i,T?[T]:[])){this.checkQueuedReadsAgainstWorker(r);continue e}const e=i.end<o||null!==this.fileSize,t=this.createWorker(i.start,i.end,e);if(t)T&&(t.pendingSlices=[T]),this.runWorker(t);else{let t=x(this.queuedReads,i.start,e=>e.hole.start),r=-1!==t?this.queuedReads[t]:null;for(r&&i.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,i.end),r.strictTarget&&=e,T&&r.pendingSlices.push(T)):(t++,r={hole:{start:i.start,end:i.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,r));t+1<this.queuedReads.length;){const e=this.queuedReads[t+1];if(e.hole.start>r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&=e.strictTarget,r.age=Math.min(r.age,e.age),this.queuedReads.splice(t+1,1)}}}return c||(i(m),c=k.then(t=>t&&{bytes:t,view:d(t),offset:e})),c}checkHoleAgainstWorker(e,t,i){if(ee(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t<i.length;t++){const r=i[t];e.pendingSlices.includes(r)||e.pendingSlices.push(r)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){const r=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,r.hole,r.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,r){if(this.workers.length>=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i<this.workers.length;i++){const r=this.workers[i];r.running||0!==r.pendingSlices.length||e&&!(r.age<e.age)||(t=i,e=r)}if(!e)return null;i(null!==t),i(0===e.pendingSlices.length),this.workers.splice(t,1)}const a={startPos:e,currentPos:e,targetPos:t,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(a),a}runWorker(e){i(!e.running),i(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))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let i=1;i<this.queuedReads.length;i++)this.queuedReads[i].age<this.queuedReads[e].age&&(e=i);const t=this.queuedReads[e];this.queuedReads.splice(e,1);const r=this.createWorker(t.hole.start,t.hole.end,t.strictTarget);i(r),r.pendingSlices=t.pendingSlices,this.runWorker(r)}})}consolidateEverythingIntoOneWorker(e){const t=new Set(e.pendingSlices);for(let i=0;i<this.workers.length;i++){const r=this.workers[i];if(r!==e){for(const e of r.pendingSlices)t.add(e);r.aborted=!0,r.pendingSlices.length=0,this.workers.splice(i,1),i--}}for(let i=0;i<this.queuedReads.length;i++){const e=this.queuedReads[i];for(const i of e.pendingSlices)t.add(i)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){i(!e.aborted);const r=e.currentPos,a=r+t.length;this.insertIntoCache({start:r,end:a,bytes:t,view:d(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let i=0;i<e.pendingSlices.length;i++){const s=e.pendingSlices[i],n=Math.max(r,s.start),o=Math.min(a,s.start+s.bytes.length);n<o&&s.bytes.set(t.subarray(n-r,o-r),n-s.start);for(let e=0;e<s.holes.length;e++){const t=s.holes[e];r<=t.start&&a>t.start&&(t.start=a),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let i=0;i<this.workers.length;i++){const t=this.workers[i];e===t||t.running||ee(r,a,t.currentPos,t.targetPos)&&(this.workers.splice(i,1),i--)}}supplyFileSize(e){i(null===this.fileSize),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 r=t.pendingSlices[i];for(const a of r.holes)if(a.end>e){r.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 e of i.pendingSlices)e.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let t=0;t<i.pendingSlices.length;t++){const r=i.pendingSlices[t];r.start>=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);i(-1!==t),e.running=!1,this.workers.splice(t,1),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=x(this.cache,e.start,e=>e.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const r=new Uint8Array(e.end-i.start);r.set(i.bytes,0),r.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=r,i.view=d(r),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 t=this.cache[i];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(i,1),this.currentCacheSize-=t.bytes.length,i--;continue}const r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=d(r),e.end=t.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let i=1;i<this.cache.length;i++){const r=this.cache[i];r.age<t.age&&(e=i,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}},$r=class extends Or{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 void 0===e?null!==this._length?this._length:void 0:null===e?null!==this._length?this._length:null:D(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r);return a instanceof Promise?a.then(e=>e?(e.offset-=this._offset,e):null):a?(a.offset-=this._offset,a):null}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}},Kr=function(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},Xr=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r}),Gr=/^0[xX][0-9a-fA-F]+$/,Qr=/^data:.*;base64,/i,Yr=class extends Rr{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{const t=this.getRemainingWaitTimeMs();t>0&&await(e=t,new Promise(t=>setTimeout(t,e))),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}var e})()}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 t={stack:[],error:void 0,hasError:!1};try{const r=await new rn(Kr(t,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1).source).requestEntireFile();i(r),e=vn(r,r.length,{ignore:Br})}catch(b){t.error=b,t.hasError=!0}finally{Xr(t)}}let t=!1,r=0,a=null,n=null,o=0,c=null,l=null,u=null,h=null,m=null,f=null,p=!1,g=s(this.segments)??null;const k=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},w=e=>{o=e,g&&(i(null!==g.sequenceNumber),g.sequenceNumber<e&&(r=g.timestamp+g.duration,c=g.firstSegment,l=g.initSegment,m=g.lastProgramDateTimeSeconds,g=null))};for(let i=0;i<e.length;i++){const b=e[i];if(t){if(!b.startsWith("#")){if(!g){if(null===a)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let e=n;if(e&&"AES-128"===e.method&&!e.iv){const t=new Uint8Array(16),i=d(t);i.setUint32(8,Math.floor(o/2**32)),i.setUint32(12,o),e={...e,iv:t}}const t={path:se(this.path,b),offset:h?.offset??0,length:h?.length??null},i={timestamp:r,relativeToUnixEpoch:null!==m,firstSegment:c,sequenceNumber:o,location:t,duration:a,encryption:e,initSegment:l,lastProgramDateTimeSeconds:m};c??=i,r+=a,this.segments.push(i)}a=null,null===h?u=null:h=null,w(o+1)}if(b.startsWith("#EXTINF:")){if(g){p=!0;continue}p||(null===m&&o>0&&null!==f&&(r=o*f),p=!0);const e=b.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),s=Number(i);if(!Number.isFinite(s)||s<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);a=s}else if(b.startsWith("#EXT-X-MAP:")){const e=new Ar(b.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let s=null;if(null!==i&&(s=k(i)),s&&null===s.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!g){const e={path:se(this.path,t),offset:s?.offset??0,length:s?.length??null};if("AES-128"===n?.method&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:r,relativeToUnixEpoch:null!==m,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:m}}a=null,null===h?u=null:h=null}else if(b.startsWith("#EXT-X-KEY:")){const e=new Ar(b.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!Gr.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(16);for(let t=0;t<16;t++){const r=-32+t;i[t]=parseInt(e.slice(r,r+2),16)}}const a=e.get("keyformat")??"identity";if("identity"!==a)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.");n={method:"AES-128",keyUri:se(this.path,t),iv:i,keyFormat:a}}else{if("SAMPLE-AES"!==t&&"SAMPLE-AES-CTR"!==t)throw new Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`);{const i=e.get("uri");if(!i)throw new Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if("identity"===(e.get("keyformat")??"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 r=null;if(Qr.test(i)){const e=i.indexOf(","),t=ie(i.slice(e+1));if(t.length>=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=d(t).getUint32(0);r=$t(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(b.startsWith("#EXT-X-MEDIA-SEQUENCE:")){const e=b.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);w(t)}else if(b.startsWith("#EXT-X-BYTERANGE:")){const e=k(b.slice(17));if(null===e.offset){if(null===u)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=u}h=e,u=e.offset+e.length}else if(b.startsWith("#EXT-X-PROGRAM-DATE-TIME:")){if(g)continue;const e=b.slice(25),t=Date.parse(e);if(!Number.isFinite(t))continue;const i=t/1e3;if(m===i)continue;if(null===m&&this.segments.length>0){const e=s(this.segments),t=i-(e.timestamp+e.duration);for(const i of this.segments)i.timestamp+=t,i.relativeToUnixEpoch=!0;r+=t}m=i,r=i}else if("#EXT-X-DISCONTINUITY"===b)c=null;else if(b.startsWith("#EXT-X-TARGETDURATION:")){const e=b.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,f=t}else{if("#EXT-X-ENDLIST"===b){this.streamHasEnded=!0;break}b.startsWith("#EXT-X-PLAYLIST-TYPE:")&&"vod"===b.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}else{if("#EXTM3U"!==b)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");t=!0}}if(!t)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return 0===this.segments.length&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){0===this.segments.length&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=x(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r<this.segments.length-1||this.streamHasEnded||i)return this.segments[r];const a=this.segments[r];if(e<a.timestamp+a.duration)return a;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){const r=this.segments.indexOf(e);i(-1!==r);const a=r+1;let s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(a<this.segments.length)return this.segments[a];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){const t=this.segments.indexOf(e);return i(-1!==t),this.segments[t-1]??null}getInputForSegment(e){const t=e,r=this.inputCache.find(e=>e.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let a=null;(t.initSegment||t.firstSegment)&&(a=this.getInputForSegment(t.initSegment??t.firstSegment));const s={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let i=e.psshBoxes;const{psshBox:r}=t.encryption;return null!==r.keyIds&&!r.keyIds.includes(e.keyId)||i.some(e=>Kt(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},n=new Zs({source:new Wr(t.location.path,async e=>{i(e.isRoot);const r={...e,isRoot:!1};let a;const s=t.location.offset>0||null!==t.location.length;if(t.encryption&&"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method)if("AES-128"===t.encryption.method){const e=t.encryption;i(e.iv);let n=await this.input._getSourceCached(r);if(s){const e=n.source.slice(t.location.offset,t.location.length??void 0).ref();n.free(),n=e}a=new qr(((e,t,i)=>{let r=!1,a=0;const s=new ci;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(o instanceof Promise&&(o=await o),!o||0===o.length)throw new Error("Invalid ciphertext.");const c=o.length;if(c%16!=0)throw new Error("Invalid ciphertext.");const l=65552===c?c-16:c,d=nn(o,l),u=new Uint8Array(l);for(let e=0;e<l;e+=16)s.in.set(d.subarray(e,e+16)),s.decrypt(),u.set(s.out,e);if(l<c)n.enqueue(u),a+=l;else{const e=u[l-1];if(0===e||e>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=u.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new rn(n.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=await new rn(Kr(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},2),!1).source).requestSlice(0,16);if(!i)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:nn(i,16),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{Xr(t)}},()=>{n.free()})).ref()}else i(!1);else if(a=await this.input._getSourceCached(r),s){const e=a.source.slice(t.location.offset,t.location.length??void 0).ref();a.free(),a=e}return a}),formats:this.input._formats.filter(e=>!(e instanceof ka)),initInput:a??void 0,formatOptions:s});if(n._onFormatDetermined=e=>{if(("SAMPLE-AES"===t.encryption?.method||"SAMPLE-AES-CTR"===t.encryption?.method)&&!e._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:n,age:this.nextInputCacheAge++}),this.inputCache.length>4){const e=oe(this.inputCache,e=>e.age);i(-1!==e),this.inputCache.splice(e,1)}return n}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}},Jr=class extends Vt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{i(this.input._rootSource instanceof Lr);const{rootPath:e}=this.input._rootSource,t=await this.input._reader.requestEntireFile();i(t);const r=vn(t,t.length,{ignore:Br}),a=[],s=[];for(let i=1;i<r.length;i++){const t=r[i];if(t.startsWith("#EXT-X-STREAM-INF:")){const s=i,n=r[++i];if(void 0===n)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const o=se(e,n),c=new Ar(t.slice(18));if(null===c.getAsNumber("bandwidth"))throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");a.push({fullPath:o,attributes:c,lineNumber:s,hasOnlyKeyPackets:!1})}else if(t.startsWith("#EXT-X-I-FRAME-STREAM-INF:")){const r=new Ar(t.slice(26)),s=r.get("uri");if(null===s)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(null===r.getAsNumber("bandwidth"))throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const n=se(e,s);a.push({fullPath:n,attributes:r,lineNumber:i,hasOnlyKeyPackets:!0})}else if(t.startsWith("#EXT-X-MEDIA:")){const r=new Ar(t.slice(13));if(null===r.get("type"))throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(null===r.get("group-id"))throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let a=null;const n=r.get("uri");null!==n&&(a=se(e,n)),s.push({fullPath:a,attributes:r,lineNumber:i})}else if("#EXT-X-I-FRAMES-ONLY"===t);else if(t.startsWith("#EXTINF:")){const t=new Yr(this,e,null,r);return this.segmentedInputs=[t],this.hasMasterPlaylist=!1,void(this.trackBackings=await t.getTrackBackings())}}const n=[...new Set(s.filter(e=>"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(s.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],c=await Promise.all(a.map(async(t,r)=>{const a=[],c=t.attributes.get("codecs");let l;if(c)l=c.split(",").map(e=>e.trim());else{const e=await this.getSegmentedInputForPath(t.fullPath).getTrackBackings(),i=await Promise.all(e.map(async e=>({track:e,codec:await e.getCodec()})));l=await Promise.all(i.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const d=t.attributes.get("video"),u=t.attributes.get("audio"),h=l.some(e=>ve.includes(Le(e))),m=l.some(e=>xe.includes(Le(e)));if(null!==d&&!h){if(!n.includes(d))throw new Error(`Invalid M3U8 file; variant stream references video group "${d}" which is not defined in any #EXT-X-MEDIA tags.`);const t=s.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===d&&"video"===i.toLowerCase()});e:if(t){const r=t.attributes.get("uri");if(null===r)break e;const a=se(e,r),s=(await this.getSegmentedInputForPath(a).getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);i(null!==n),l.push(n)}}if(null!==u&&!m){if(!o.includes(u))throw new Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);const t=s.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"audio"===i.toLowerCase()});e:if(t){const r=t.attributes.get("uri");if(null===r)break e;const a=se(e,r),s=(await this.getSegmentedInputForPath(a).getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);i(null!==n),l.push(n)}}l=[...new Set(l)];let f=null,p=null;const g=t.attributes.getAsNumber("bandwidth");i(null!==g);const k=t.attributes.getAsNumber("average-bandwidth"),w=t.attributes.get("name");for(const e of l){const i=Le(e);if(null!==i)if(ve.includes(i)){if(null!==f)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");f=e;const i=t.attributes.get("video");if(null===i){const e=t.attributes.get("resolution");let i=null,s=null;if(e){const t=e.match(/^(\d+)x(\d+)$/);t&&(i=Number(t[1]),s=Number(t[2]))}a.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:"und",lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:f,pairingMask:1n<<BigInt(r),peakBitrate:g,averageBitrate:k,name:w,hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"video",width:i,height:s}})}else{if(!n.includes(i))throw new Error(`Invalid M3U8 file; variant stream references video group "${i}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of s){const s=e.attributes.get("group-id"),n=e.attributes.get("type");if(s!==i||"video"!==n.toLowerCase())continue;const o=e.attributes.get("resolution")??t.attributes.get("resolution");let c=null,l=null;if(o){const e=o.match(/^(\d+)x(\d+)$/);e&&(c=Number(e[1]),l=Number(e[2]))}a.push({id:-1,demuxer:this,backingTrack:null,default:ia(e.attributes),autoselect:ia(e.attributes)||ra(e.attributes),languageCode:aa(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:e.fullPath??t.fullPath,fullCodecString:f,pairingMask:1n<<BigInt(r),peakBitrate:null,averageBitrate:null,name:e.attributes.get("name"),hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"video",width:c,height:l}})}}}else if(xe.includes(i)){if(null!==p)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");p=e;const i=t.attributes.get("audio");if(null===i){const e=t.attributes.get("channels"),i=null!==e?Number(e.split("/")[0]):null;a.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:"und",lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(r),peakBitrate:g,averageBitrate:k,name:w,hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==i&&Number.isInteger(i)&&i>0?i:null}})}else{if(!o.includes(i))throw new Error(`Invalid M3U8 file; variant stream references audio group "${i}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of s){const s=e.attributes.get("group-id"),n=e.attributes.get("type");if(s!==i||"audio"!==n.toLowerCase())continue;const o=e.attributes.get("channels")??t.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;a.push({id:-1,demuxer:this,backingTrack:null,default:ia(e.attributes),autoselect:ia(e.attributes)||ra(e.attributes),languageCode:aa(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:e.fullPath??t.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(r),peakBitrate:null,averageBitrate:null,name:e.attributes.get("name"),hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==c&&Number.isInteger(c)&&c>0?c:null}})}}}}return a})),l=[],d=e=>{const t=l.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||=e.default,t.autoselect||=e.autoselect,t.lineNumber=Math.min(t.lineNumber,e.lineNumber),null!==e.peakBitrate&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),null!==e.averageBitrate&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),"und"===t.languageCode&&(t.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const i of c)for(const e of i)d(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const i of l)"video"===i.info.type?this.trackBackings.push(new ea(i)):this.trackBackings.push(new ta(i));this.internalTracks=l})()}async getTrackBackings(){return await this.readMetadata(),i(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let i=null;return this.internalTracks&&(i=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))),t=new Yr(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return _r}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}},Zr=class{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 r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===r.length)t=r[0];else if(this instanceof ea){for(const i of r)if(await i.getCodec()===this.getCodec()){t=i;break}}else{i(this instanceof ta);for(const e of r)if(await e.getCodec()===this.getCodec()){t=e;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{...ke,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(){i(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())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async 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)}},ea=class extends Zr{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Le(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async 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()}},ta=class extends Zr{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Le(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?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()}},ia=e=>{const t=e.get("default");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},ra=e=>{const t=e.get("autoselect");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},aa=e=>{if(null===e)return"und";return e.split("-")[0]||"und"},sa=class{constructor(){this._isIsobmff=!1}},na=class extends sa{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);const i=Sn(t,4);return"ftyp"!==i&&"styp"!==i?null:Sn(t,4)}_createDemuxer(e){return new li(e)}},oa=class extends na{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=e._reader.requestSlice(4,4);if(i instanceof Promise&&(i=await i),!i)return!1;const r=Sn(i,4);return"moof"===r||"sidx"===r}get name(){return"MP4"}get mimeType(){return"video/mp4"}},ca=class extends na{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}},la=class extends sa{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,16);if(i instanceof Promise&&(i=await i),!i)return!1;const r=Ri(i);if(null===r)return!1;if(r<1||r>8)return!1;if(Mi(i,r)!==Ft.EBML)return!1;const a=zi(i);if("number"!=typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(s instanceof Promise&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Oi(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case Ft.EBMLVersion:case Ft.EBMLReadVersion:if(1!==Mi(s,r))return!1;break;case Ft.DocType:if(Ni(s,r)!==t)return!1;break;case Ft.DocTypeVersion:if(Mi(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new $i(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}},da=class extends la{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}},ua=class extends sa{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,10);if(i instanceof Promise&&(i=await i),!i)break;const r=In(i);if(!r)break;t=i.filePos+r.size}const i=await Qi(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=Xe(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(s instanceof Promise&&(s=await s),!s)return!1;const n=mn(s);if(1483304551===n||1231971951===n)return!0;t=i.startPos+i.header.totalSize;const o=await Qi(e._reader,t,t+4);if(!o)return!1;const c=o.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new Yi(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}},ha=class extends sa{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const i=Sn(t,4);return("RIFF"===i||"RIFX"===i||"RF64"===i)&&(t.skip(4),"WAVE"===Sn(t,4))}_createDemuxer(e){return new cr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}},ma=class extends sa{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===Sn(t,4)}_createDemuxer(e){return new ar(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}},fa=class extends sa{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===Sn(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new pr(e)}},pa=class extends sa{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,10);if(i instanceof Promise&&(i=await i),!i)break;const r=In(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(i instanceof Promise&&(i=await i),!i)return!1;const r=ur(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),i instanceof Promise&&(i=await i),!i)return!1;const a=ur(i);return!!a&&r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration}_createDemuxer(e){return new mr(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}},ga=class extends sa{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;const i=nn(t,205);return 71===i[0]&&71===i[188]||71===i[0]&&71===i[204]||71===i[4]&&71===i[196]}_createDemuxer(e){return new yr(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}},ka=class extends sa{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t)return!1;if("#EXTM3U"!==Sn(t,7))return!1;if(!(e._rootSource instanceof Lr))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 Jr(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return _r}},wa=/* @__PURE__ */new oa,ba=/* @__PURE__ */new ca,ya=/* @__PURE__ */new la,Ta=/* @__PURE__ */new da,Sa=/* @__PURE__ */new ua,va=/* @__PURE__ */new ha,Pa=/* @__PURE__ */new ma,Ca=/* @__PURE__ */new pa,xa=/* @__PURE__ */new fa,Ia=/* @__PURE__ */new ga,Ea=[/* @__PURE__ */new ka,wa,ba,ya,Ta,va,Pa,xa,Sa,Ca,Ia],_a=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});re();var Ba=-1/0,Aa=-1/0,Ra=null;"undefined"!=typeof FinalizationRegistry&&(Ra=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Ba>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Ba=t),"undefined"!=typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Aa>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Aa=t),"undefined"!=typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));var Fa=class{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}},Ma=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Da=new Set(Ma),za=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(q*this.timestamp)}get microsecondDuration(){return Math.trunc(q*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(t,r){if(this._closed=!1,t instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&t instanceof SharedArrayBuffer||ArrayBuffer.isView(t)){if(!r||"object"!=typeof r)throw new TypeError("init must be an object.");if(void 0===r.format||!Da.has(r.format))throw new TypeError("init.format must be one of: "+Ma.join(", "));if(!Number.isInteger(r.codedWidth)||r.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(r.codedHeight)||r.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==r.rotation&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==r.duration&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==r.layout){if(!Array.isArray(r.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const e of r.layout){if(!e||"object"!=typeof e||Array.isArray(e))throw new TypeError("Each entry in init.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(void 0!==r.visibleRect&&le(r.visibleRect,"init.visibleRect"),void 0!==r.displayWidth&&(!Number.isInteger(r.displayWidth)||r.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==r.displayHeight&&(!Number.isInteger(r.displayHeight)||r.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==r.displayWidth!=(void 0!==r.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=l(t).slice(),this._layout=r.layout??$a(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0;let e=r.colorSpace??null;null===e&&(e="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new Wa(e),this.visibleRect={left:r.visibleRect?.left??0,top:r.visibleRect?.top??0,width:r.visibleRect?.width??r.codedWidth,height:r.visibleRect?.height??r.codedHeight},void 0!==r.displayWidth?(this.squarePixelWidth=this.rotation%180==0?r.displayWidth:r.displayHeight,this.squarePixelHeight=this.rotation%180==0?r.displayHeight:r.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if("undefined"!=typeof VideoFrame&&t instanceof VideoFrame){if(void 0!==r?.rotation&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==r?.timestamp&&!Number.isFinite(r?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==r?.duration&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==r?.visibleRect&&le(r.visibleRect,"init.visibleRect"),this._data=t,this._layout=null,this.format=t.format,this.visibleRect={left:t.visibleRect?.x??0,top:t.visibleRect?.y??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},this.rotation=r?.rotation??0,this.squarePixelWidth=t.displayWidth,this.squarePixelHeight=t.displayHeight,this.timestamp=r?.timestamp??t.timestamp/1e6,this.duration=r?.duration??(t.duration??0)/1e6,this.colorSpace=new Wa(t.colorSpace)}else if("undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&t instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&t instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas){if(!r||"object"!=typeof r)throw new TypeError("init must be an object.");if(void 0!==r.rotation&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==r.duration&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if("undefined"!=typeof VideoFrame)return new e(new VideoFrame(t,{timestamp:Math.trunc(r.timestamp*q),duration:Math.trunc((r.duration??0)*q)||void 0}),r);let a=0,s=0;if("naturalWidth"in t?(a=t.naturalWidth,s=t.naturalHeight):"videoWidth"in t?(a=t.videoWidth,s=t.videoHeight):"width"in t&&(a=Number(t.width),s=Number(t.height)),!a||!s)throw new TypeError("Could not determine dimensions.");const n=new OffscreenCanvas(a,s),o=n.getContext("2d",{alpha:X(),willReadFrequently:!0});i(o),o.drawImage(t,0,0),this._data=n,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a,height:s},this.squarePixelWidth=a,this.squarePixelHeight=s,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new Wa({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(t instanceof Fa))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!r||"object"!=typeof r)throw new TypeError("init must be an object.");if(void 0!==r.rotation&&![0,90,180,270].includes(r.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(r.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==r.duration&&(!Number.isFinite(r.duration)||r.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=t,t._referenceCount++,this.format=t.getFormat(),null!==this.format&&!Ma.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:t.getCodedWidth(),height:t.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=t.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=t.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=t.getColorSpace()}this.pixelAspectRatio=ce({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),Ra?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return i(null!==this._data),this._data instanceof Fa?new e(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):Va(this._data)?new e(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(i(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,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):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,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(Ra?.unregister(this),this._data instanceof Fa?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Va(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(ja(e),this._closed)throw new Error("VideoSample is closed.");if(null==(e.format??this.format))throw new Error("Cannot get allocation size when format is null.");return Va(this._data)?this._data.allocationSize(e):Xa(this,e).allocationSize}async copyTo(t,r={}){if(!y(t))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(ja(r),this._closed)throw new Error("VideoSample is closed.");if(null==(r.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(i(null!==this._data),Va(this._data))return this._data.copyTo(t,r);if(r.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(r.format)){if(!(this._data instanceof Fa)){if("undefined"==typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const e=this.toVideoFrame(),i=await e.copyTo(t,r);return e.close(),i}{const i={stack:[],error:void 0,hasError:!1};try{const a=function(e,t,i){if(null!=t){if("object"!=typeof t&&"function"!=typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!=typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(i,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},r.colorSpace??"srgb"),!1);if(!(a instanceof e))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(a.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${a.format}' instead.`);return await a.copyTo(t,r)}catch(u){i.error=u,i.hasError=!0}finally{_a(i)}}}const a=Xa(this,r);i(this.format);const s=l(t);if(s.byteLength<a.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${a.allocationSize}, Available: ${s.byteLength}`);const n=Ka(this.format);let o;if(this._data instanceof Fa){let e=this._data.getDataPlanes();if(e instanceof Promise&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=e}else if(this._data instanceof Uint8Array)i(this._layout),i(this._layout.length===n.length),o=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/n[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");i(e),o=[{data:l(e.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}const c=[],d=n.length;for(let e=0;e<d;e++){const t=a.computedLayouts[e],i=o[e].stride,r=o[e].data;let n=t.sourceTop*i;n+=t.sourceLeftBytes;let l=t.destinationOffset;const d=t.sourceWidthBytes,u={offset:l,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(n+d>r.byteLength)throw new Error("Source buffer OOB read.");if(l+d>s.byteLength)throw new Error("Destination buffer OOB write.");const e=r.subarray(n,n+d);s.set(e,l),n+=i,l+=t.destinationStride}c.push(u)}if(void 0!==r.format){const e=this.format.startsWith("RGB")!==r.format.startsWith("RGB"),t=this.format.includes("X")&&r.format.includes("A");if(e||t)for(let i=0;i<a.allocationSize;i+=4){if(e){const e=s[i];s[i]=s[i+2],s[i+2]=e}t&&(s[i+3]=255)}}return c}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(i(null!==this._data),this._data instanceof Fa){if(null===this.format)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((e,t)=>e+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const a=[];for(const s of e)i.set(s.data,r),a.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:a[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Va(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,d=0,u=this.displayWidth,h=this.displayHeight,m=0,f=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,d=i,u=r,h=a,m=s,f=n,void 0!==o?(p=o,g=c):(p=u,g=h)):(m=t,f=i,void 0!==r&&(p=r,g=a)),!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))throw new TypeError("sy must be a number.");if(!Number.isFinite(u)||u<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(m))throw new TypeError("dx must be a number.");if(!Number.isFinite(f))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:d,sWidth:u,sHeight:h}=this._rotateSourceRegion(l,d,u,h,this.rotation));const k=this.toCanvasImageSource();e.save();const w=m+p/2,b=f+g/2;e.translate(w,b),e.rotate(this.rotation*Math.PI/180);const y=this.rotation%180==0?1:p/g;e.scale(1/y,y),e.drawImage(k,l,d,u,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)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(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Ha(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,d,u=t.crop;u&&(u=qa(u,s,n));const{sx:h,sy:m,sWidth:f,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,d=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],u="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*u,d=a*u,o=(i-l)/2,c=(r-d)/2}e.save();const g=a%180==0?1:l/d;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),h,m,f,p,o,c,l,d),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(i(null!==this._data),this._data instanceof Fa||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(t){if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.width&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==t.height&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==t.roundDimensionsTo&&(!Number.isInteger(t.roundDimensionsTo)||t.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotate&&![0,90,180,270].includes(t.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&Ha(t.crop,"options."),void 0!==t.alpha&&!["keep","discard"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const r=a(this.rotation+(t.rotate??0)),[s,n]=r%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o=t.crop;o&&(o=qa(o,s,n));const c=o?o.width:s,l=o?o.height:n,d=c/l;let u,h;void 0!==t.width&&void 0===t.height?(u=t.width,h=u/d):void 0===t.width&&void 0!==t.height?(h=t.height,u=h*d):void 0!==t.width&&void 0!==t.height?(u=t.width,h=t.height):(u=c,h=l),u=O(u,t.roundDimensionsTo??1),h=O(h,t.roundDimensionsTo??1);const m={width:u,height:h,fit:t.fit??"fill",rotation:r,crop:o??{left:0,top:0,width:s,height:n},alpha:t.alpha??"keep"};for(const e of Oa){let t=e(this,m);if(t instanceof Promise&&(t=await t),null!==t)return t}let f=null,p=!1;for(const e of La)if(e.canvas.width===m.width&&e.canvas.height===m.height){f=e.canvas,e.age=Ua++;break}if(null===f){if("undefined"!=typeof OffscreenCanvas)f=new OffscreenCanvas(m.width,m.height);else{if("undefined"==typeof window||"undefined"==typeof document)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().");f=document.createElement("canvas"),f.width=m.width,f.height=m.height}p=!0,La.length>=Na&&La.splice(oe(La,e=>e.age),1),La.push({canvas:f,age:Ua++})}const g=f.getContext("2d",{alpha:!0});return i(g),"discard"===m.alpha?(g.fillStyle="black",g.fillRect(0,0,m.width,m.height)):p||g.clearRect(0,0,m.width,m.height),this.drawWithFit(g,{fit:m.fit,rotation:m.rotation,crop:m.crop}),new e(f,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}},Oa=[],Na=3,La=[],Ua=0,Wa=class{constructor(e){if(void 0!==e){if(!e||"object"!=typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(f);if(null!=e.primaries&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(g);if(null!=e.transfer&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(w);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)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}}},Va=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,qa=(e,t,r)=>{const a=Math.min(e.left,t),s=Math.min(e.top,r),n=Math.min(e.width,t-a),o=Math.min(e.height,r-s);return i(n>=0),i(o>=0),{left:a,top:s,width:n,height:o}},Ha=(e,t)=>{if(!e||"object"!=typeof e)throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},ja=e=>{if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!=typeof e.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const t of e.layout){if(!t||"object"!=typeof t)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!=typeof e.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},$a=(e,t,i)=>{const r=Ka(e),a=[];let s=0;for(const n of r){const e=Math.ceil(t/n.widthDivisor),r=Math.ceil(i/n.heightDivisor),o=e*n.sampleBytes,c=o*r;a.push({offset:s,stride:o}),s+=c}return a},Ka=e=>{const t=(e,t,i,r,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:A(e),i(!1)}},Xa=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=Ga(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let n;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");n=t.format}else n=e.format;return Ya(a,n,s)},Ga=(e,t,i,r,a)=>{const s={...e};if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!Qa(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Qa=(e,t)=>{if(null===e)return!0;const i=Ka(e);for(let r=0;r<i.length;r++){const e=i[r],a=e.widthDivisor,s=e.heightDivisor;if((t.x||0)%a!==0)return!1;if((t.y||0)%s!==0)return!1}return!0},Ya=(e,t,i)=>{const r=Ka(t),a=r.length;if(void 0!==i&&i.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const n=[],o=[];for(let c=0;c<a;c++){const t=r[c],a=t.sampleBytes,l=t.widthDivisor,d=t.heightDivisor,u={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(u.sourceTop=Math.ceil(Math.trunc(e.y||0)/d),u.sourceHeight=Math.ceil(Math.trunc(e.height||0)/d),u.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*a,u.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/l)*a,void 0!==i){const e=i[c];if(e.stride<u.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);u.destinationOffset=e.offset,u.destinationStride=e.stride}else u.destinationOffset=s,u.destinationStride=u.sourceWidthBytes;const h=u.destinationStride*u.sourceHeight+u.destinationOffset;if(h>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let e=0;e<c;e++){const t=n[e];if(!(o[c]<=t.destinationOffset||o[e]<=u.destinationOffset))throw new TypeError("Planes overlap.")}n.push(u)}return{allocationSize:s,computedLayouts:n}},Ja=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]),Za=class{constructor(){this._referenceCount=0}},es=class e{get microsecondTimestamp(){return Math.trunc(q*this.timestamp)}get microsecondDuration(){return Math.trunc(q*this.duration)}constructor(e){if(this._closed=!1,ss(e)){if(null===e.format)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 Za){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Ja.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||"object"!=typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Ja.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)||0===e.numberOfChannels)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/(ts(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let i;if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate,e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const r=this.numberOfFrames*this.numberOfChannels*ts(this.format);if(i.byteLength<r)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}Ra?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||"object"!=typeof e)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(void 0!==e.format&&!Ja.has(e.format))throw new TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!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 r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const a=ts(t),s=is(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?r:r*this.numberOfChannels)*a}copyTo(e,t){if(!y(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)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(void 0!==t.format&&!Ja.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!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:r,frameOffset:a}=t;let{planeIndex:s}=t;const n=this.format,o=i??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:c-u;if(h>c-u)throw new RangeError("frameCount out of range");const m=ts(o),f=is(o);if(f&&s>=l)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const p=(f?h:h*l)*m;if(e.byteLength<p)throw new RangeError("Destination buffer is too small");const g=d(e),k=as(o);if(ss(this._data))$()&&l>2&&o!==n?os(this._data,g,n,o,l,s,u,h):this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:h,format:o});else{const e=rs(n),t=ts(n),i=is(n);let r;if(this._data instanceof Za){const e=e=>{const r=this._data.getDataPlane(e);if(!(r instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const a=c*t*(i?1:l);if(r.byteLength!==a)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${a} bytes, got ${r.byteLength} bytes.`);return r};if(i)if(f)r=e(s),s=0;else{r=new Uint8Array(c*t*l);for(let i=0;i<l;i++){const a=e(i);r.set(a,i*c*t)}}else r=e(0)}else r=this._data;const a=d(r);for(let n=0;n<h;n++)if(f){let r;r=i?(s*c+(n+u))*t:((n+u)*l+s)*t,k(g,n*m,e(a,r))}else for(let r=0;r<l;r++){let s;s=i?(r*c+(n+u))*t:((n+u)*l+r)*t,k(g,(n*l+r)*m,e(a,s))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Za){const t=new e(this._data);return t.setTimestamp(this.timestamp),t}if(ss(this._data)){const t=new e(this._data.clone());return t.setTimestamp(this.timestamp),t}return new e({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Ra?.unregister(this),this._data instanceof Za?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):ss(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 Za?this._createAudioDataFromData():ss(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(is(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})}{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"}),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(t,i){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=t.numberOfChannels,a=t.sampleRate,s=t.length,n=Math.floor(24e4/r);let o=0,c=s;for(;c>0;){const s=Math.min(n,c),l=new Float32Array(r*s);for(let e=0;e<r;e++)t.copyFromChannel(l.subarray(e*s,(e+1)*s),e,o);yield new e({format:"f32-planar",sampleRate:a,numberOfFrames:s,numberOfChannels:r,timestamp:i+o/a,data:l}),o+=s,c-=s}}static fromAudioBuffer(t,i){if(!(t instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=t.numberOfChannels,a=t.sampleRate,s=t.length,n=Math.floor(24e4/r);let o=0,c=s;const l=[];for(;c>0;){const s=Math.min(n,c),d=new Float32Array(r*s);for(let e=0;e<r;e++)t.copyFromChannel(d.subarray(e*s,(e+1)*s),e,o);const u=new e({format:"f32-planar",sampleRate:a,numberOfFrames:s,numberOfChannels:r,timestamp:i+o/a,data:d});l.push(u),o+=s,c-=s}return l}},ts=e=>{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},is=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},rs=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},as=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,D(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,D(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,D(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},ss=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,ns=e=>{switch(e){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return e}},os=(e,t,i,r,a,s,n,o)=>{const c=rs(i),l=as(r),u=ts(i),h=ts(r),m=is(i);if(is(r))if(m){const r=new ArrayBuffer(o*u),a=d(r);e.copyTo(r,{planeIndex:s,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++)l(t,e*h,c(a,e*u))}else{const r=new ArrayBuffer(o*a*u),m=d(r);e.copyTo(r,{planeIndex:0,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++)l(t,e*h,c(m,(e*a+s)*u))}else if(m){const r=new ArrayBuffer(o*u),s=d(r);for(let d=0;d<a;d++){e.copyTo(r,{planeIndex:d,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++)l(t,(e*a+d)*h,c(s,e*u))}}else{const r=new ArrayBuffer(o*a*u),s=d(r);e.copyTo(r,{planeIndex:0,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++)for(let i=0;i<a;i++){const r=e*a+i;l(t,r*h,c(s,r*u))}}},cs=(e,t)=>{const i=e.allocationSize({format:t,planeIndex:0}),r=new ArrayBuffer(i);return e.copyTo(r,{format:t,planeIndex:0}),new es({data:r,format:t,numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,timestamp:e.timestamp,duration:e.duration})},ls=/* @__PURE__ */new Map,ds=/* @__PURE__ */new Map,us=(e,t)=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding options must be an object.");if(void 0!==t.alpha&&!["discard","keep"].includes(t.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==t.latencyMode&&!["quality","realtime"].includes(t.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==t.fullCodecString&&"string"!=typeof t.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==t.fullCodecString&&Le(t.fullCodecString)!==e)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(void 0!==t.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==t.scalabilityMode&&"string"!=typeof t.scalabilityMode)throw new TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==t.contentHint&&"string"!=typeof t.contentHint)throw new TypeError("contentHint, when provided, must be a string.")},hs=e=>{const t=e.bitrate instanceof ps?e.bitrate._toVideoBitrate(e.codec,e.width,e.height):e.bitrate;return{codec:e.fullCodecString??Re(e.codec,e.width,e.height,t),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:e.bitrateMode,alpha:e.alpha??"discard",framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...(i=e.codec,"avc"===i?{avc:{format:"avc"}}:"hevc"===i?{hevc:{format:"hevc"}}:{})};var i},ms=(e,t)=>{if(!t||"object"!=typeof t)throw new TypeError("Encoding options must be an object.");if(void 0!==t.bitrateMode&&!["constant","variable"].includes(t.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==t.fullCodecString&&"string"!=typeof t.fullCodecString)throw new TypeError("fullCodecString, when provided, must be a string.");if(void 0!==t.fullCodecString&&Le(t.fullCodecString)!==e)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},fs=e=>{const t=e.bitrate instanceof ps?e.bitrate._toAudioBitrate(e.codec):e.bitrate;return{codec:e.fullCodecString??Me(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:t,bitrateMode:e.bitrateMode,...(i=e.codec,"aac"===i?{aac:{format:"aac"}}:"opus"===i?{opus:{format:"opus"}}:{})};var i},ps=class{constructor(e){this._factor=e}_toVideoBitrate(e,t,i){const r=t*i,a=3e6*Math.pow(r/2073600,.95)*{avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2}[e]*this._factor;return 1e3*Math.ceil(a/1e3)}_toAudioBitrate(e){if(Pe.includes(e)||"flac"===e)return;const t={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!t)throw new Error(`Unhandled codec: ${e}`);let i=t*this._factor;return"aac"===e?i=[96e3,128e3,16e4,192e3].reduce((e,t)=>Math.abs(t-i)<Math.abs(e-i)?t:e):"opus"===e||"vorbis"===e?i=Math.max(6e3,i):"mp3"===e&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-i)<Math.abs(e-i)?t:e)),1e3*Math.round(i/1e3)}},gs=/* @__PURE__ */new ps(1),ks=/* @__PURE__ */new ps(2),ws=async(e,t={})=>{const{width:i=1280,height:r=720,bitrate:a=1e6,...s}=t;if(!ve.includes(e))return!1;if(!Number.isInteger(i)||i<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(!(a instanceof ps)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");us(e,s);const n=hs({codec:e,width:i,height:r,bitrate:a,framerate:void 0,...s,alpha:"discard"}),o=JSON.stringify(n),c=ls.get(o);if(c)return c;const l=(async()=>!!Ss.some(t=>t.supports(e,n))||"undefined"!=typeof VideoEncoder&&(i%2!=1&&r%2!=1||"avc"!==e&&"hevc"!==e)&&!!(await VideoEncoder.isConfigSupported(n)).supported&&(!X()||new Promise(async e=>{try{const t=new VideoEncoder({output:()=>{},error:()=>e(!1)});t.configure(n);const a=new Uint8Array(i*r*4),s=new VideoFrame(a,{format:"RGBA",codedWidth:i,codedHeight:r,timestamp:0});t.encode(s),s.close(),await t.flush(),e(!0)}catch{e(!1)}})))();return ls.set(o,l),l},bs=async(e=xe,t)=>{const i=await Promise.all(e.map(e=>(async(e,t={})=>{const{numberOfChannels:i=2,sampleRate:r=48e3,bitrate:a=128e3,...s}=t;if(!xe.includes(e))return!1;if(!Number.isInteger(i)||i<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(a instanceof ps)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");ms(e,s);const n=fs({codec:e,numberOfChannels:i,sampleRate:r,bitrate:a,...s}),o=JSON.stringify(n),c=ds.get(o);if(c)return c;const l=(async()=>!!vs.some(t=>t.supports(e,n))||!!Pe.includes(e)||"undefined"!=typeof AudioEncoder&&!0===(await AudioEncoder.isConfigSupported(n)).supported)();return ds.set(o,l),l})(e,t)));return e.filter((e,t)=>i[t])},ys=[],Ts=[],Ss=[],vs=[],Ps=e=>{if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(void 0!==e.skipLiveWait&&"boolean"!=typeof e.skipLiveWait)throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Cs=e=>{if(!ae(e))throw new TypeError("timestamp must be a number.")},xs=(e,t,i)=>i.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const i=await e.determinePacketType(t);return i&&(t.type=i),t}):t,Is=class{constructor(e){if(!(e instanceof Us))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Ps(e),this._track.input._disposed)throw new tn;return xs(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Ps(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Cs(e),Ps(t),this._track.input._disposed)throw new tn;return xs(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Ht))throw new TypeError("packet must be an EncodedPacket.");if(Ps(t),this._track.input._disposed)throw new tn;return xs(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Cs(e),Ps(t),this._track.input._disposed)throw new tn;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);return r?(i("key"===r.type),"delta"===await this._track.determinePacketType(r)?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r):r}async getNextKeyPacket(e,t={}){if(!(e instanceof Ht))throw new TypeError("packet must be an EncodedPacket.");if(Ps(t),this._track.input._disposed)throw new tn;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);return r?(i("key"===r.type),"delta"===await this._track.determinePacketType(r)?this.getNextKeyPacket(r,t):r):r}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Ht))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Ht))throw new TypeError("endPacket must be an EncodedPacket.");if(Ps(i),this._track.input._disposed)throw new tn;const r=[];let{promise:a,resolve:s}=E(),{promise:n,resolve:o}=E(),c=!1,l=!1,d=null;const u=[],h=()=>Math.max(2,u.length);(async()=>{let d=e??await this.getFirstPacket(i);for(;d&&!l&&!this._track.input._disposed&&!(t&&d.sequenceNumber>=t?.sequenceNumber);)r.length>h()?(({promise:n,resolve:o}=E()),await n):(r.push(d),s(),({promise:a,resolve:s}=E()),d=await this.getNextPacket(d,i));c=!0,s()})().catch(e=>{d||(d=e,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new tn;if(l)return{value:void 0,done:!0};if(d)throw d;if(r.length>0){const e=r.shift(),t=performance.now();for(u.push(t);u.length>0&&t-u[0]>=1e3;)u.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Es=class{constructor(e,t){this.onSample=e,this.onError=t}},_s=class{mediaSamplesInRange(e=-1/0,t=1/0,i){Cs(e),Cs(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=E(),{promise:c,resolve:l}=E(),d=!1,u=!1,h=!1,m=null;const f={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const i=await this._createDecoder(i=>{l(),i.timestamp>=t&&(u=!0),u?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=E())))},e=>{m||(m=e,o())}),p=this._createPacketSink(),g=await p.getKeyPacket(e,f)??await p.getFirstKeyPacket(f);let k=g;const w=p.packets(g??void 0,void 0,f);for(await w.next();k&&!u&&!this._track.input._disposed;){const e=Bs(r.length);if(r.length+i.getDecodeQueueSize()>e){({promise:c,resolve:l}=E()),await c;continue}i.decode(k);const t=await w.next();if(t.done)break;k=t.value}await w.return(),h||this._track.input._disposed||await i.flush(),i.close(),!a&&s&&r.push(s),d=!0,o()})().catch(e=>{m||(m=e,o())});const p=this._track,g=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new tn;if(h)return{value:void 0,done:!0};if(m)throw g(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(d)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,u=!0,l(),o(),g(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const r=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),a=[],s=[];let{promise:n,resolve:o}=E(),{promise:c,resolve:l}=E(),d=!1,u=!1,h=null;const m=e=>{s.push(e),o(),({promise:n,resolve:o}=E())},f={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const e=await this._createDecoder(e=>{if(l(),u)return void e.close();let t=0;for(;a.length>0&&e.timestamp-a[0]>-1e-10;)t++,a.shift();if(t>0)for(let i=0;i<t;i++)m(i<t-1?e.clone():e);else e.close()},e=>{h||(h=e,o())}),t=this._createPacketSink();let n=null,p=null,g=-1;const k=async()=>{i(p);let r=p;for(e.decode(r);r.sequenceNumber<g;){const a=Bs(s.length);for(;s.length+e.getDecodeQueueSize()>a&&!u;)({promise:c,resolve:l}=E()),await c;if(u)break;const n=await t.getNextPacket(r,f);i(n),e.decode(n),r=n}g=-1},w=async()=>{await e.flush();for(let e=0;e<a.length;e++)m(null);a.length=0};for await(const i of r){if(Cs(i),u||this._track.input._disposed)break;const e=await t.getPacket(i,f),r=e&&await t.getKeyPacket(i,f);r?(n&&(r.sequenceNumber!==p.sequenceNumber||e.timestamp<n.timestamp)&&(await k(),await w()),a.push(e.timestamp),g=Math.max(e.sequenceNumber,g),n=e,p=r):(-1!==g&&(await k(),await w()),m(null),n=null)}u||this._track.input._disposed||(-1!==g&&await k(),await w()),e.close(),d=!0,o()})().catch(e=>{h||(h=e,o())});const p=this._track,g=()=>{for(const e of s)e?.close()};return{async next(){for(;;){if(p.input._disposed)throw g(),new tn;if(u)return{value:void 0,done:!0};if(h)throw g(),h;if(s.length>0){const e=s.shift();return i(void 0!==e),l(),{value:e,done:!1}}if(d)return{value:void 0,done:!0};await n}},return:async()=>(u=!0,l(),o(),g(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}},Bs=e=>0===e?40:8,As=class extends Es{constructor(e,t,r,a,s,n){super(e,t),this.codec=r,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new H,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.frameHandlerSerializer=new H;const o=ys.find(e=>e.supports(r,a));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof za))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();i(void 0!==t),await this.mergeAlpha(e,t)}else this.colorQueue.push(e)}).catch(e=>this.onError(e))};if("avc"===r&&this.decoderConfig.description&&Q()){const e=(e=>{try{const t=d(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint8(i++),n=t.getUint8(i++),o=3&t.getUint8(i++),c=31&t.getUint8(i++),l=[];for(let d=0;d<c;d++){const r=t.getUint16(i,!1);i+=2,l.push(e.subarray(i,i+r)),i+=r}const u=t.getUint8(i++),h=[];for(let d=0;d<u;d++){const r=t.getUint16(i,!1);i+=2,h.push(e.subarray(i,i+r)),i+=r}const m={configurationVersion:r,avcProfileIndication:a,profileCompatibility:s,avcLevelIndication:n,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:h,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&i+4<=e.length){const r=3&t.getUint8(i++),a=7&t.getUint8(i++),s=7&t.getUint8(i++),n=t.getUint8(i++);m.chromaFormat=r,m.bitDepthLumaMinus8=a,m.bitDepthChromaMinus8=s;const o=[];for(let c=0;c<n;c++){const r=t.getUint16(i,!1);i+=2,o.push(e.subarray(i,i+r)),i+=r}m.sequenceParameterSetExt=o}return m}catch(t){return console.error("Error deserializing AVC Decoder Configuration Record:",t),null}})(l(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=ht(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const t=/* @__PURE__ */new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(i(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(i(this.decoder),$()||I(this.inputTimestamps,e.timestamp,e=>e),Q()&&0===this.currentPacketIndex)if("avc"===this.codec){const i=[];for(const t of at(e.data,this.decoderConfig)){const r=st(e.data[t.offset]);r>=20&&r<=31||i.push(e.data.subarray(t.offset,t.offset+t.length))}e=new Ht((t=i,(r=this.decoderConfig).description?lt(t,1+(3&l(r.description)[4])):ct(t)),e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=((e,t)=>{const i=/* @__PURE__ */new Set;let r=tt.audAllowed;for(const s of ft(e,t)){if(r===tt.noMoreDataAllowed){i.add(s.offset);continue}const t=pt(e[s.offset]);if(r===tt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>tt.audAllowed?a=!0:r=tt.beforeFirstVcl:t<=31?r>tt.afterFirstVcl?a=!0:r=tt.afterFirstVcl:36===t?r!==tt.afterFirstVcl?a=!0:r=tt.eoBitstreamAllowed:37===t?r<tt.afterFirstVcl?a=!0:r=tt.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?r>tt.beforeFirstVcl?a=!0:r=tt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r<tt.afterFirstVcl&&(a=!0),a&&i.add(s.offset)}if(0===i.size)return null;const a=[];for(const s of ft(e,t))i.has(s.offset)||a.push(e.subarray(s.offset,s.offset+s.length));return((e,t)=>t.description?lt(e,1+(3&l(t.description)[21])):ct(e))(a,t)})(e.data,this.decoderConfig);t&&(e=new Ht(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}var t,r;this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new Fs),!this.alphaDecoder){const e=e=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();i(void 0!==t),await this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const e=this.colorQueue.shift();i(void 0!==e),await this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(e=>this.onError(e))},t=/* @__PURE__ */new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=Rt(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of ft(e,this.decoderConfig)){const i=pt(e[t.offset]);if(i===Je.RASL_N||i===Je.RASL_R)return!0}return!1}sampleHandler(e){if($()){if(this.sampleQueue.length>0&&e.timestamp>=s(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}I(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();i(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){const t=new za(e);return void this.sampleHandler(t)}i(this.merger);const r=new za(await this.merger.update(e,t));this.sampleHandler(r)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await this.frameHandlerSerializer.currentPromise,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),$()){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()):(i(this.decoder),this.decoder.close(),this.alphaDecoder?.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}},Rs=!1,Fs=class e{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=/* @__PURE__ */new Map,this.nextRequestId=0;const t="undefined"!=typeof OffscreenCanvas||"undefined"!=typeof document&&"function"==typeof document.createElement;if(!e.forceCpu&&t&&!Rs)try{"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}catch(i){this.gl=null,this.canvas=null,Rs=!0,console.warn("Falling back to CPU for color/alpha merging.",i)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){i(this.gl);const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){i(this.gl);const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){i(this.gl),i(this.program);const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const a=this.gl.getAttribLocation(this.program,"a_position"),s=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){i(this.gl);const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateGpu(e,t){i(this.gl),i(this.canvas),e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const r=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),r}updateCpu(e,t){if(!this.worker){const e=new Blob([`(${Ms.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.addEventListener("message",e=>{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),this.worker.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()})}const i=this.nextRequestId++,r=E();return this.pendingRequests.set(i,r),this.worker.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;const e=/* @__PURE__ */new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};Fs.forceCpu=!0;var Ms=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:a,alpha:s}=e.data;i=i.then(async()=>{try{const e=await r(a,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{a.close(),s.close()}})});const r=async(e,t)=>{const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),c=i.includes("P12"),l=r.includes("P10"),d=r.includes("P12");if(l!==o||d!==c)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);const u=e.codedWidth,h=e.codedHeight;if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return await a(e,t,u,h,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return await s(e,t,u,h,i);if("NV12"===i)return await n(e,t,u,h);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)},a=async(e,t,i,r,a)=>{const s=i*r,n=new Uint8Array(4*s);await e.copyTo(n);const c=await o(t,i,r,1);for(let o=0,d=3;o<s;o++,d+=4)n[d]=c[o];const l={format:"RGBX"===a||"RGBA"===a?"RGBA":"BGRA",codedWidth:i,codedHeight:r,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[n.buffer]};return new VideoFrame(n,l)},s=async(e,t,i,r,a)=>{const s=a.includes("P10"),n=a.includes("P12"),c=s||n?2:1;let l,d;a.startsWith("I420")?(l=Math.ceil(i/2),d=Math.ceil(r/2)):a.startsWith("I422")?(l=Math.ceil(i/2),d=r):(l=i,d=r);const u=i*r,h=u*c,m=l*d*c,f=new Uint8Array(h+2*m+u*c);await e.copyTo(f);const p=await o(t,i,r,c),g=h+2*m;f.set(p,g);const k={format:a.slice(0,4)+"A"+a.slice(4),codedWidth:i,codedHeight:r,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[f.buffer]};return new VideoFrame(f,k)},n=async(e,i,r,a)=>{const s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const d=s,u=s+n,h=s;for(let o=0;o<n;o++)l[d+o]=t[h+2*o],l[u+o]=t[h+2*o+1];const m=await o(i,r,a,1);l.set(m,s+2*n);const f={format:"I420A",codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,f)},o=async(t,i,r,a)=>{const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e);const n=t.format;if("RGBA"===n||"BGRA"===n||"RGBX"===n||"BGRX"===n){const t="RGBA"===n||"RGBX"===n?0:2,a=i*r;for(let i=0;i<a;i++)e[i]=e[4*i+t];return e.subarray(0,a)}return e.subarray(0,i*r*a)}},Ds=class extends _s{constructor(e){if(!(e instanceof qs))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),a=await this._track.getRotation(),s=await this._track.getDecoderConfig(),n=await this._track.getTimeResolution();return i(r&&s),new As(e,t,r,s,a,n)}_createPacketSink(){return new Is(this._track)}async getSample(e,t={}){Cs(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)}},zs=class{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof qs))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.alpha&&"boolean"!=typeof t.alpha)throw new TypeError("options.alpha, when provided, must be a boolean.");if(void 0!==t.width&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(void 0!==t.height&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&Ha(t.crop,"options."),void 0!==t.poolSize&&("number"!=typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ds(e),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(),r=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[s,n]=i%180==0?[r,a]:[a,r];let o=e.crop;o&&(o=qa(o,s,n));let[c,l]=o?[o.width,o.height]:[s,n];const d=c/l;void 0!==e.width&&void 0===e.height?(c=e.width,l=Math.round(c/d)):void 0===e.width&&void 0!==e.height?(l=e.height,c=Math.round(l*d)):void 0!==e.width&&void 0!==e.height&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=i,this._crop=o})()}_videoSampleToWrappedCanvas(e){const t=this._width,r=this._height;let a=this._canvasPool[this._nextCanvasIndex],s=!1;a||("undefined"!=typeof document?(a=document.createElement("canvas"),a.width=t,a.height=r):a=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=a),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const n=a.getContext("2d",{alpha:this._alpha||X()});i(n),n.resetTransform(),s||(!this._alpha&&X()?(n.fillStyle="black",n.fillRect(0,0,t,r)):n.clearRect(0,0,t,r)),e.drawWithFit(n,{fit:this._fit,rotation:this._rotation,crop:this._crop});const o={canvas:a,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){Cs(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*M(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*M(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}},Os=class extends Es{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new H,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const a=t=>{let i=t.timestamp;this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=Ts.find(e=>e.supports(i,r));if(s)this.customDecoder=new s,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof es))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=/* @__PURE__ */new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new es(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(i(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(i(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(i(this.decoder),this.decoder.close())}},Ns=class extends Es{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,i(Pe.includes(r.codec)),this.codec=r.codec;const{dataType:a,sampleSize:s,littleEndian:n}=Ne(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const a=(1<<i|(15&r)<<i-4|1<<i-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===a?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=85^e;128&r&&(r&=-129,t=-1),i=4+((240&r)>>4);let a=0;return a=4!==i?1<<i|(15&r)<<i-4|1<<i-5:r<<1|1,0===t?a:-a})(e.getUint8(t)):i(!1);break;case 2:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):i(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>R(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,i)=>R(e,t,i)<<8>>8)(e,t,n):i(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-2**31:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):i(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):i(!1);break;default:A(s),i(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===a?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:A(s),i(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=d(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(r),s=new DataView(a);for(let l=0;l<i*this.decoderConfig.numberOfChannels;l++){const e=l*this.inputSampleSize,i=l*this.outputSampleSize,r=this.readInputValue(t,e);this.writeOutputValue(s,i,r)}const n=i/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const c=new es({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}},Ls=class extends _s{constructor(e){if(!(e instanceof Hs))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode()))throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),a=await this._track.getDecoderConfig();return i(r&&a),Pe.includes(a.codec)?new Ns(e,t,a):new Os(e,t,r,a)}_createPacketSink(){return new Is(this._track)}async getSample(e,t={}){Cs(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)}},Us=class e{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof qs}isAudioTrack(){return this instanceof Hs}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Ws(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Ws(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Ws(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Ws(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Ws(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});return N((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new Is(this);let r=1/0,a=-1/0,s=0,n=0;for await(const o of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-r)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-r)).toPrecision(16)):0}}async isLive(){return null!==await this._backing.getLiveRefreshInterval()}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(t){if(!(t instanceof e))throw new TypeError("other must be an InputTrack.");return this.input===t.input&&this!==t&&0n!==(this._backing.getPairingMask()&t._backing.getPairingMask())}async getPairableTracks(e){return this.input.getTracks(Xs({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Xs({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Xs({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Xs({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Xs({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&=Vs(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&&=Vs(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=Vs(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}},Ws=(e,t,i)=>{if(e instanceof Promise)throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},Vs=e=>{if(void 0!==e&&"function"!=typeof e)throw new TypeError("predicate, when provided, must be a function.");return e?t=>{const i=e=>{if("boolean"!=typeof e)throw new TypeError("predicate must return or resolve to a boolean value.");return e},r=e(t);return r instanceof Promise?r.then(i):i(r)}:void 0},qs=class extends Us{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Ws(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Ws(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Ws(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Ws(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Ws(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Ws(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=ce({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=ce({num:Ws(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Ws(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Ws(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Ws(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){const e=await(this._backing.getMetadataDisplayWidth?.());return null!=e?e:await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(void 0!==e){const t=Ws(e,"displayWidth","getDisplayWidth");if(null!==t)return t}return Ws(Ws(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight(),"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await(this._backing.getMetadataDisplayHeight?.());return null!=e?e:await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(void 0!==e){const t=Ws(e,"displayHeight","getDisplayHeight");if(null!==t)return t}return Ws(Ws(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth(),"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());return null!=e?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 i(null!==t),!!ys.some(i=>i.supports(t,e))||"undefined"!=typeof VideoDecoder&&!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ht))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(null===t)return null;const r=await this.getDecoderConfig();return i(r),Rt(t,r,e.data)}},Hs=class extends Us{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Ws(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Ws(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Ws(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());return null!=e?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 i(null!==t),!!Ts.some(i=>i.supports(t,e))||!!e.codec.startsWith("pcm-")||"undefined"!=typeof AudioDecoder&&!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ht))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}},js=e=>-(e??-1/0),$s=e=>-e,Ks=e=>{if("object"!=typeof e||!e)throw new TypeError("query must be an object.");if(void 0!==e.filter&&"function"!=typeof e.filter)throw new TypeError("query.filter, when provided, must be a function.");if(void 0!==e.sortBy&&"function"!=typeof e.sortBy)throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:e.filter?t=>{const i=e=>{if("boolean"!=typeof e)throw new TypeError("query.filter must return or resolve to a boolean.");return e},r=e.filter(t);return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if(!("number"==typeof e||Array.isArray(e)&&e.every(e=>"number"==typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return r instanceof Promise?r.then(i):i(r)}:void 0}},Xs=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return r instanceof Promise?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return r instanceof Promise||a instanceof Promise?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),Gs=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){const t=await Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!t?.sortBy)return i;const r=i.map(e=>t.sortBy(e)),a=r.some(e=>e instanceof Promise)?await Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{const i=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(i.length,r.length);for(let s=0;s<a;s++){const e=i[s]??0,t=r[s]??0;if(e!==t)return e-t}return 0}).map(e=>e.track)};re();var Qs=null;"undefined"!=typeof FinalizationRegistry&&(Qs=new FinalizationRegistry(e=>{for(const t of e)t.freed||t.free()}));var Ys,Js,Zs=class e extends ue{get disposed(){return this._disposed}constructor(t){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=/* @__PURE__ */new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(!Array.isArray(t.formats)||t.formats.some(e=>!(e instanceof sa)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(t.source instanceof Or||t.source instanceof Nr))throw new TypeError("options.source must be a Source or SourceRef.");if(t.source instanceof Or&&t.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==t.initInput&&!(t.initInput instanceof e))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==t.formatOptions&&((e,t)=>{if(!e||"object"!=typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!=typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!=typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}})(t.formatOptions,"formatOptions"),this._formats=t.formats,this._initInput=t.initInput??null,this._formatOptions=t.formatOptions??{},t.source instanceof Or?this._rootRef=t.source.ref():this._rootRef=t.source,this._sourceRefs.push(this._rootRef),Qs?.register(this,this._sourceRefs,this)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){i(this._rootSource instanceof Lr);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){const r=this._sourceCache.find(i=>i.cacheGroup===t&&Ur(i.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const a=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Ur(i.request,e));if(a)return a.promise.then(e=>e.sourceRef.source.ref());const s=(async()=>{const r=await this._getSourceUncached(e);if(ne(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=oe(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);i(-1!==e);const r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),((e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)})(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);const a=this._sourceCachePromises.findIndex(t=>t.request===e);return i(-1!==a),this._sourceCachePromises.splice(a,1),{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader=new rn(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats)if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new en})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),i(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof en)return!1;throw e}}async getFirstTimestamp(e){e??=await this.getTracks();const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=await Promise.all(t.map(e=>e.getFirstTimestamp()));return Math.min(...i)}async computeDuration(e,t){e??=await this.getTracks();const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=await Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??=await this.getTracks();const i=e.filter(e=>null!==e),r=(await Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)}async getTracks(e){return e&&=Ks(e),Gs((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=Ks(e),Gs((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=Ks(e),Gs((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){e&&=Ks(e);const t=Xs(e,{sortBy:async e=>[$s((await e.getDisposition()).default),$s(await e.hasPairableAudioTrack()),$s(!(await e.hasOnlyKeyPackets())),js(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=Ks(e);const t=await this.getPrimaryVideoTrack(),i=Xs(e,{sortBy:async e=>[$s(!t||e.canBePairedWith(t)),$s((await e.getDisposition()).default),js(await e.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 i="video"===e.getType()?new qs(this,e):new Hs(this,e);return this._backingToTrack.set(e,i),i}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,Qs?.unregister(this),this._demuxerPromise?.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}},en=class extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}},tn=class extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}},rn=class{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)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 tn;if(e<0)return null;if(null!==this.fileSizeNonStrict&&e+t>this.fileSizeNonStrict)return null;if(0===t){const t=new Uint8Array(0);return new an(t,d(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,zr);return r instanceof Promise?r.then(t=>t?new an(t.bytes,t.view,t.offset,e,i):null):r?new an(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new tn;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,D(this.fileSizeNonStrict-e,t,r));{const a=this.requestSlice(e,r),s=a=>a||(i(null!==this.fileSizeNonStrict),this.requestSlice(e,D(this.fileSizeNonStrict-e,t,r)));return a instanceof Promise?a.then(s):s(a)}}requestEntireFile(){return null!==this.fileSizeNonStrict?this.requestSlice(0,this.fileSizeNonStrict):(async()=>{const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);const i=1024*e.length;let r=this.requestSliceRange(i,0,1024);if(r instanceof Promise&&(r=await r),!r)break;e.push(nn(r,r.length)),t+=r.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new an(i,d(i),0,0,t)})()}},an=class e{constructor(e,t,i,r,a){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=a,this.bufferPos=r-i}static tempFromBytes(t){return new e(t,d(t),0,0,t.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(t,i=this.end-t){if(t<this.start||t+i>this.end)throw new RangeError("Slicing outside of original slice.");return new e(this.bytes,this.view,this.offset,t,t+i)}},sn=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw new RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},nn=(e,t)=>{sn(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},on=e=>(sn(e,1),e.view.getUint8(e.bufferPos++)),cn=(e,t)=>{sn(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},ln=e=>{sn(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},dn=e=>{sn(e,3);const t=R(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},un=e=>{sn(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},hn=(e,t)=>{sn(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},mn=e=>{sn(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},fn=e=>{sn(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},pn=e=>{sn(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},gn=(e,t)=>{let i,r;return t?(i=hn(e,!0),r=hn(e,!0)):(r=hn(e,!1),i=hn(e,!1)),4294967296*r+i},kn=e=>4294967296*mn(e)+mn(e),wn=e=>4294967296*pn(e)+mn(e),bn=e=>{const t=fn(e);return 4294967296*(e=>{sn(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e)+t},yn=e=>{sn(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Tn=e=>{sn(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Sn=(e,t)=>{sn(e,t);let i="";for(let r=0;r<t;r++)i+=String.fromCharCode(e.bytes[e.bufferPos++]);return i},vn=(e,t,i)=>u.decode(nn(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}(Ys||(Ys={})),function(e){e[e.ISO_8859_1=0]="ISO_8859_1",e[e.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",e[e.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",e[e.UTF_8=3]="UTF_8"}(Js||(Js={}));var Pn=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],Cn=(e,t)=>{const i=e.filePos;t.raw??={},t.raw.TAG??=nn(e,125),e.filePos=i;const r=xn(e,30);r&&(t.title??=r);const a=xn(e,30);a&&(t.artist??=a);const s=xn(e,30);s&&(t.album??=s);const n=xn(e,4),o=Number.parseInt(n,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(o,0,1));const c=nn(e,30);let l;if(0===c[28]&&0!==c[29]){const i=c[29];i>0&&(t.trackNumber??=i),e.skip(-30),l=xn(e,28),e.skip(2)}else e.skip(-30),l=xn(e,30);l&&(t.comment??=l);const d=on(e);d<Pn.length&&(t.genre??=Pn[d])},xn=(e,t)=>{const i=nn(e,t),r=Z(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n<a.length;n++)s+=String.fromCharCode(a[n]);return s.trimEnd()},In=e=>{const t=e.filePos,i=Sn(e,3),r=on(e),a=on(e),s=on(e),n=mn(e);return"ID3"!==i||255===r||255===a||2155905152&n?(e.filePos=t,null):{majorVersion:r,revision:a,flags:s,size:Qe(n)}},En=(e,t,i)=>{if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const r=new _n(t,nn(e,t.size));if(t.flags&Ys.Footer&&r.removeFooter(),t.flags&Ys.Unsynchronisation&&3===t.majorVersion&&r.ununsynchronizeAll(),t.flags&Ys.ExtendedHeader){const e=r.readU32();3===t.majorVersion?r.pos+=e:r.pos+=e-4}for(;r.pos<=r.bytes.length-r.frameHeaderSize();){const e=r.readId3V2Frame();if(!e)break;const a=r.pos,s=r.pos+e.size;let n=!1,o=!1,c=!1;if(3===t.majorVersion?(n=!!(64&e.flags),o=!!(128&e.flags)):4===t.majorVersion&&(n=!!(4&e.flags),o=!!(8&e.flags),c=!!(2&e.flags)||!!(t.flags&Ys.Unsynchronisation)),n)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),r.pos=s;else if(o)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),r.pos=s;else{if(c&&r.ununsynchronizeRegion(r.pos,s),i.raw??={},"TXXX"===e.id){const e=i.raw.TXXX??={},t=r.readId3V2TextEncoding(),a=r.readId3V2Text(t,s),n=r.readId3V2Text(t,s);e[a]??=n}else"T"===e.id[0]?i.raw[e.id]??=r.readId3V2EncodingAndText(s):i.raw[e.id]??=r.readBytes(e.size);switch(r.pos=a,e.id){case"TIT2":case"TT2":i.title??=r.readId3V2EncodingAndText(s);break;case"TIT3":case"TT3":i.description??=r.readId3V2EncodingAndText(s);break;case"TPE1":case"TP1":i.artist??=r.readId3V2EncodingAndText(s);break;case"TALB":case"TAL":i.album??=r.readId3V2EncodingAndText(s);break;case"TPE2":case"TP2":i.albumArtist??=r.readId3V2EncodingAndText(s);break;case"TRCK":case"TRK":{const e=r.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.trackNumber??=t),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"TPOS":case"TPA":{const e=r.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.discNumber??=t),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}break;case"TCON":case"TCO":{const e=r.readId3V2EncodingAndText(s);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Pn[e]){i.genre??=Pn[e];break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Pn[e]){i.genre??=Pn[e];break}}i.genre??=e}break;case"TDRC":case"TDAT":{const e=r.readId3V2EncodingAndText(s),t=new Date(e);Number.isNaN(t.getTime())||(i.date??=t)}break;case"TYER":case"TYE":{const e=r.readId3V2EncodingAndText(s),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??=new Date(t,0,1))}break;case"USLT":case"ULT":{const e=r.readU8();r.pos+=3,r.readId3V2Text(e,s),i.lyrics??=r.readId3V2Text(e,s)}break;case"COMM":case"COM":{const e=r.readU8();r.pos+=3,r.readId3V2Text(e,s),i.comment??=r.readId3V2Text(e,s)}break;case"APIC":case"PIC":{const e=r.readId3V2TextEncoding();let a;if(2===t.majorVersion){const e=r.readAscii(3);a="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else a=r.readId3V2Text(e,s);const n=r.readU8(),o=r.readId3V2Text(e,s).trimEnd(),c=s-r.pos;if(c>=0){const e=r.readBytes(c);i.images||(i.images=[]),i.images.push({data:e,mimeType:a,kind:3===n?"coverFront":4===n?"coverBack":"unknown",description:o})}}break;default:r.pos+=e.size}r.pos=s}}},_n=class{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const i=this.bytes[t];e.push(i),255===i&&t!==this.bytes.length-1&&0===this.bytes[t]&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const i=[];for(let s=e;s<t;s++){const e=this.bytes[s];i.push(e),255===e&&s!==t-1&&0===this.bytes[s+1]&&s++}const r=this.bytes.subarray(0,e),a=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+i.length+a.length),this.bytes.set(r,0),this.bytes.set(i,r.length),this.bytes.set(a,r.length+i.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-10),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,256*e+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(2===this.header.majorVersion){const e=this.readAscii(3);return"\0\0\0"===e?null:{id:e,size:this.readU24(),flags:0}}{const e=this.readAscii(4);if("\0\0\0\0"===e)return null;const t=this.readU32();let i=4===this.header.majorVersion?Qe(t):t;const r=this.readU16(),a=this.pos,s=e=>{const t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;const t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!s(i)){const e=4===this.header.majorVersion?t:Qe(t);s(e)&&(i=e)}return this.pos=a,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case Js.ISO_8859_1:{let e="";for(let t=0;t<r.length;t++){const a=r[t];if(0===a){this.pos=i+t+1;break}e+=String.fromCharCode(a)}return e}case Js.UTF_16_WITH_BOM:if(255===r[0]&&254===r[1]){const e=new TextDecoder("utf-16le"),t=Z(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2==0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(254===r[0]&&255===r[1]){const e=new TextDecoder("utf-16be"),t=Z(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2==0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{const e=Z(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),u.decode(r.subarray(0,e))}case Js.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Z(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2==0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case Js.UTF_8:{const e=Z(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),u.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}},Bn=class{constructor(e){this.mutex=new T,this.trackTimestampInfo=/* @__PURE__ */new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&t<r.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 ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!i)throw new Error("First packet must be a key packet.");r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}},An=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,Rn=e=>{const t=Math.floor(e/36e5),i=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3),a=e%1e3;return t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")},Fn=class{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=/* @__PURE__ */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 a of e.children)a&&this.writeBox(a);const i=this.writer.getPos(),r=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,r),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);i(void 0!==t);const r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}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}}},Mn=/* @__PURE__ */new Uint8Array(8),Dn=/* @__PURE__ */new DataView(Mn.buffer),zn=e=>[(e%256+256)%256],On=e=>(Dn.setUint16(0,e,!1),[Mn[0],Mn[1]]),Nn=e=>(Dn.setInt16(0,e,!1),[Mn[0],Mn[1]]),Ln=e=>(Dn.setUint32(0,e,!1),[Mn[1],Mn[2],Mn[3]]),Un=e=>(Dn.setUint32(0,e,!1),[Mn[0],Mn[1],Mn[2],Mn[3]]),Wn=e=>(Dn.setInt32(0,e,!1),[Mn[0],Mn[1],Mn[2],Mn[3]]),Vn=e=>(Dn.setUint32(0,Math.floor(e/2**32),!1),Dn.setUint32(4,e,!1),[Mn[0],Mn[1],Mn[2],Mn[3],Mn[4],Mn[5],Mn[6],Mn[7]]),qn=e=>(Dn.setInt32(0,Math.floor(e/2**32),!1),Dn.setUint32(4,e,!1),[Mn[0],Mn[1],Mn[2],Mn[3],Mn[4],Mn[5],Mn[6],Mn[7]]),Hn=e=>(Dn.setInt16(0,256*e,!1),[Mn[0],Mn[1]]),jn=e=>(Dn.setInt32(0,65536*e,!1),[Mn[0],Mn[1],Mn[2],Mn[3]]),$n=e=>(Dn.setInt32(0,2**30*e,!1),[Mn[0],Mn[1],Mn[2],Mn[3]]),Kn=(e,t)=>{const i=[];let r=e;do{let e=127&r;r>>=7,i.length>0&&(e|=128),i.push(e),void 0!==t&&t--}while(r>0||t);return i.reverse()},Xn=(e,t=!1)=>{const i=Array(e.length).fill(null).map((t,i)=>e.charCodeAt(i));return t&&i.push(0),i},Gn=e=>{const t=e*(Math.PI/180),i=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[i,r,0,-r,i,0,0,0,1]},Qn=/* @__PURE__ */Gn(0),Yn=e=>[jn(e[0]),jn(e[1]),$n(e[2]),jn(e[3]),jn(e[4]),$n(e[5]),jn(e[6]),jn(e[7]),$n(e[8])],Jn=(e,t,i)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:i}),Zn=(e,t,i,r,a)=>Jn(e,[zn(t),Ln(i),r??[]],a),eo=()=>Jn("styp",[Xn("iso5"),Un(0),Xn("iso5"),Xn("iso6"),Xn("mp41"),Xn("cmfc"),Xn("dash")]),to=(e,t)=>{let i=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(i)||(i=0),Zn("sidx",1,0,[Un(1),Un(xc),Vn(Ec(e.minWrittenTimestamp,xc)),Vn(0),On(0),On(1),Un(2147483647&t),Un(Ec(i,xc)),Un(0)])},io=e=>({type:"mdat",largeSize:e}),ro=e=>Jn("moov",void 0,[ao(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>no(t,e.creationTime)),e.isFragmented?Ho(e.trackDatas):null,rc(e)]),ao=(e,t)=>{const i=Math.max(0,...t.map(e=>Ec(so(e),xc)+Ec(e.startTimestampOffset??0,xc))),r=Math.max(0,...t.map(e=>e.track.id))+1,a=!n(e)||!n(i),s=a?Vn:Un;return Zn("mvhd",+a,0,[s(e),s(e),Un(xc),s(i),jn(1),Hn(1),Array(10).fill(0),Yn(Qn),Array(24).fill(0),Un(r)])},so=e=>{if(0===e.samples.length)return 0;let t=1/0,i=-1/0;for(let r=0;r<e.samples.length;r++){const a=e.samples[r];a.timestamp<t&&(t=a.timestamp),a.timestamp+a.duration>i&&(i=a.timestamp+a.duration)}return t===1/0?0:i-t},no=(e,t)=>{const i=Ic(e),r=null!==e.startTimestampOffset&&e.startTimestampOffset>0;return Jn("trak",void 0,[oo(e,t),r?co(e,e.startTimestampOffset):null,lo(e,t),void 0!==i.name?Jn("udta",void 0,[Jn("name",[...h.encode(i.name)])]):null])},oo=(e,t)=>{const i=Ec(so(e),xc)+Ec(e.startTimestampOffset??0,xc),r=!n(t)||!n(i),a=r?Vn:Un;let s;if("video"===e.type){const t=e.track.metadata.rotation;s=Gn(t??0)}else s=Qn;let o=2;return!1!==e.track.metadata.disposition?.default&&(o|=1),Zn("tkhd",+r,o,[a(t),a(t),Un(e.track.id),Un(0),a(i),Array(8).fill(0),On(0),On(e.track.id),Hn("audio"===e.type?1:0),On(0),Yn(s),jn("video"===e.type?e.info.width:0),jn("video"===e.type?e.info.height:0)])},co=(e,t)=>{const i=Ec(t,xc),r=Ec(so(e),xc),a=!n(i)||!n(r),s=a?Vn:Un,o=a?qn:Wn;return Jn("edts",void 0,[Zn("elst",a?1:0,0,[Un(2),s(i),o(-1),jn(1),s(r),o(0),jn(1)])])},lo=(e,t)=>Jn("mdia",void 0,[uo(e,t),fo(!0,ho[e.type],mo[e.type]),po(e)]),uo=(e,t)=>{const i=Ec(so(e),e.timescale),r=!n(t)||!n(i),a=r?Vn:Un;return Zn("mdhd",+r,0,[a(t),a(t),Un(e.timescale),a(i),On(kc(e.track.metadata.languageCode??"und")),On(0)])},ho={video:"vide",audio:"soun",subtitle:"text"},mo={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},fo=(e,t,i,r="\0\0\0\0")=>Zn("hdlr",0,0,[e?Xn("mhlr"):Un(0),Xn(t),Xn(r),Un(0),Un(0),Xn(i,!0)]),po=e=>Jn("minf",void 0,[go[e.type](),ko(),yo(e)]),go={video:()=>Zn("vmhd",0,1,[On(0),On(0),On(0),On(0)]),audio:()=>Zn("smhd",0,0,[On(0),On(0)]),subtitle:()=>Zn("nmhd",0,0)},ko=()=>Jn("dinf",void 0,[wo()]),wo=()=>Zn("dref",0,0,[Un(1)],[bo()]),bo=()=>Zn("url ",0,1),yo=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return Jn("stbl",void 0,[To(e),Oo(e),t?Vo(e):null,t?qo(e):null,Lo(e),Uo(e),Wo(e),No(e)])},To=e=>{let t;if("video"===e.type)t=So(uc(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){const r=mc(e.track.source._codec,e.muxer.isQuickTime);i(r),t=xo(r,e)}else"subtitle"===e.type&&(t=zo(pc[e.track.source._codec],e));return i(t),Zn("stsd",0,0,[Un(1)],[t])},So=(e,t)=>{return Jn(e,[Array(6).fill(0),On(1),On(0),On(0),Array(12).fill(0),On(t.info.width),On(t.info.height),Un(4718592),Un(4718592),Un(0),On(1),Array(32).fill(0),On(24),Nn(65535)],[hc[t.track.source._codec](t),vo(t),(i=t.info.decoderConfig.colorSpace,i&&i.primaries&&i.transfer&&i.matrix&&void 0!==i.fullRange?Po(t):null)]);var i},vo=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:Jn("pasp",[Un(e.info.pixelAspectRatio.num),Un(e.info.pixelAspectRatio.den)]),Po=e=>Jn("colr",[Xn("nclx"),On(f[e.info.decoderConfig.colorSpace.primaries]),On(g[e.info.decoderConfig.colorSpace.transfer]),On(w[e.info.decoderConfig.colorSpace.matrix]),zn((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),Co=e=>{if(!e.info.decoderConfig)return null;const t=e.info.decoderConfig,i=t.codec.split("."),r=Number(i[1]),a=Number(i[2]),s=(Number(i[3])<<4)+((i[4]?Number(i[4]):1)<<1)+(i[8]?Number(i[8]):Number(t.colorSpace?.fullRange??0)),n=i[5]?Number(i[5]):t.colorSpace?.primaries?f[t.colorSpace.primaries]:2,o=i[6]?Number(i[6]):t.colorSpace?.transfer?g[t.colorSpace.transfer]:2,c=i[7]?Number(i[7]):t.colorSpace?.matrix?w[t.colorSpace.matrix]:2;return Zn("vpcC",1,0,[zn(r),zn(a),zn(s),zn(n),zn(o),zn(c),On(0)])},xo=(e,t)=>{let i,r=0,a=16;const s=Pe.includes(t.track.source._codec);if(s){const e=t.track.source._codec,{sampleSize:i}=Ne(e);a=8*i,a>16&&(r=1)}if(t.muxer.isQuickTime&&(r=1),0===r)i=[Array(6).fill(0),On(1),On(r),On(0),Un(0),On(t.info.numberOfChannels),On(a),On(0),On(0),On(t.info.sampleRate<65536?t.info.sampleRate:0),On(0)];else{const e=s?0:-2;i=[Array(6).fill(0),On(1),On(r),On(0),Un(0),On(t.info.numberOfChannels),On(Math.min(a,16)),Nn(e),On(0),On(t.info.sampleRate<65536?t.info.sampleRate:0),On(0),s?[Un(1),Un(a/8),Un(t.info.numberOfChannels*a/8)]:[Un(0),Un(0),Un(0)],Un(2)]}return Jn(e,i,[fc(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},Io=e=>{let t;switch(e.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw new Error(`Unhandled audio codec: ${e.track.source._codec}`)}let i=[...zn(t),...zn(21),...Ln(0),...Un(0),...Un(0)];if(e.info.decoderConfig.description){const t=l(e.info.decoderConfig.description);i=[...i,...zn(5),...Kn(t.byteLength),...t]}return i=[...On(1),...zn(0),...zn(4),...Kn(i.length),...i,...zn(6),...zn(1),...zn(2)],i=[...zn(3),...Kn(i.length),...i],Zn("esds",0,0,i)},Eo=e=>Jn("wave",void 0,[_o(e),Bo(e),Jn("\0\0\0\0")]),_o=e=>Jn("frma",[Xn(mc(e.track.source._codec,e.muxer.isQuickTime))]),Bo=e=>{const{littleEndian:t}=Ne(e.track.source._codec);return Jn("enda",[On(+t)])},Ao=e=>{let t=e.info.numberOfChannels,r=3840,a=e.info.sampleRate,s=0,n=0,o=new Uint8Array(0);const c=e.info.decoderConfig?.description;if(c){i(c.byteLength>=18);const e=_t(l(c));t=e.outputChannelCount,r=e.preSkip,a=e.inputSampleRate,s=e.outputGain,n=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return Jn("dOps",[zn(0),zn(t),On(r),Un(a),Nn(s),zn(n),...o])},Ro=e=>{const t=e.info.decoderConfig?.description;return i(t),Zn("dfLa",0,0,[...l(t).subarray(4)])},Fo=e=>{const{littleEndian:t,sampleSize:i}=Ne(e.track.source._codec);return Zn("pcmC",0,0,[zn(+t),zn(8*i)])},Mo=e=>{const t=zt(e.info.firstPacket.data);if(!t)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 i=new Uint8Array(3),r=new we(i);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCode),r.writeBits(5,0),Jn("dac3",[...i])},Do=e=>{const t=Lt(e.info.firstPacket.data);if(!t)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 i=16;for(const n of t.substreams)i+=23,n.numDepSub>0?i+=9:i+=1;const r=Math.ceil(i/8),a=new Uint8Array(r),s=new we(a);s.writeBits(13,t.dataRate),s.writeBits(3,t.substreams.length-1);for(const n of t.substreams)s.writeBits(2,n.fscod),s.writeBits(5,n.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,n.bsmod),s.writeBits(3,n.acmod),s.writeBits(1,n.lfeon),s.writeBits(3,0),s.writeBits(4,n.numDepSub),n.numDepSub>0?s.writeBits(9,n.chanLoc):s.writeBits(1,0);return Jn("dec3",[...a])},zo=(e,t)=>Jn(e,[Array(6).fill(0),On(1)],[gc[t.track.source._codec](t)]),Oo=e=>Zn("stts",0,0,[Un(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[Un(e.sampleCount),Un(e.sampleDelta)])]),No=e=>{if(e.samples.every(e=>"key"===e.type))return null;const t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return Zn("stss",0,0,[Un(t.length),t.map(([e])=>Un(e+1))])},Lo=e=>Zn("stsc",0,0,[Un(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[Un(e.firstChunk),Un(e.samplesPerChunk),Un(1)])]),Uo=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){const{sampleSize:t}=Ne(e.track.source._codec);return Zn("stsz",0,0,[Un(t*e.info.numberOfChannels),Un(e.samples.reduce((t,i)=>t+Ec(i.duration,e.timescale),0))])}return Zn("stsz",0,0,[Un(0),Un(e.samples.length),e.samples.map(e=>Un(e.size))])},Wo=e=>e.finalizedChunks.length>0&&s(e.finalizedChunks).offset>=2**32?Zn("co64",0,0,[Un(e.finalizedChunks.length),e.finalizedChunks.map(e=>Vn(e.offset))]):Zn("stco",0,0,[Un(e.finalizedChunks.length),e.finalizedChunks.map(e=>Un(e.offset))]),Vo=e=>Zn("ctts",1,0,[Un(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[Un(e.sampleCount),Wn(e.sampleCompositionTimeOffset)])]),qo=e=>{let t=1/0,r=-1/0,a=1/0,s=-1/0;i(e.compositionTimeOffsetTable.length>0),i(e.samples.length>0);for(let i=0;i<e.compositionTimeOffsetTable.length;i++){const a=e.compositionTimeOffsetTable[i];t=Math.min(t,a.sampleCompositionTimeOffset),r=Math.max(r,a.sampleCompositionTimeOffset)}for(let i=0;i<e.samples.length;i++){const t=e.samples[i];a=Math.min(a,Ec(t.timestamp,e.timescale)),s=Math.max(s,Ec(t.timestamp+t.duration,e.timescale))}const n=Math.max(-t,0);return s>=2**31?null:Zn("cslg",0,0,[Wn(n),Wn(t),Wn(r),Wn(a),Wn(s)])},Ho=e=>Jn("mvex",void 0,e.map(jo)),jo=e=>Zn("trex",0,0,[Un(e.track.id),Un(1),Un(0),Un(0),Un(0)]),$o=(e,t)=>Jn("moof",void 0,[Ko(e),...t.map(Go)]),Ko=e=>Zn("mfhd",0,0,[Un(e)]),Xo=e=>{let t=0,i=0;const r="delta"===e.type;return i|=+r,t|=r?1:2,t<<24|i<<16},Go=e=>Jn("traf",void 0,[Qo(e),Yo(e),Jo(e)]),Qo=e=>{i(e.currentChunk);let t=0;t|=8,t|=16,t|=32,t|=131072;const r=e.currentChunk.samples[1]??e.currentChunk.samples[0],a={duration:r.timescaleUnitsToNextSample,size:r.size,flags:Xo(r)};return Zn("tfhd",0,131128,[Un(e.track.id),Un(a.duration),Un(a.size),Un(a.flags)])},Yo=e=>(i(e.currentChunk),Zn("tfdt",1,0,[Vn(Ec(e.currentChunk.startTimestamp,e.timescale))])),Jo=e=>{i(e.currentChunk);const t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),r=e.currentChunk.samples.map(e=>e.size),a=e.currentChunk.samples.map(Xo),s=e.currentChunk.samples.map(t=>Ec(t.timestamp-t.decodeTimestamp,e.timescale)),n=new Set(t),o=new Set(r),c=new Set(a),l=new Set(s),d=2===c.size&&a[0]!==a[1],u=n.size>1,h=o.size>1,m=!d&&c.size>1,f=l.size>1||[...l].some(e=>0!==e);let p=0;return p|=1,p|=4*+d,p|=256*+u,p|=512*+h,p|=1024*+m,p|=2048*+f,Zn("trun",1,p,[Un(e.currentChunk.samples.length),Un(e.currentChunk.offset-e.currentChunk.moofOffset||0),d?Un(a[0]):[],e.currentChunk.samples.map((e,i)=>[u?Un(t[i]):[],h?Un(r[i]):[],m?Un(a[i]):[],f?Wn(s[i]):[]])])},Zo=(e,t)=>Zn("tfra",1,0,[Un(e.track.id),Un(63),Un(e.finalizedChunks.length),e.finalizedChunks.map(i=>[Vn(Ec(i.samples[0].timestamp,e.timescale)),Vn(i.moofOffset),Un(t+1),Un(1),Un(1)])]),ec=()=>Jn("vtte"),tc=(e,t,i,r,a)=>Jn("vttc",void 0,[null!==a?Jn("vsid",[Wn(a)]):null,null!==i?Jn("iden",[...h.encode(i)]):null,null!==t?Jn("ctim",[...h.encode(Rn(t))]):null,null!==r?Jn("sttg",[...h.encode(r)]):null,Jn("payl",[...h.encode(e)])]),ic=e=>Jn("vtta",[...h.encode(e)]),rc=e=>{const t=[],i=e.format._options.metadataFormat??"auto",r=e.output._metadataTags;if("mdir"===i||"auto"===i&&!e.isQuickTime){const e=cc(r);e&&t.push(e)}else if("mdta"===i){const e=lc(r);e&&t.push(e)}else("udta"===i||"auto"===i&&e.isQuickTime)&&ac(t,e.output._metadataTags);return 0===t.length?null:Jn("udta",void 0,t)},ac=(e,t)=>{for(const{key:i,value:r}of te(t))switch(i){case"title":e.push(sc("©nam",r));break;case"description":e.push(sc("©des",r));break;case"artist":e.push(sc("©ART",r));break;case"album":e.push(sc("©alb",r));break;case"albumArtist":e.push(sc("albr",r));break;case"genre":e.push(sc("©gen",r));break;case"date":e.push(sc("©day",r.toISOString().slice(0,10)));break;case"comment":e.push(sc("©cmt",r));break;case"lyrics":e.push(sc("©lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:A(i)}if(t.raw)for(const i in t.raw){const r=t.raw[i];null==r||4!==i.length||e.some(e=>e.type===i)||("string"==typeof r?e.push(sc(i,r)):r instanceof Uint8Array&&e.push(Jn(i,Array.from(r))))}},sc=(e,t)=>{const i=h.encode(t);return Jn(e,[On(i.length),On(kc("und")),Array.from(i)])},nc={"image/jpeg":13,"image/png":14,"image/bmp":27},oc=(e,t)=>{const i=[];for(const{key:r,value:a}of te(e))switch(r){case"title":i.push({key:t?"title":"©nam",value:dc(a)});break;case"description":i.push({key:t?"description":"©des",value:dc(a)});break;case"artist":i.push({key:t?"artist":"©ART",value:dc(a)});break;case"album":i.push({key:t?"album":"©alb",value:dc(a)});break;case"albumArtist":i.push({key:t?"album_artist":"aART",value:dc(a)});break;case"comment":i.push({key:t?"comment":"©cmt",value:dc(a)});break;case"genre":i.push({key:t?"genre":"©gen",value:dc(a)});break;case"lyrics":i.push({key:t?"lyrics":"©lyr",value:dc(a)});break;case"date":i.push({key:t?"date":"©day",value:dc(a.toISOString().slice(0,10))});break;case"images":for(const e of a)"coverFront"===e.kind&&i.push({key:"covr",value:Jn("data",[Un(nc[e.mimeType]??0),Un(0),Array.from(e.data)])});break;case"trackNumber":if(t){const t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();i.push({key:"track",value:dc(t)})}else i.push({key:"trkn",value:Jn("data",[Un(0),Un(0),On(0),On(a),On(e.tracksTotal??0),On(0)])});break;case"discNumber":t||i.push({key:"disc",value:Jn("data",[Un(0),Un(0),On(0),On(a),On(e.discsTotal??0),On(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:A(r)}if(e.raw)for(const r in e.raw){const a=e.raw[r];null==a||!t&&4!==r.length||i.some(e=>e.key===r)||("string"==typeof a?i.push({key:r,value:dc(a)}):a instanceof Uint8Array?i.push({key:r,value:Jn("data",[Un(0),Un(0),Array.from(a)])}):a instanceof fe&&i.push({key:r,value:Jn("data",[Un(nc[a.mimeType]??0),Un(0),Array.from(a.data)])}))}return i},cc=e=>{const t=oc(e,!1);return 0===t.length?null:Zn("meta",0,0,void 0,[fo(!1,"mdir","","appl"),Jn("ilst",void 0,t.map(e=>Jn(e.key,void 0,[e.value])))])},lc=e=>{const t=oc(e,!0);return 0===t.length?null:Jn("meta",void 0,[fo(!1,"mdta",""),Zn("keys",0,0,[Un(t.length)],t.map(e=>Jn("mdta",[...h.encode(e.key)]))),Jn("ilst",void 0,t.map((e,t)=>Jn(String.fromCharCode(...Un(t+1)),void 0,[e.value])))])},dc=e=>Jn("data",[Un(1),Un(0),...h.encode(e)]),uc=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},hc={avc:e=>e.info.decoderConfig&&Jn("avcC",[...l(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&Jn("hvcC",[...l(e.info.decoderConfig.description)]),vp8:Co,vp9:Co,av1:e=>Jn("av1C",(e=>{const t=e.split("."),i=Number(t[1]),r=t[2];return[129,(i<<5)+Number(r.slice(0,-1)),(("H"===r.slice(-1)?1:0)<<7)+((8===Number(t[3])?0:1)<<6)+0+((t[4]?Number(t[4]):0)<<4)+((t[5]?Number(t[5][0]):1)<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]})(e.info.decoderConfig.codec))},mc=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";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"}if(t)switch(e){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},fc=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return Io;case"opus":return Ao;case"flac":return Ro;case"ac3":return Mo;case"eac3":return Do}if(t)switch(e){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Eo}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return Fo}return null},pc={webvtt:"wvtt"},gc={webvtt:e=>Jn("vttC",[...h.encode(e.info.config.description)])},kc=e=>{i(3===e.length);let t=0;for(let i=0;i<3;i++)t<<=5,t+=e.charCodeAt(i)-96;return t},wc=class{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(){i(!this.started),this.target._start(),this.started=!0}write(e){i(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 i(this.started&&!this.finalized),this.target._flush()}async finalize(){i(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 r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){const e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),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 e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}},bc=class extends ue{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){!1!==this._monotonicity&&(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 Pc(this,e)}},yc=65536,Tc=2**32,Sc=class extends bc{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||"object"!=typeof e)throw new TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==e.onFinalize&&"function"!=typeof e.onFinalize)throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in/* @__PURE__ */new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer(yc,{maxByteLength:Tc})}catch{this._buffer=new ArrayBuffer(yc),this._supportsResize=!1}else this._buffer=new ArrayBuffer(yc);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>Tc)throw new Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this._supportsResize)this._buffer.resize(t);else{const e=new ArrayBuffer(t),i=new Uint8Array(e);i.set(this._bytes,0),this._buffer=e,this._bytes=i}}}_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)}},vc=class extends bc{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}},Pc=class extends bc{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)}},Cc=class{constructor(e,t){if(this.rootPath=e,this.getTarget=t,"string"!=typeof e)throw new TypeError("rootPath must be a string.");if("function"!=typeof t)throw new TypeError("getTarget must be a function.")}},xc=57600,Ic=e=>{const t={},i=e.track;return void 0!==i.metadata.name&&(t.name=i.metadata.name),t},Ec=(e,t,i=!0)=>{const r=e*t;return i?Math.round(r):r},_c=class extends Bn{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Sc,this.auxWriter=new wc(this.auxTarget,!1),this.auxBoxWriter=new Fn(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=E(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof Gc,this.isCmaf=t instanceof Xc,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof Xc?1/0:1)}async start(){const e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>void 0!==this.format._options.fastStart?"fragmented"===this.format._options.fastStart:e instanceof Sc),this.boxWriter=new Fn(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Sc&&"in-memory"),this.isFragmented="fragmented"===this.fastStart),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 e=new wc(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new Fn(e)}const t=this.output._tracks.some(e=>e.isVideoTrack()&&"avc"===e.source._codec);{const e=this.initBoxWriter??this.boxWriter;if(i(e),this.format._options.onFtyp&&e.writer.startTrackingWrites(),e.writeBox((e=>{const t=512;return Jn("ftyp",e.isQuickTime?[Xn("qt "),Un(t),Xn("qt ")]:e.fragmented?e.cmaf?[Xn("iso5"),Un(t),Xn("iso5"),Xn("iso6"),Xn("mp41"),Xn("cmfc"),Xn("dash")]:[Xn("iso5"),Un(t),Xn("iso5"),Xn("iso6"),Xn("mp41")]:[Xn("isom"),Un(t),Xn("isom"),e.holdsAvc?Xn("avc1"):[],Xn("mp41")])})({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){const{data:t,start:i}=e.writer.stopTrackingWrites();this.format._options.onFtyp(t,i)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const i of this.output._tracks)if(void 0===i.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(i(this.writer),i(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=io(!0),this.boxWriter.writeBox(this.mdat));await(this.writer?.flush()),e()}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(e=>"video"===e.type||"audio"===e.type?e.info.decoderConfig.codec:{webvtt:"wvtt"}[e.track.source._codec]);return jt({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){const a=this.trackDatas.find(t=>t.track===e);if(a)return a;(e=>{if(!e)throw new TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!Ue.some(t=>e.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(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.displayAspectWidth&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(void 0!==e.decoderConfig.displayAspectHeight&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(void 0!==e.decoderConfig.displayAspectWidth!=(void 0!==e.decoderConfig.displayAspectHeight))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(void 0!==e.decoderConfig.description&&!y(e.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){const{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const i=Object.keys(f);if(null!=t.primaries&&!i.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);const r=Object.keys(g);if(null!=t.transfer&&!r.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const a=Object.keys(w);if(null!=t.matrix&&!a.includes(t.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!We.test(e.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(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!Ve.test(e.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(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!qe.test(e.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(e.decoderConfig.codec.startsWith("av01")&&!He.test(e.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/.')})(r),i(r),i(r.decoderConfig);const s={...r.decoderConfig};i(void 0!==s.codedWidth),i(void 0!==s.codedHeight);let n=!1;if("avc"!==e.source._codec||s.description){if("hevc"===e.source._codec&&!s.description){const e=kt(t.data);if(!e)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=(e=>{const t=[];t.push(e.configurationVersion),t.push((3&e.generalProfileSpace)<<6|(1&e.generalTierFlag)<<5|31&e.generalProfileIdc),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(255&e.generalProfileCompatibilityFlags),t.push(...e.generalConstraintIndicatorFlags),t.push(255&e.generalLevelIdc),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(255&e.minSpatialSegmentationIdc),t.push(252|3&e.parallelismType),t.push(252|3&e.chromaFormatIdc),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.avgFrameRate>>8&255),t.push(255&e.avgFrameRate),t.push((3&e.constantFrameRate)<<6|(7&e.numTemporalLayers)<<3|(1&e.temporalIdNested)<<2|3&e.lengthSizeMinusOne),t.push(255&e.arrays.length);for(const i of e.arrays){t.push((1&i.arrayCompleteness)<<7|63&i.nalUnitType),t.push(i.nalUnits.length>>8&255),t.push(255&i.nalUnits.length);for(const e of i.nalUnits){t.push(e.length>>8&255),t.push(255&e.length);for(let i=0;i<e.length;i++)t.push(e[i])}}return new Uint8Array(t)})(e),n=!0}}else{const e=dt(t.data);if(!e)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=(e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}t.push(e.pictureParameterSets.length);for(const i of e.pictureParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication){i(null!==e.chromaFormat),i(null!==e.bitDepthLumaMinus8),i(null!==e.bitDepthChromaMinus8),i(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length);for(const i of e.sequenceParameterSetExt){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}}return new Uint8Array(t)})(e),n=!0}const o=(e=>{const t=e<0?-1:1;let i=0,r=1,a=1,s=0,n=e=Math.abs(e);for(;;){const e=Math.floor(n),o=e*a+i,c=e*s+r;if(c>1e6)return{num:t*a,den:s};if(i=a,r=s,a=o,s=c,n=1/(n-e),!isFinite(n))break}return{num:t*a,den:s}})(1/(e.metadata.frameRate??57600)).den,c=s.displayAspectWidth,l=s.displayAspectHeight,d=void 0===c||void 0===l?{num:1,den:1}:ce({num:c*s.codedHeight,den:l*s.codedWidth}),u={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:n},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(u),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),u}getAudioTrackData(e,t,r){const a=this.trackDatas.find(t=>t.track===e);if(a)return a;(e=>{if(!e)throw new TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw new TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!je.some(t=>e.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(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!y(e.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.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(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&e.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(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!e.decoderConfig.description||e.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(e.decoderConfig.codec.startsWith("ac-3")||e.decoderConfig.codec.startsWith("ac3")){if("ac-3"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(e.decoderConfig.codec.startsWith("ec-3")||e.decoderConfig.codec.startsWith("eac3")){if("ec-3"!==e.decoderConfig.codec)throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!Pe.includes(e.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Pe.join(", ")}).`)})(r),i(r),i(r.decoderConfig);const s={...r.decoderConfig};let n=!1;if("aac"===e.source._codec&&!s.description){const e=ur(an.tempFromBytes(t.data));if(!e)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 i=be[e.samplingFrequencyIndex],r=ye[e.channelConfiguration];if(void 0===i||void 0===r)throw new Error("Invalid ADTS frame header.");s.description=Se({objectType:e.objectType,sampleRate:i,numberOfChannels:r}),n=!0}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&Pe.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:n,firstPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const r=this.trackDatas.find(t=>t.track===e);if(r)return r;(e=>{if(!e)throw new TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw new TypeError("Subtitle metadata must be an object.");if(!e.config)throw new TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw new TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw new TypeError("Subtitle metadata config description must be a string.")})(t),i(t),i(t.config);const a={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:/* @__PURE__ */new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,t,i){const r=await this.mutex.acquire();try{const r=this.getVideoTrackData(e,t,i);let a=t.data;if(r.info.requiresAnnexBTransformation){const e=[...it(a)].map(e=>a.subarray(e.offset,e.offset+e.length));if(0===e.length)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=lt(e,4)}this.validateTimestamp(r.track,t.timestamp,"key"===t.type);const s=this.createSampleForTrack(r,a,t.timestamp,t.duration,t.type);await this.registerSample(r,s)}finally{r()}}async addEncodedAudioPacket(e,t,i){const r=await this.mutex.acquire();try{const r=this.getAudioTrackData(e,t,i);let a=t.data;if(r.info.requiresAdtsStripping){const e=ur(an.tempFromBytes(a));if(!e)throw new Error("Expected ADTS frame, didn't get one.");const t=null===e.crcCheck?7:9;a=a.subarray(t)}this.validateTimestamp(r.track,t.timestamp,"key"===t.type);let s=t.timestamp,n=t.duration;if(r.info.requiresPcmTransformation){const e=Ne(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(n=a.byteLength/e/r.info.sampleRate,null!==r.info.expectedNextPcmPacketTimestamp){const e=s-r.info.expectedNextPcmPacketTimestamp;if(e<.01)s=r.info.expectedNextPcmPacketTimestamp;else{const t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);s=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=s+n}const o=this.createSampleForTrack(r,a,s,n,t.type);await this.registerSample(r,o)}finally{r()}}async padWithSilence(e,t,i){const r=Ec(i,e.timescale);if(i=r/e.timescale,r>0){const{sampleSize:a,silentValue:s}=Ne(e.info.decoderConfig.codec),n=r*e.info.numberOfChannels,o=new Uint8Array(a*n).fill(s),c=this.createSampleForTrack(e,new Uint8Array(o.buffer),t,i,"key");await this.registerSample(e,c)}return i}async addSubtitleCue(e,t,i){const r=await this.mutex.acquire();try{const r=this.getSubtitleTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,!0),"webvtt"===e.source._codec&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const r=/* @__PURE__ */new Set([]);for(const l of e.cueQueue)i(l.timestamp<=t),i(e.lastCueEndTimestamp<=l.timestamp+l.duration),r.add(Math.max(l.timestamp,e.lastCueEndTimestamp)),r.add(l.timestamp+l.duration);const a=[...r].sort((e,t)=>e-t),s=a[0],n=a[1]??s;if(t<n)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const t=ec();this.auxBoxWriter.writeBox(t);const i=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,i,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,r),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){const i=e.cueQueue[t];if(i.timestamp>=n)break;An.lastIndex=0;const r=An.test(i.text),a=i.timestamp+i.duration;let o=e.cueToSourceId.get(i);if(void 0===o&&n<a&&(o=e.nextSourceId++,e.cueToSourceId.set(i,o)),i.notes){const e=ic(i.notes);this.auxBoxWriter.writeBox(e)}const c=tc(i.text,r?s:null,i.identifier??null,i.settings??null,o??null);this.auxBoxWriter.writeBox(c),a===n&&e.cueQueue.splice(t--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,s,n-s,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=n}}createSampleForTrack(e,t,i,r,a){return{timestamp:i,decodeTimestamp:i,duration:r,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:Ec(r,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let i=0;i<e.timestampProcessingQueue.length;i++){const r=e.timestampProcessingQueue[i];t+=Ec(r.duration,e.timescale)}return 0===e.timeToSampleTable.length?e.timeToSampleTable.push({sampleCount:t,sampleDelta:1}):s(e.timeToSampleTable).sampleCount+=t,void(e.timestampProcessingQueue.length=0)}const r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=r[0]);for(let a=0;a<e.timestampProcessingQueue.length;a++){const t=e.timestampProcessingQueue[a];t.decodeTimestamp=r[a];const n=Ec(t.timestamp-t.decodeTimestamp,e.timescale),o=Ec(t.duration,e.timescale);if(null!==e.lastTimescaleUnits){i(e.lastSample);const r=Ec(t.decodeTimestamp,e.timescale,!1),a=Math.round(r-e.lastTimescaleUnits);if(i(a>=0),e.lastTimescaleUnits+=a,e.lastSample.timescaleUnitsToNextSample=a,!this.isFragmented){let t=s(e.timeToSampleTable);if(i(t),1===t.sampleCount){t.sampleDelta=a;const i=e.timeToSampleTable[e.timeToSampleTable.length-2];i&&i.sampleDelta===a&&(i.sampleCount++,e.timeToSampleTable.pop(),t=i)}else t.sampleDelta!==a&&(t.sampleCount--,e.timeToSampleTable.push(t={sampleCount:1,sampleDelta:a}));t.sampleDelta===o?t.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const r=s(e.compositionTimeOffsetTable);i(r),r.sampleCompositionTimeOffset===n?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else e.lastTimescaleUnits=Ec(t.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));e.lastSample=t}if(e.timestampProcessingQueue.length=0,i(e.lastSample),i(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){i("key"===t.type);const r=Ec(t.timestamp,e.timescale,!1),a=Math.round(r-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=a}}async registerSample(e,t){"key"===t.type&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),"reserve"===this.fastStart)){const t=e.track.metadata.maximumPacketCount;if(i(void 0!==t),e.samples.length>t)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const a=this.trackDatas.every(i=>{if(e===i)return"key"===t.type;const r=i.sampleQueue[0];return r?"key"===r.type:i.closed});i>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=i>=.5}else r=!0;r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),i(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(i(!this.isFragmented),i(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,i)=>t+Ec(i.duration,e.timescale),0)),0!==e.compactlyCodedChunkTable.length&&s(e.compactlyCodedChunkTable).samplesPerChunk===t||e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),"in-memory"!==this.fastStart){e.currentChunk.offset=this.writer.getPos();for(const t of e.currentChunk.samples)i(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}else e.currentChunk.offset=0}async interleaveSamples(e=!1){if(i(this.isFragmented),e||this.allTracksAreKnown())e:for(;;){let t=null,i=1/0;for(const a of this.trackDatas){if(!e&&0===a.sampleQueue.length&&!a.closed)break e;a.sampleQueue.length>0&&a.sampleQueue[0].timestamp<i&&(t=a,i=a.sampleQueue[0].timestamp)}if(!t)break;const r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){i(this.isFragmented);const t=this.nextFragmentNumber++;if(1===t){const e=this.initBoxWriter??this.boxWriter;i(e),this.format._options.onMoov&&e.writer.startTrackingWrites();const t=ro(this);if(e.writeBox(t),this.format._options.onMoov){const{data:t,start:i}=e.writer.stopTrackingWrites();this.format._options.onMoov(t,i)}if(this.isCmaf){i(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Fn(this.writer);const e=this.boxWriter.measureBox(eo()),t=this.boxWriter.measureBox(to(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}i(this.writer),i(this.boxWriter);const r=this.trackDatas.filter(e=>e.currentChunk),a=$o(t,r),s=this.writer.getPos(),n=s+this.boxWriter.measureBox(a);let o=n+8,c=1/0;for(const i of r){i.currentChunk.offset=o,i.currentChunk.moofOffset=s;for(const e of i.currentChunk.samples)o+=e.size;c=Math.min(c,i.currentChunk.startTimestamp)}const l=o-n,d=l>=2**32;if(d)for(const i of r)i.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const u=$o(t,r);if(this.boxWriter.writeBox(u),this.format._options.onMoof){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,c)}i(this.writer.getPos()===n),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=io(d);h.size=l,this.boxWriter.writeBox(h),this.writer.seek(n+(d?16:8));for(const i of r)for(const e of i.currentChunk.samples)this.writer.write(e.data),e.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(const i of r)i.finalizedChunks.push(i.currentChunk),this.finalizedChunks.push(i.currentChunk),i.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(i(this.writer),i(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){const e=ro(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;i(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=io(!0),this.boxWriter.writeBox(this.mdat);for(const i of this.trackDatas){for(const e of i.sampleQueue)await this.addSampleToTrack(i,e);i.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){i("reserve"===this.fastStart);let e=0;for(const t of this.trackDatas){const r=t.track.metadata.maximumPacketCount;i(void 0!==r),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){const t=await this.mutex.acquire(),i=this.trackDatas.find(t=>t.track===e);i&&(i.closed=!0,"subtitle"===i.type&&"webvtt"===e.source._codec&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const i of this.trackDatas)i.closed=!0,"subtitle"===i.type&&"webvtt"===i.track.source._codec&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const r of this.trackDatas){await this.finalizeCurrentChunk(r),i(null!==r.startTimestampOffset);for(let e=0;e<r.samples.length;e++){const t=r.samples[e];t.timestamp-=r.startTimestampOffset,t.decodeTimestamp-=r.startTimestampOffset}}if(i(this.writer),i(this.boxWriter),"in-memory"===this.fastStart){let e;this.mdat=io(!1);for(let r=0;r<2;r++){const t=ro(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+r+e;for(const s of this.finalizedChunks){s.offset=a;for(const{data:t}of s.samples)i(t),a+=t.byteLength,e+=t.byteLength}if(a<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const t=ro(this);if(this.boxWriter.writeBox(t),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat);for(const r of this.finalizedChunks)for(const e of r.samples)i(e.data),this.writer.write(e.data),e.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){const e=null!==this.segmentHeaderSize?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(eo()),this.boxWriter.writeBox(to(this,e))}else{const e=this.writer.getPos(),i=(t=this.trackDatas,Jn("mfra",void 0,[...t.map(Zo),Zn("mfro",0,0,[Un(0)])]));this.boxWriter.writeBox(i);const r=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{i(this.mdat);const e=this.boxWriter.offsets.get(this.mdat);i(void 0!==e);const t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}const r=ro(this);if("reserve"===this.fastStart){i(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);const e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:e})}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}var t;e()}},Bc=class{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(5*this.targetSampleRate),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=Math.floor(e.startTime*this.targetSampleRate),this.timestampOffset=e.startTime-this.bufferStartFrame/this.targetSampleRate}doChannelMixerSetup(){i(null!==this.sourceNumberOfChannels);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;this.channelMixer=1===e&&2===t?(t,i)=>t[i*e]:1===e&&4===t?(t,i,r)=>t[i*e]*+(r<2):1===e&&6===t?(t,i,r)=>t[i*e]*+(2===r):2===e&&1===t?(t,i)=>{const r=i*e;return.5*(t[r]+t[r+1])}:2===e&&4===t||2===e&&6===t?(t,i,r)=>t[i*e+r]*+(r<2):4===e&&1===t?(t,i)=>{const r=i*e;return.25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:4===e&&2===t?(t,i,r)=>{const a=i*e;return.5*(t[a+r]+t[a+r+2])}:4===e&&6===t?(t,i,r)=>{const a=i*e;return r<2?t[a+r]:2===r||3===r?0:t[a+r-2]}:6===e&&1===t?(t,i)=>{const r=i*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:6===e&&2===t?(t,i,r)=>{const a=i*e;return t[a+r]+Math.SQRT1_2*(t[a+2]+t[a+r+4])}:6===e&&4===t?(t,i,r)=>{const a=i*e;return r<2?t[a+r]+Math.SQRT1_2*t[a+2]:t[a+r+2]}:(t,i,r)=>r<e?t[i*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){null===this.sourceSampleRate&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const r=e.allocationSize({planeIndex:0,format:"f32"}),a=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(a,{planeIndex:0,format:"f32"});const s=e.timestamp,n=Math.min(e.timestamp+e.duration,this.endTime),o=Math.floor(s*this.targetSampleRate),c=Math.ceil(n*this.targetSampleRate);for(let l=o;l<c;l++){if(l<this.bufferStartFrame)continue;for(;l>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const t=l-this.bufferStartFrame;i(t<this.bufferSizeInFrames);const r=(l/this.targetSampleRate-s)*this.sourceSampleRate,n=Math.floor(r),o=Math.ceil(r),c=r-n;for(let i=0;i<this.targetNumberOfChannels;i++){let r=0,s=0;n>=0&&n<e.numberOfFrames&&(r=this.channelMixer(a,n,i)),o>=0&&o<e.numberOfFrames&&(s=this.channelMixer(a,o,i));const l=r+c*(s-r),d=t*this.targetNumberOfChannels+i;this.outputBuffer[d]+=l}null===this.maxWrittenFrame?this.maxWrittenFrame=t:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,t)}}async finalizeCurrentBuffer(){if(null===this.maxWrittenFrame)return;const e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const i=this.bufferStartFrame/this.targetSampleRate,r=new es({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:i+this.timestampOffset,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}},Ac=class{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if("canceled"===this._connectedTrack.output.state)throw new Error("Output has been canceled.");if("finalizing"===this._connectedTrack.output.state||"finalized"===this._connectedTrack.output.state)throw new Error("Output has been finalized.");if("pending"===this._connectedTrack.output.state)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("pending"===e.output.state)throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,"finalizing"!==e.output.state&&"finalized"!==e.output.state&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}},Rc=class extends Ac{constructor(e){if(super(),this._connectedTrack=null,!ve.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${ve.join(", ")}.`);this._codec=e}},Fc=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&"key"!==t.type)throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")},Mc=class extends Rc{constructor(e){super(e)}add(e,t){if(!(e instanceof Ht))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Fc(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}},Dc=class{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.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new H,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t,r){const a=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const s=this.encodingConfig,n=s.sizeChangeBehavior??"deny";let o=!1;if(null!==this.codedWidth&&null!==this.codedHeight){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,"deny"===n))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(void 0!==s.transform?.width||void 0!==s.transform?.height||void 0!==s.transform?.rotate||void 0!==s.transform?.crop||!0===s.transform?.force||o&&"passThrough"!==n){let r=s.transform?.width,a=s.transform?.height,c=s.transform?.fit??"fill";o&&"passThrough"!==n&&(i(this.outputWidth),i(this.outputHeight),i("deny"!==n),r=this.outputWidth,a=this.outputHeight,c=n);const l=await e.transform({width:r,height:a,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,fit:c,alpha:s.alpha});null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=l.displayWidth,this.outputHeight=l.displayHeight),t&&e.close(),e=l,t=!0}else null!==this.outputWidth&&null!==this.outputHeight||(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const c=s.transform?.frameRate;if(void 0!==c){const i=e.timestamp+e.duration,s=U(e.timestamp,c);if(null!==this.frameRateLastSample){if(s<=this.frameRateLastTimestamp)return this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),void(this.frameRateLastEndTimestamp=i);await this.padFrameRate(s,r)}e===a&&(e=e.clone(),t=!0),e.setTimestamp(s),e.setDuration(1/c),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=s,this.frameRateLastEndTimestamp=i}await this.processAndEncode(e,r)}finally{t&&e.close()}}async processAndEncode(e,t){const r=this.encodingConfig;let a;if(r.transform?.process){let t=r.transform.process(e);if(t instanceof Promise&&(t=await t),null===t)return;Array.isArray(t)||(t=[t]),a=t.map(t=>t instanceof za?t:"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?new za(t):new za(t,{timestamp:e.timestamp,duration:e.duration}))}else a=[e];try{for(const e of a){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),i(this.encoderInitialized);const r=this.encodingConfig.keyFrameInterval??2,a=Math.floor(e.timestamp/r),s={...t,keyFrame:t?.keyFrame||0===r||a!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=a,this.customEncoder){this.customEncoderQueueSize++;const t=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,s)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await i}else{i(this.encoder);const t=e.toVideoFrame(),r=x(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),a=-1!==r?this.preciseTimings[r]:null;if(a&&a.microsecondTimestamp===t.timestamp?(a.timestamp!==e.timestamp&&(a.timestampIsValid=!1),a.duration!==e.duration&&(a.durationIsValid=!1)):(this.preciseTimings.splice(r+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(t.format&&!t.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(t,s),t.close();else{const e=t.displayWidth,i=t.displayHeight;this.splitter||(this.splitter=new Oc(e,i));const{colorFrame:r,alphaFrame:a}=await this.splitter.update(t);this.alphaFrameQueue.push(a),this.encoder.encode(r,s),r.close()}else this.encoder.encode(t,s),t.close();this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener("dequeue",e,{once:!0}))}await this.lastMuxerPromise}}finally{for(const t of a)t!==e&&t.close()}}async padFrameRate(e,t){const r=this.encodingConfig.transform.frameRate;i(this.frameRateLastSample);const a=Math.round((e-this.frameRateLastTimestamp)*r);for(let i=1;i<a;i++){const e=this.frameRateLastSample.clone();e.setTimestamp(this.frameRateLastTimestamp+i/r),e.setDuration(1/r),await this.processAndEncode(e,t),e.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const t=hs({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(t);const r=Ss.find(e=>e.supports(this.encodingConfig.codec,t));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof Ht))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Fc(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else{if("undefined"==typeof VideoEncoder)throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard","keep"===this.encodingConfig.alpha&&(t.latencyMode="quality"),!(t.width%2!=1&&t.height%2!=1||"avc"!==this.encodingConfig.codec&&"hevc"!==this.encodingConfig.codec))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const e=[],r=[];let a=0,s=0;const n=(e,t,i)=>{const r={};if(t){const e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}let a=Ht.fromEncodedChunk(e,r);const s=x(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),n=-1!==s?this.preciseTimings[s]:null;n&&n.microsecondTimestamp===e.timestamp&&(a=a.clone({timestamp:n.timestampIsValid?n.timestamp:void 0,duration:n.durationIsValid?n.duration:void 0})),Fc(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,i).catch(e=>{this.error??=e})},o=/* @__PURE__ */new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(t,o)=>{if(!this.alphaEncoder)return void n(t,null,o);const c=this.alphaFrameQueue.shift();i(void 0!==c),c?(this.alphaEncoder.encode(c,{keyFrame:"key"===t.type}),s++,c.close(),e.push({chunk:t,meta:o})):0===s?n(t,null,o):(r.push(a+s),e.push({chunk:t,meta:o}))},error:e=>{e.stack=o,this.error??=e}}),this.encoder.configure(t),"keep"===this.encodingConfig.alpha){const o=/* @__PURE__ */new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(t,o)=>{s--;const c=e.shift();for(i(void 0!==c),n(c.chunk,t,c.meta),a++;r.length>0&&r[0]===a;){r.shift();const t=e.shift();i(void 0!==t),n(t.chunk,null,t.meta)}},error:e=>{e.stack=o,this.error??=e}}),this.alphaEncoder.configure(t)}}i(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){const e=this.encodingConfig.transform.frameRate,t=U(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await(this.alphaEncoder?.flush())),"closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.splitter?.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},zc=!1,Oc=class e{constructor(t,i){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=/* @__PURE__ */new Map,this.nextRequestId=0;const r="undefined"!=typeof OffscreenCanvas||"undefined"!=typeof document&&"function"==typeof document.createElement;if(!e.forceCpu&&r&&!zc)try{"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(t,i):(this.canvas=document.createElement("canvas"),this.canvas.width=t,this.canvas.height=i);const e=this.canvas.getContext("webgl2",{alpha:!0});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(a){this.gl=null,this.canvas=null,zc=!0,console.warn("Falling back to CPU for color/alpha splitting.",a)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){i(this.gl),i(this.canvas),e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);const t=this.runColorProgram(e),r=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:r}}createVertexShader(){return i(this.gl),this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t")}createColorProgram(){i(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_sourceTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec4 source = texture(u_sourceTexture, v_texCoord);\n\t\t\t\tfragColor = vec4(source.rgb, 1.0);\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createAlphaProgram(){i(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_sourceTexture;\n\t\t\tuniform vec2 u_resolution; // The width and height of the canvas\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\n\t\t\t// This function determines the value for a single byte in the YUV stream\n\t\t\tfloat getByteValue(float byteOffset) {\n\t\t\t\tfloat width = u_resolution.x;\n\t\t\t\tfloat height = u_resolution.y;\n\n\t\t\t\tfloat yPlaneSize = width * height;\n\n\t\t\t\tif (byteOffset < yPlaneSize) {\n\t\t\t\t\t// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from\n\t\t\t\t\tfloat y = floor(byteOffset / width);\n\t\t\t\t\tfloat x = mod(byteOffset, width);\n\t\t\t\t\t\n\t\t\t\t\t// Add 0.5 to sample the center of the texel\n\t\t\t\t\tvec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;\n\t\t\t\t\t\n\t\t\t\t\t// The luma value is the alpha from the source texture\n\t\t\t\t\treturn texture(u_sourceTexture, sampleCoord).a;\n\t\t\t\t} else {\n\t\t\t\t\t// Write a fixed value for chroma and beyond\n\t\t\t\t\treturn 128.0 / 255.0;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\t// Each fragment writes 4 bytes (R, G, B, A)\n\t\t\t\tfloat pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);\n\t\t\t\tfloat baseByteOffset = pixelIndex * 4.0;\n\n\t\t\t\tvec4 result;\n\t\t\t\tfor (int i = 0; i < 4; i++) {\n\t\t\t\t\tfloat currentByteOffset = baseByteOffset + float(i);\n\t\t\t\t\tresult[i] = getByteValue(currentByteOffset);\n\t\t\t\t}\n\t\t\t\t\n\t\t\t\tfragColor = result;\n\t\t\t}\n\t\t"),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){i(this.gl);const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(r)),r}createVAO(){i(this.gl),i(this.colorProgram);const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const a=this.gl.getAttribLocation(this.colorProgram,"a_position"),s=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,8),e}createTexture(){i(this.gl);const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}runColorProgram(e){return i(this.gl),i(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}runAlphaProgram(e){i(this.gl),i(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:t,height:r}=this.canvas,a=t*r+Math.ceil(t/2)*Math.ceil(r/2)*2,s=Math.ceil(a/(4*t));let n=new Uint8Array(4*t*s);this.gl.readPixels(0,0,t,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),n=n.subarray(0,a),i(128===n[t*r]),i(128===n[n.length-1]);const o={format:"I420",codedWidth:t,codedHeight:r,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[n.buffer]};return new VideoFrame(n,o)}updateCpu(e){if(!this.worker){const e=new Blob([`(${Nc.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(e);this.worker=new Worker(t),URL.revokeObjectURL(t),this.worker.addEventListener("message",e=>{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha splitter worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()})}const t=this.nextRequestId++,i=E();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.gl?.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null,this.canvas=null,this.worker?.terminate(),this.worker=null;const e=/* @__PURE__ */new Error("Color/alpha splitter closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}};Oc.forceCpu=!0;var Nc=()=>{let e=null,t=Promise.resolve();self.addEventListener("message",e=>{const{id:r,sourceFrame:a}=e.data;t=t.then(async()=>{try{const{colorFrame:e,alphaFrame:t}=await i(a);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{a.close()}})});const i=async t=>{const i=t.format;if(!i)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const s=t.codedWidth,n=t.codedHeight,o=t.allocationSize();if(e&&e.byteLength===o||(e=new Uint8Array(o)),await t.copyTo(e),"RGBA"===i||"BGRA"===i)return r(e,s,n,i,t);if("I420A"===i||"I420AP10"===i||"I420AP12"===i||"I422A"===i||"I422AP10"===i||"I422AP12"===i||"I444A"===i||"I444AP10"===i||"I444AP12"===i)return a(e,s,n,i,t);throw new Error(`CPU color/alpha splitting does not support format '${i}'.`)},r=(e,t,i,r,a)=>{const s=t*i,n=s+Math.ceil(t/2)*Math.ceil(i/2)*2,o=new Uint8Array(n);for(let d=0,u=3;d<s;d++,u+=4)o[d]=e[u];o.fill(128,s);const c=new VideoFrame(e,{format:"RGBA"===r?"RGBX":"BGRX",codedWidth:t,codedHeight:i,timestamp:a.timestamp,duration:a.duration??void 0}),l={format:"I420",codedWidth:t,codedHeight:i,timestamp:a.timestamp,duration:a.duration??void 0,transfer:[o.buffer]};return{colorFrame:c,alphaFrame:new VideoFrame(o,l)}},a=(e,t,i,r,a)=>{const s=r.includes("P10"),n=r.includes("P12"),o=s||n?2:1;let c,l;r.startsWith("I420")?(c=Math.ceil(t/2),l=Math.ceil(i/2)):r.startsWith("I422")?(c=Math.ceil(t/2),l=i):(c=t,l=i);const d=t*i,u=d*o,h=d*o+c*l*o*2,m=r.replace("A",""),f=Math.ceil(t/2)*Math.ceil(i/2),p=new Uint8Array(u+f*o*2),g=h;p.set(e.subarray(g,g+u),0);const k=u,w=s?512:n?2048:128;1===o?p.fill(w,k):new Uint16Array(p.buffer,k,2*f).fill(w);const b=s?"I420P10":n?"I420P12":"I420",y=new VideoFrame(e.subarray(0,h),{format:m,codedWidth:t,codedHeight:i,timestamp:a.timestamp,duration:a.duration??void 0}),T={format:b,codedWidth:t,codedHeight:i,timestamp:a.timestamp,duration:a.duration??void 0,transfer:[p.buffer]};return{colorFrame:y,alphaFrame:new VideoFrame(p,T)}}},Lc=class extends Rc{constructor(e){(e=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding config must be an object.");if(!ve.includes(e.codec))throw new TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${ve.join(", ")}.`);if(!(e.bitrate instanceof ps)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(void 0!==e.keyFrameInterval&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==e.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(e.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==e.transform){if("object"!=typeof e.transform||!e.transform)throw new TypeError("config.transform, when provided, must be an object.");if(void 0!==e.transform.width&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(void 0!==e.transform.height&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(void 0!==e.transform.fit&&!["fill","contain","cover"].includes(e.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.transform.width&&void 0!==e.transform.height&&void 0===e.transform.fit&&!["fill","contain","cover"].includes(e.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(void 0!==e.transform.fit&&["fill","contain","cover"].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.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(void 0!==e.transform.rotate&&![0,90,180,270].includes(e.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.transform.crop&&Ha(e.transform.crop,"config.transform."),void 0!==e.transform.process&&"function"!=typeof e.transform.process)throw new TypeError("config.transform.process, when provided, must be a function.");if(void 0!==e.transform.frameRate&&(!Number.isFinite(e.transform.frameRate)||e.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(void 0!==e.transform.force&&"boolean"!=typeof e.transform.force)throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(void 0!==e.onEncodedPacket&&"function"!=typeof e.onEncodedPacket)throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(void 0!==e.onEncoderConfig&&"function"!=typeof e.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");us(e.codec,e)})(e),super(e.codec),this._encoder=new Dc(this,e)}add(e,t){if(!(e instanceof za))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Uc=class extends Ac{constructor(e){if(super(),this._connectedTrack=null,!xe.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${xe.join(", ")}.`);this._codec=e}},Wc=class extends Uc{constructor(e){super(e)}add(e,t){if(!(e instanceof Ht))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}},Vc=class{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 H,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),null!==this.lastNumberOfChannels&&null!==this.lastSampleRate){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;void 0!==i.transform?.numberOfChannels||void 0!==i.transform?.sampleRate?(this.resampler||(this.resampler=new Bc({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.transform.sampleRate??e.sampleRate,startTime:e.timestamp,endTime:1/0,onSample:async e=>{await this.processAndEncode(e,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){const i=this.encodingConfig;if(void 0!==i.transform?.sampleFormat&&ns(e.format)!==i.transform.sampleFormat){const r=cs(e,i.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(i.transform?.process){let r=i.transform.process(e);if(r instanceof Promise&&(r=await r),null===r)return;Array.isArray(r)||(r=[r]);for(const e of r){if(!(e instanceof es))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(e,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),i(this.encoderInitialized);{const t=Math.round(e.timestamp*e.sampleRate),i=Math.round((e.timestamp+e.duration)*e.sampleRate);if(null===this.lastEndSampleIndex)this.lastEndSampleIndex=i;else{const i=t-this.lastEndSampleIndex;if(i>=64){const t=new es({data:new Float32Array(i*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:i,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;const t=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).then(()=>this.customEncoderQueueSize--).catch(e=>this.error??=e).finally(()=>{t.close()});this.customEncoderQueueSize>=4&&await i,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{i(this.encoder);const r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener("dequeue",e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){i(this.outputSampleSize),i(this.writeOutputValue);const{numberOfChannels:r,numberOfFrames:a,sampleRate:s,timestamp:n}=e,o=2048,c=[];for(let i=0;i<a;i+=o){const t=Math.min(o,e.numberOfFrames-i),a=t*r*this.outputSampleSize,s=new ArrayBuffer(a),n=new DataView(s);c.push({frameCount:t,view:n})}const l=e.allocationSize({planeIndex:0,format:"f32-planar"}),d=new Float32Array(l/Float32Array.BYTES_PER_ELEMENT);for(let i=0;i<r;i++){e.copyTo(d,{planeIndex:i,format:"f32-planar"});for(let e=0;e<c.length;e++){const{frameCount:t,view:a}=c[e];for(let s=0;s<t;s++)this.writeOutputValue(a,(s*r+i)*this.outputSampleSize,d[e*o+s])}}t&&e.close();const u={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:s}};for(let i=0;i<c.length;i++){const{frameCount:e,view:t}=c[i],r=t.buffer,a=i*o,l=new Ht(new Uint8Array(r),"key",n+a/s,e/s);this.encodingConfig.onEncodedPacket?.(l,u),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,u)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{const{numberOfChannels:t,sampleRate:r}=e,a=fs({numberOfChannels:t,sampleRate:r,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(a);const n=vs.find(e=>e.supports(this.encodingConfig.codec,a));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=a,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof Ht))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==t&&(!t||"object"!=typeof t))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.error??=e})},await this.customEncoder.init();else if(Pe.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if("undefined"==typeof AudioEncoder)throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(a)).supported)throw new Error(`This specific encoder configuration (${a.codec}, ${a.bitrate} bps, ${a.numberOfChannels} channels, ${a.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);const e=/* @__PURE__ */new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(e,t)=>{if("aac"===this.encodingConfig.codec&&t?.decoderConfig){let e=!1;if(e=!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||0===Te(l(t.decoderConfig.description)).objectType,e){const e=Number(s(a.codec.split(".")));t.decoderConfig.description=Se({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let i=Ht.fromEncodedChunk(e);i=i.clone({timestamp:N(i.timestamp,a.sampleRate),duration:null!=e.duration?N(i.duration,a.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(i,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,i,t).catch(e=>{this.error??=e})},error:t=>{t.stack=e,this.error??=t}}),this.encoder.configure(a)}i(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:r,littleEndian:a}=Ne(e);switch(this.outputSampleSize=r,r){case 1:"unsigned"===t?this.writeOutputValue=(e,t,i)=>e.setUint8(t,D(127.5*(i+1),0,255)):"signed"===t?this.writeOutputValue=(e,t,i)=>{e.setInt8(t,D(Math.round(128*i),-128,127))}:"ulaw"===t?this.writeOutputValue=(e,t,i)=>{const r=D(Math.floor(32767*i),-32768,32767);e.setUint8(t,(e=>{let t=e,i=4096,r=0,a=12,s=0;for(t<0&&(t=-t,r=128),t+=33,t>8191&&(t=8191);(t&i)!==i&&a>=5;)i>>=1,a--;return s=t>>a-4&15,255&~(r|a-5<<4|s)})(r))}:"alaw"===t?this.writeOutputValue=(e,t,i)=>{const r=D(Math.floor(32767*i),-32768,32767);e.setUint8(t,(e=>{let t=2048,i=0,r=11,a=0,s=e;for(s<0&&(s=-s,i=128),s>4095&&(s=4095);(s&t)!==t&&r>=5;)t>>=1,r--;return a=s>>(4===r?1:r-4)&15,85^(i|r-4<<4|a)})(r))}:i(!1);break;case 2:"unsigned"===t?this.writeOutputValue=(e,t,i)=>e.setUint16(t,D(32767.5*(i+1),0,65535),a):"signed"===t?this.writeOutputValue=(e,t,i)=>e.setInt16(t,D(Math.round(32767*i),-32768,32767),a):i(!1);break;case 3:"unsigned"===t?this.writeOutputValue=(e,t,i)=>F(e,t,D(8388607.5*(i+1),0,16777215),a):"signed"===t?this.writeOutputValue=(e,t,i)=>((e,t,i,r)=>{(i=D(i,-8388608,8388607))<0&&(i=i+16777216&16777215),F(e,t,i,r)})(e,t,D(Math.round(8388607*i),-8388608,8388607),a):i(!1);break;case 4:"unsigned"===t?this.writeOutputValue=(e,t,i)=>e.setUint32(t,D(2147483647.5*(i+1),0,4294967295),a):"signed"===t?this.writeOutputValue=(e,t,i)=>e.setInt32(t,D(Math.round(2147483647*i),-2147483648,2147483647),a):"float"===t?this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,a):i(!1);break;case 8:"float"===t?this.writeOutputValue=(e,t,i)=>e.setFloat64(t,i,a):i(!1);break;default:A(r),i(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),"closed"!==this.encoder.state&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.error)throw this.error}},qc=class extends Uc{constructor(e){(e=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding config must be an object.");if(!xe.includes(e.codec))throw new TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${xe.join(", ")}.`);if(void 0===e.bitrate&&!Pe.includes(e.codec)&&"flac"!==e.codec)throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(void 0!==e.bitrate&&!(e.bitrate instanceof ps)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==e.transform){if("object"!=typeof e.transform||!e.transform)throw new TypeError("config.transform, when provided, must be an object.");if(void 0!==e.transform.numberOfChannels&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(void 0!==e.transform.sampleRate&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(void 0!==e.transform.sampleFormat&&!["u8","s16","s32","f32"].includes(e.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(void 0!==e.transform.process&&"function"!=typeof e.transform.process)throw new TypeError("config.transform.process, when provided, must be a function.")}if(void 0!==e.onEncodedPacket&&"function"!=typeof e.onEncodedPacket)throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(void 0!==e.onEncoderConfig&&"function"!=typeof e.onEncoderConfig)throw new TypeError("config.onEncoderConfig, when provided, must be a function.");ms(e.codec,e)})(e),super(e.codec),this._encoder=new Vc(this,e)}add(e){if(!(e instanceof es))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}},Hc=class extends Ac{constructor(e){if(super(),this._connectedTrack=null,!Ie.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${Ie.join(", ")}.`);this._codec=e}},jc=class{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>ve.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>xe.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>Ie.includes(e))}_codecUnsupportedHint(e){return""}},$c=class extends jc{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==e.minimumFragmentDuration&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==e.onFtyp&&"function"!=typeof e.onFtyp)throw new TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==e.onMoov&&"function"!=typeof e.onMoov)throw new TypeError("options.onMoov, when provided, must be a function.");if(void 0!==e.onMdat&&"function"!=typeof e.onMdat)throw new TypeError("options.onMdat, when provided, must be a function.");if(void 0!==e.onMoof&&"function"!=typeof e.onMoof)throw new TypeError("options.onMoof, when provided, must be a function.");if(void 0!==e.metadataFormat&&!["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(){const e=2**32-1;return{video:{min:0,max:e},audio:{min:0,max:e},subtitle:{min:0,max:e},total:{min:1,max:e}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new _c(e,this)}},Kc=class extends $c{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ve,...Ce,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ie]}_codecUnsupportedHint(e){return(new Gc).getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}},Xc=class extends $c{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...ve,...Ce,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...Ie]}},Gc=class extends $c{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...ve,...xe]}_codecUnsupportedHint(e){return(new Kc).getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}},Qc=["video","audio","subtitle"],Yc=class e{constructor(e,t,i,r,a){this.id=e,this.output=t,this.type=i,this.source=r,this.metadata=a}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(t){if(!(t instanceof e))throw new TypeError("other must be an OutputTrack.");if(this===t)return!1;const i=de(this.metadata.group),r=de(t.metadata.group);for(const e of i){if(this.type!==t.type&&r.some(t=>e===t))return!0;if(r.some(t=>e._pairedGroups.has(t)))return!0}return!1}},Jc=class extends Yc{constructor(e,t,i,r){super(e,t,"video",i,r)}},Zc=class extends Yc{constructor(e,t,i,r){super(e,t,"audio",i,r)}},el=class extends Yc{constructor(e,t,i,r){super(e,t,"subtitle",i,r)}},tl=class e{constructor(){this._pairedGroups=/* @__PURE__ */new Set}pairWith(t){if(!(t instanceof e))throw new TypeError("other must be an OutputTrackGroup.");if(this===t)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(t),t._pairedGroups.add(this)}},il=e=>{if(!e||"object"!=typeof e)throw new TypeError("metadata must be an object.");if(void 0!==e.languageCode&&!V(e.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==e.name&&"string"!=typeof e.name)throw new TypeError("metadata.name, when provided, must be a string.");if(void 0!==e.disposition&&(e=>{if(!e||"object"!=typeof e)throw new TypeError("disposition must be an object.");if(void 0!==e.default&&"boolean"!=typeof e.default)throw new TypeError("disposition.default must be a boolean.");if(void 0!==e.primary&&"boolean"!=typeof e.primary)throw new TypeError("disposition.primary must be a boolean.");if(void 0!==e.forced&&"boolean"!=typeof e.forced)throw new TypeError("disposition.forced must be a boolean.");if(void 0!==e.original&&"boolean"!=typeof e.original)throw new TypeError("disposition.original must be a boolean.");if(void 0!==e.commentary&&"boolean"!=typeof e.commentary)throw new TypeError("disposition.commentary must be a boolean.");if(void 0!==e.hearingImpaired&&"boolean"!=typeof e.hearingImpaired)throw new TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==e.visuallyImpaired&&"boolean"!=typeof e.visuallyImpaired)throw new TypeError("disposition.visuallyImpaired must be a boolean.")})(e.disposition),void 0!==e.maximumPacketCount&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==e.group&&!(e.group instanceof tl)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof tl))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")},rl=class extends ue{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(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new tl,this._onFinalize=null,this._unfinalizedTargets=/* @__PURE__ */new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new T,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.format instanceof jc))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof bc||e.target instanceof Cc))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof bc&&this._rememberTarget(e.target),void 0!==e.initTarget&&!(e.initTarget instanceof bc)&&"function"!=typeof e.initTarget)throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(void 0!==e.onFinalize&&"function"!=typeof e.onFinalize)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 bc&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){i(this._target instanceof Cc);const t=this._target.getTarget(e),r=e=>{if(!(e instanceof bc))throw new TypeError("getTarget must return a Target.");return e};return t instanceof Promise?t.then(r):r(t)}async _getTarget(e){i(this._target instanceof Cc);const t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),"canceled"===this.state?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(i(null!==this._initTarget),this._initTarget instanceof bc)return this._initTarget;const e=await this._initTarget();return"canceled"===this.state?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return null!==this._initTarget}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof bc)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=t=>("canceled"===this.state?t._close():this._rememberTarget(t),this._emit("target",{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{const t=await this._getRootTarget(),i=new wc(t,"boolean"==typeof e?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof Rc))throw new TypeError("source must be a VideoSource.");if(il(t),void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(void 0!==t.frameRate&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Jc(this._tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof Uc))throw new TypeError("source must be an AudioSource.");il(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new Zc(this._tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof Hc))throw new TypeError("source must be a SubtitleSource.");il(t);const i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new el(this._tracks.length+1,this,e,i))}setMetadataTags(e){if(ge(e),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if("pending"!==this.state)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((t,i)=>t+(i.type===e.type?1:0),0),r=t[e.type].max;if(i===r)throw new Error(0===r?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${1===r?"":"s"}.`);const a=t.total.max;if(this._tracks.length===a)throw new Error(`${this.format._name} does not support more than ${a} tracks${1===a?"":"s"} in total.`);if(e.isVideoTrack()){const t=this.format.getSupportedVideoCodecs();if(0===t.length)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const t=this.format.getSupportedAudioCodecs();if(0===t.length)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const t=this.format.getSupportedSubtitleCodecs();if(0===t.length)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){const e=this.format.getSupportedTrackCounts();for(const i of Qc){const t=this._tracks.reduce((e,t)=>e+(t.type===i?1:0),0),r=e[i].min;if(t<r)throw new Error(r===e[i].max?`${this.format._name} requires exactly ${r} ${i} track${1===r?"":"s"}.`:`${this.format._name} requires at least ${r} ${i} track${1===r?"":"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${1===t?"":"s"}.`:`${this.format._name} requires at least ${t} track${1===t?"":"s"}.`);if("canceled"===this.state)throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const e=await this._mutex.acquire();try{await this._muxer.start();const e=this._tracks.map(e=>e.source._start());await Promise.all(e)}finally{e()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){return this._cancelPromise?(console.warn("Output has already been canceled."),this._cancelPromise):"finalizing"!==this.state&&"finalized"!==this.state?this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})():void("finalized"===this.state&&console.warn("Output has already been finalized."))}async finalize(){if("pending"===this.state)throw new Error("Cannot finalize before starting.");if("canceled"===this.state)throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const e=this._tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){const e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}},al=e=>{if(!e||"object"!=typeof e)throw new TypeError("options.video, when provided, must be an object.");if(void 0!==e?.discard&&"boolean"!=typeof e.discard)throw new TypeError("options.video.discard, when provided, must be a boolean.");if(void 0!==e?.forceTranscode&&"boolean"!=typeof e.forceTranscode)throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(void 0!==e?.codec&&!ve.includes(e.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${ve.join(", ")}.`);if(void 0!==e?.bitrate&&!(e.bitrate instanceof ps)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==e?.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if(void 0!==e?.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if(void 0!==e?.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(void 0!==e?.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(void 0!==e?.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e?.allowRotationMetadata&&"boolean"!=typeof e.allowRotationMetadata)throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(void 0!==e?.crop&&Ha(e.crop,"options.video."),void 0!==e?.frameRate&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(void 0!==e?.alpha&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(void 0!==e?.keyFrameInterval&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==e?.process&&"function"!=typeof e.process)throw new TypeError("options.video.process, when provided, must be a function.");if(void 0!==e?.processedWidth&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(void 0!==e?.processedHeight&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(void 0!==e?.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e?.group&&!(e.group instanceof tl||Array.isArray(e.group)&&e.group.every(e=>e instanceof tl)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},sl=e=>{if(!e||"object"!=typeof e)throw new TypeError("options.audio, when provided, must be an object.");if(void 0!==e?.discard&&"boolean"!=typeof e.discard)throw new TypeError("options.audio.discard, when provided, must be a boolean.");if(void 0!==e?.forceTranscode&&"boolean"!=typeof e.forceTranscode)throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(void 0!==e?.codec&&!xe.includes(e.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${xe.join(", ")}.`);if(void 0!==e?.bitrate&&!(e.bitrate instanceof ps)&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==e?.numberOfChannels&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(void 0!==e?.sampleRate&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(void 0!==e?.sampleFormat&&!["u8","s16","s32","f32"].includes(e.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(void 0!==e?.process&&"function"!=typeof e.process)throw new TypeError("options.audio.process, when provided, must be a function.");if(void 0!==e?.processedNumberOfChannels&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(void 0!==e?.processedSampleRate&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(void 0!==e?.group&&!(e.group instanceof tl||Array.isArray(e.group)&&e.group.every(e=>e instanceof tl)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},nl=48e3,ol=class e{static async init(t){const i=new e(t);return await i._init(),i}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPromises=[],this._executed=!1,this._synchronizer=new ll,this._totalDuration=null,this._maxTimestamps=/* @__PURE__ */new Map,this._canceled=!1,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.input instanceof Zs))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof rl))throw new TypeError("options.output must be an Output.");if(void 0!==e.tracks&&"all"!==e.tracks&&"primary"!==e.tracks)throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||"pending"!==e.output.state)throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(void 0!==e.video&&"function"!=typeof e.video)if(Array.isArray(e.video))for(const r of e.video)al(r);else al(e.video);if(void 0!==e.audio&&"function"!=typeof e.audio)if(Array.isArray(e.audio))for(const r of e.audio)sl(r);else sl(e.audio);if(void 0!==e.trim&&(!e.trim||"object"!=typeof e.trim))throw new TypeError("options.trim, when provided, must be an object.");if(void 0!==e.trim?.start&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(void 0!==e.trim?.end&&!Number.isFinite(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a finite number.");if(void 0!==e.trim?.start&&void 0!==e.trim.end&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(void 0!==e.tags&&("object"!=typeof e.tags||!e.tags)&&"function"!=typeof e.tags)throw new TypeError("options.tags, when provided, must be an object or a function.");if("object"==typeof e.tags&&ge(e.tags),void 0!==e.showWarnings&&"boolean"!=typeof e.showWarnings)throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this.input=e.input,this.output=e.output;const{promise:t,resolve:i}=E();this._started=t,this._start=i}async _init(){const e=await this.input.getFormat();let t,r=this._options.tracks;void 0===r&&(r=e.name.includes("(HLS)")?"primary":"all"),"all"===r?t=await this.input.getTracks():"primary"===r?t=[await this.input.getPrimaryVideoTrack(),await this.input.getPrimaryAudioTrack()].filter(e=>null!==e):(A(r),i(!1));const a=this.output.format.getSupportedTrackCounts();let s=1,n=1;const o=[],c=[];for(const m of t){let e;if(m.isVideoTrack())if(this._options.video)if("function"==typeof this._options.video){const t=await this._options.video(m,s)??{};if(Array.isArray(t))for(const e of t)al(e);else al(t);e=Array.isArray(t)?t:[t],s++}else e=Array.isArray(this._options.video)?this._options.video:[this._options.video];else e=[{}];else if(m.isAudioTrack())if(this._options.audio)if("function"==typeof this._options.audio){const t=await this._options.audio(m,n)??{};if(Array.isArray(t))for(const e of t)sl(e);else sl(t);e=Array.isArray(t)?t:[t],n++}else e=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else e=[{}];else i(!1);const t=e.filter(e=>e.discard);for(const i of t)this.discardedTracks.push({track:m,reason:"discarded_by_user",trackOptions:i});if(e.length===t.length){0===e.length&&this.discardedTracks.push({track:m,reason:"discarded_by_user",trackOptions:{}});continue}const r=e.filter(e=>!e.discard);o.push(m),c.push(r)}void 0!==this._options.trim?.start?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);for(let m=0;m<o.length;m++){const e=o[m],t=c[m];for(const r of t){if(this._totalTrackCount===a.total.max){this.discardedTracks.push({track:e,reason:"max_track_count_reached",trackOptions:r});continue}if(this._addedCounts[e.type]===a[e.type].max){this.discardedTracks.push({track:e,reason:"max_track_count_of_type_reached",trackOptions:r});continue}const t=this._nextOutputTrackId++;e.isVideoTrack()?await this._processVideoTrack(e,r,t):e.isAudioTrack()?await this._processAudioTrack(e,r,t):i(!1)}}for(let m=0;m<this.utilizedTracks.length-1;m++)for(let e=m+1;e<this.utilizedTracks.length;e++){const t=this.utilizedTracks[m],r=this.utilizedTracks[e],a=this._outputOwnTrackGroups[m],s=this._outputOwnTrackGroups[e];i(void 0!==a),i(void 0!==s),a&&s&&t.canBePairedWith(r)&&a.pairWith(s)}const l=await this.input.getMetadataTags();let d;if(this._options.tags){const e="function"==typeof this._options.tags?await this._options.tags(l):this._options.tags;ge(e),d=e}else d=l;const u=e.mimeType===this.output.format.mimeType,h=l.raw===d.raw;if(l.raw&&h&&!u&&delete d.raw,this.output.setMetadataTags(d),this.isValid=this._totalTrackCount>=a.total.min&&this._addedCounts.video>=a.video.min&&this._addedCounts.audio>=a.audio.min&&this._addedCounts.subtitle>=a.subtitle.min,this._options.showWarnings??1){const e=[],t=this.discardedTracks.filter(e=>"discarded_by_user"!==e.reason);t.length>0&&e.push("Some tracks had to be discarded from the conversion:",t),this.isValid||(e.length>0&&e.push("\n\n"),e.push(this._getInvalidityExplanation().join(""))),e.length>0&&console.warn(...e)}}_getInvalidityExplanation(){const e=[];if(0===this.discardedTracks.length)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(e=>"discarded_by_user"===e.reason||"no_encodable_target_codec"===e.reason)&&this.discardedTracks.some(e=>"no_encodable_target_codec"===e.reason);if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const t=this.discardedTracks.flatMap(e=>"discarded_by_user"===e.reason?[]:"video"===e.track.type?this.output.format.getSupportedVideoCodecs():"audio"===e.track.type?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs()),i=[...new Set(t)];1===i.length?e.push(`\nTracks were discarded because your environment is not able to encode '${i[0]}'.`):e.push(`\nTracks were discarded because your environment is not able to encode any of the following codecs: ${i.map(e=>`'${e}'`).join(", ")}.`),i.includes("mp3")&&e.push("\nThe @mediabunny/mp3-encoder extension package provides support for encoding MP3."),i.includes("aac")&&e.push("\nThe @mediabunny/aac-encoder extension package provides support for encoding AAC."),(i.includes("ac3")||i.includes("eac3"))&&e.push("\nThe @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3."),i.includes("flac")&&e.push("\nThe @mediabunny/flac-encoder extension package provides support for encoding FLAC.")}else e.push("\nCheck the discardedTracks field for more info.")}return e}async execute(){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.\n"+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");this._executed=!0;for(const t of this._outputTrackIds)this._synchronizer.declareTrack(t);if(this.onProgress){const e=[...new Set(this.utilizedTracks)].map(async e=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration()),t=Math.max(0,...await Promise.all(e));this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const i of this._outputTrackIds)this._maxTimestamps.set(i,0);this.onProgress?.(0,0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}if(this._canceled)throw new cl;if(await this.output.finalize(),this._computeProgress){const e=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,e)}}async cancel(){"finalizing"!==this.output.state&&"finalized"!==this.output.state&&(this._canceled?console.warn("Conversion already canceled."):(this._canceled=!0,await this.output.cancel()))}async _processVideoTrack(e,t,r){const s=await e.getCodec();if(!s)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});let n;const o=await e.getRotation(),c=a(o+(t.rotate??0));let l=c;const d=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),u=await e.getSquarePixelWidth(),h=await e.getSquarePixelHeight(),[m,f]=c%180==0?[u,h]:[h,u];let p=t.crop;p&&(p=qa(p,m,f));const[g,k]=p?[p.width,p.height]:[m,f];let w=g,b=k;const y=w/b;void 0!==t.width&&void 0===t.height?(w=he(t.width),b=he(Math.round(w/y))):void 0===t.width&&void 0!==t.height?(b=he(t.height),w=he(Math.round(b*y))):void 0!==t.width&&void 0!==t.height&&(w=he(t.width),b=he(t.height));const T=await e.getFirstTimestamp();let S=this.output.format.getSupportedVideoCodecs();const v=!!t.forceTranscode||T<this._startTimestamp||!!t.frameRate||void 0!==t.keyFrameInterval||void 0!==t.process||void 0!==t.bitrate||!S.includes(s)||t.codec&&t.codec!==s||w!==g||b!==k||0!==c&&!d||!!p,P=t.alpha??"discard";if(v){if(!(await e.canDecode()))return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});t.codec&&(S=S.filter(e=>e===t.codec));const s=t.bitrate??ks,m=await(async(e,t)=>{for(const i of e)if(await ws(i,t))return i;return null})(S,{width:t.process&&t.processedWidth?t.processedWidth:w,height:t.process&&t.processedHeight?t.processedHeight:b,bitrate:s});if(!m)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});const f={codec:m,bitrate:s,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:P,hardwareAcceleration:t.hardwareAcceleration,transform:{}};i(f.transform);let y=w!==g||b!==k||0!==c&&(!d||void 0!==t.process)||!!p||u!==await e.getCodedWidth()||h!==await e.getCodedHeight();if(!y){const t=new rl({format:new Kc,target:new vc}),i=new Lc(f);t.addVideoTrack(i),await t.start();const r=await new Ds(e).getSample(T);if(r)try{await i.add(r),r.close(),await t.finalize()}catch(I){console.info("Error when probing encoder support. Falling back to rerender path.",I),y=!0,t.cancel()}else await t.cancel()}t.frameRate&&(f.transform.frameRate=t.frameRate),y&&(l=0,f.transform.width=w,f.transform.height=b,f.transform.fit=t.fit??"fill",f.transform.rotate=a(c-o),f.transform.crop=p,f.transform.alpha=P);const v=new Lc(f);n=v,this._trackPromises.push((async()=>{await this._started;const i=new Ds(e);for await(const e of i.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled)return void e.close();const i=Math.max(e.timestamp-this._startTimestamp,0);e.setTimestamp(i),await this._registerVideoSample(t,r,v,e),e.close()}v.close(),this._synchronizer.closeTrack(r)})())}else{const t=new Mc(s);n=t,this._trackPromises.push((async()=>{await this._started;const a=new Is(e),s={decoderConfig:await e.getDecoderConfig()??void 0};for await(const e of a.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this._canceled)return;if(e.timestamp>=this._endTimestamp)break;const a=e.clone({timestamp:e.timestamp-this._startTimestamp,sideData:"discard"===P?{}:e.sideData});i(a.timestamp>=0),this._reportProgress(r,a.timestamp+a.duration),await t.add(a,s),this._synchronizer.shouldWait(r,a.timestamp)&&await this._synchronizer.wait(a.timestamp)}t.close(),this._synchronizer.closeTrack(r)})())}let C=null;t.group||(C=new tl);const x=await e.getLanguageCode();this.output.addVideoTrack(n,{frameRate:t.frameRate,languageCode:V(x)?x:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:l,group:C??t.group}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(C)}async _registerVideoSample(e,t,i,r){if(this._canceled)return;let a;if(this._reportProgress(t,r.timestamp+r.duration),e.process){let t=e.process(r);t instanceof Promise&&(t=await t),Array.isArray(t)||(t=null===t?[]:[t]),a=t.map(e=>e instanceof za?e:"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?new za(e):new za(e,{timestamp:r.timestamp,duration:r.duration}))}else a=[r];try{for(const e of a){if(this._canceled)break;await i.add(e),this._synchronizer.shouldWait(t,e.timestamp)&&await this._synchronizer.wait(e.timestamp)}}finally{for(const e of a)e!==r&&e.close()}}async _processAudioTrack(e,t,r){const a=await e.getCodec();if(!a)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});let s;const n=await e.getNumberOfChannels(),o=await e.getSampleRate(),c=await e.getFirstTimestamp();let l=t.numberOfChannels??n,d=t.sampleRate??o,u=l!==n||d!==o||c<this._startTimestamp||c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,h=this.output.format.getSupportedAudioCodecs();if(t.forceTranscode||t.bitrate||u||!h.includes(a)||t.codec&&t.codec!==a||t.process||void 0!==t.sampleFormat){if(!(await e.canDecode()))return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});let i=null;t.codec&&(h=h.filter(e=>e===t.codec));const a=t.bitrate??ks,n=await bs(h,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:l,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:d,bitrate:a});if(n.some(e=>Ce.includes(e))||!h.some(e=>Ce.includes(e))||2===l&&d===nl)i=n[0]??null;else{const e=(await bs(h,{numberOfChannels:2,sampleRate:nl,bitrate:a})).find(e=>Ce.includes(e));e&&(u=!0,i=e,l=2,d=nl)}if(null===i)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});if(u)s=this._resampleAudio(e,t,r,i,l,d,a);else{const n=new qc({codec:i,bitrate:a});s=n,this._trackPromises.push((async()=>{await this._started;const i=new Ls(e);for await(const e of i.samples(void 0,this._endTimestamp)){if(this._canceled)return void e.close();e.setTimestamp(e.timestamp-this._startTimestamp),await this._registerAudioSample(t,r,n,e),e.close()}n.close(),this._synchronizer.closeTrack(r)})())}}else{const t=new Wc(a);s=t,this._trackPromises.push((async()=>{await this._started;const a=new Is(e),s={decoderConfig:await e.getDecoderConfig()??void 0};for await(const e of a.packets()){if(this._canceled)return;if(e.timestamp>=this._endTimestamp)break;const a=e.clone({timestamp:e.timestamp-this._startTimestamp});i(a.timestamp>=0),this._reportProgress(r,a.timestamp+a.duration),await t.add(a,s),this._synchronizer.shouldWait(r,a.timestamp)&&await this._synchronizer.wait(a.timestamp)}t.close(),this._synchronizer.closeTrack(r)})())}let m=null;t.group||(m=new tl);const f=await e.getLanguageCode();this.output.addAudioTrack(s,{languageCode:V(f)?f:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:m??t.group}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(m)}async _registerAudioSample(e,t,i,r){if(this._canceled)return;let a,s=r;if(void 0!==e.sampleFormat&&ns(s.format)!==e.sampleFormat&&(s=cs(s,e.sampleFormat)),this._reportProgress(t,s.timestamp+s.duration),e.process){let t=e.process(s);if(t instanceof Promise&&(t=await t),Array.isArray(t)||(t=null===t?[]:[t]),!t.every(e=>e instanceof es))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");a=t}else a=[s];try{for(const e of a){if(this._canceled)break;await i.add(e),this._synchronizer.shouldWait(t,e.timestamp)&&await this._synchronizer.wait(e.timestamp)}}finally{s!==r&&s.close();for(const e of a)e!==r&&e.close()}}_resampleAudio(e,t,r,a,s,n,o){const c=new qc({codec:a,bitrate:o});return this._trackPromises.push((async()=>{await this._started;const a=new Bc({targetNumberOfChannels:s,targetSampleRate:n,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async e=>{i(e.timestamp>=this._startTimestamp),e.setTimestamp(e.timestamp-this._startTimestamp),await this._registerAudioSample(t,r,c,e),e.close()}}),o=new Ls(e).samples(this._startTimestamp,this._endTimestamp);for await(const e of o){if(this._canceled)return void e.close();await a.add(e),e.close()}await a.finalize(),c.close(),this._synchronizer.closeTrack(r)})()),c}_reportProgress(e,t){if(!this._computeProgress)return;i(null!==this._totalDuration),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const r=Math.min(...this._maxTimestamps.values()),a=D(r/this._totalDuration,0,1);a!==this._lastProgress&&(this._lastProgress=a,this.onProgress?.(a,r))}},cl=class extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}},ll=class{constructor(){this.maxTimestamps=/* @__PURE__ */new Map,this.resolvers=[]}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){const r=this.maxTimestamps.get(e);return i(void 0!==r),this.maxTimestamps.set(e,Math.max(t,r)),t-this.computeMinAndMaybeResolve()>1}wait(e){const{promise:t,resolve:i}=E();return this.resolvers.push({timestamp:e,resolve:i}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}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<1&&(i.resolve(),this.resolvers.splice(t,1),t--)}return e}},dl=Symbol.for("mediabunny loaded");globalThis[dl]&&console.error("[WARNING]\nMediabunny 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[dl]=!0;export{Ea as ALL_FORMATS,Vr as BlobSource,Sc as BufferTarget,zs as CanvasSink,ol as Conversion,Zs as Input,Kc as Mp4OutputFormat,rl as Output,gs as QUALITY_MEDIUM};