/**
 * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.39.0.
 * Original file: /npm/mediabunny@1.27.1/dist/modules/src/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
function e(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(r){if("default"!==r&&!(r in e)){var i=Object.getOwnPropertyDescriptor(t,r);Object.defineProperty(e,r,i.get?i:{enumerable:!0,get:function(){return t[r]}})}}))})),Object.freeze(e)}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */function t(e){if(!e)throw new Error("Assertion failed.")}const r=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},i=e=>e&&e[e.length-1],a=e=>e>=0&&e<2**32;class s{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,r=7-(7&this.pos),i=(t&1<<r)>>r;return this.pos++,i}readBits(e){if(1===e)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const r=this.pos+e;for(let e=this.pos;e<r;e++){const i=Math.floor(e/8);let a=this.bytes[i];const s=7-(7&e);a&=~(1<<s),a|=(t&1<<r-e-1)>>r-e-1<<s,this.bytes[i]=a}this.pos=r}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 e=new s(this.bytes);return e.pos=this.pos,e}}const n=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)},o=e=>{const t=n(e);return 1&t?t+1>>1:-(t>>1)},c=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),l=new TextDecoder,h=new TextEncoder,u=e=>{for(let t=0;t<e.length;t++){if(e.charCodeAt(t)>255)return!1}return!0},m=e=>Object.fromEntries(Object.entries(e).map((([e,t])=>[t,e]))),p={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},f=m(p),g={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},w=m(g),k={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},b=m(k),y=e=>!!(e&&e.primaries&&e.transfer&&e.matrix&&void 0!==e.fullRange),T=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class S{constructor(){this.currentPromise=Promise.resolve()}async acquire(){let e;const t=new Promise((t=>{e=t})),r=this.currentPromise;return this.currentPromise=t,await r,e}}const v=e=>[...e].map((e=>e.toString(16).padStart(2,"0"))).join(""),C=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,x=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;i<=a;){const n=i+a>>1,o=r(e[n]);o===t?(s=n,a=n-1):o<t?i=n+1:a=n-1}return s},P=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;i<=a;){const n=i+(a-i+1)/2|0;r(e[n])<=t?(s=n,i=n+1):a=n-1}return s},_=(e,t,r)=>{const i=P(e,r(t),r);e.splice(i+1,0,t)},I=()=>{let e,t;return{promise:new Promise(((r,i)=>{e=r,t=i})),resolve:e,reject:t}},E=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},A=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return-1},B=e=>{throw new Error(`Unexpected value: ${e}`)},F=(e,t,r)=>{const i=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return r?i|a<<8|s<<16:i<<16|a<<8|s},M=(e,t,r,i)=>{r>>>=0,r&=16777215,i?(e.setUint8(t,255&r),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,r>>>16&255)):(e.setUint8(t,r>>>16&255),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,255&r))},D=(e,t)=>({async next(){const r=await e.next();return r.done?{value:void 0,done:!0}:{value:t(r.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),z=(e,t,r)=>Math.max(t,Math.min(r,e)),R="und",O=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},U=(e,t)=>Math.round(e/t)*t,N=/^[a-z]{3}$/,V=e=>N.test(e),L=1e6*(1+Number.EPSILON),W=(e,t)=>{const r={...e,...t};if(e.headers||t.headers){const i=e.headers?H(e.headers):{},a=t.headers?H(t.headers):{},s={...i};Object.entries(a).forEach((([e,t])=>{const r=Object.keys(s).find((t=>t.toLowerCase()===e.toLowerCase()));r&&delete s[r],s[e]=t})),r.headers=s}return r},H=e=>{if(e instanceof Headers){const t={};return e.forEach(((e,r)=>{t[r]=e})),t}if(Array.isArray(e)){const t={};return e.forEach((([e,r])=>{t[e]=r})),t}return e},q=async(e,t,r,i,a)=>{let s=0;for(;;)try{return await e(t,r)}catch(e){if(a())throw e;s++;const r=i(s,e,t);if(null===r)throw e;if(console.error("Retrying failed fetch. Error:",e),!Number.isFinite(r)||r<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(r>0&&await new Promise((e=>setTimeout(e,1e3*r))),a())throw e}};class j{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let $=null;const Q=()=>null!==$?$:$=!("undefined"==typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let K=null;const G=()=>null!==K?K:K="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox");let X=null;const Y=()=>null!==X?X:X=!("undefined"==typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent));let J=null;const Z=(e,t)=>-1!==e?e:t,ee=(e,t,r,i)=>e<=i&&r<=t,te=function*(e){for(const t in e){const r=e[t];void 0!==r&&(yield{key:t,value:r})}},re=e=>{switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},ie=e=>{const t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r},ae=e=>{let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)},se=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},ne=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},oe=e=>"number"==typeof e&&!Number.isNaN(e);
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class ce{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.")}}class de{constructor(e,t,r,i){if(this.data=e,this.mimeType=t,this.name=r,this.description=i,!(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!==r&&"string"!=typeof r)throw new TypeError("name, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw new TypeError("description, when provided, must be a string.")}}const le=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 ce||t instanceof de))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, or null.")}},he=e=>!(void 0!==e.title||void 0!==e.description||void 0!==e.artist||void 0!==e.album||void 0!==e.albumArtist||void 0!==e.trackNumber||void 0!==e.tracksTotal||void 0!==e.discNumber||void 0!==e.discsTotal||void 0!==e.genre||void 0!==e.date||void 0!==e.lyrics||e.images&&0!==e.images.length||void 0!==e.comment||void 0!==e.raw&&0!==Object.keys(e.raw).length),ue={default:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},me=["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"],fe=["aac","opus","mp3","vorbis","flac"],ge=[...fe,...pe],we=["webvtt"],ke=[{maxMacroblocks:99,maxBitrate:64e3,level:10},{maxMacroblocks:396,maxBitrate:192e3,level:11},{maxMacroblocks:396,maxBitrate:384e3,level:12},{maxMacroblocks:396,maxBitrate:768e3,level:13},{maxMacroblocks:396,maxBitrate:2e6,level:20},{maxMacroblocks:792,maxBitrate:4e6,level:21},{maxMacroblocks:1620,maxBitrate:4e6,level:22},{maxMacroblocks:1620,maxBitrate:1e7,level:30},{maxMacroblocks:3600,maxBitrate:14e6,level:31},{maxMacroblocks:5120,maxBitrate:2e7,level:32},{maxMacroblocks:8192,maxBitrate:2e7,level:40},{maxMacroblocks:8192,maxBitrate:5e7,level:41},{maxMacroblocks:8704,maxBitrate:5e7,level:42},{maxMacroblocks:22080,maxBitrate:135e6,level:50},{maxMacroblocks:36864,maxBitrate:24e7,level:51},{maxMacroblocks:36864,maxBitrate:24e7,level:52},{maxMacroblocks:139264,maxBitrate:24e7,level:60},{maxMacroblocks:139264,maxBitrate:48e7,level:61},{maxMacroblocks:139264,maxBitrate:8e8,level:62}],be=[{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}],ye=[{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}],Te=[{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}],Se=".01.01.01.01.00",ve=".0.110.01.01.01.0",Ce=(e,t,r,a)=>{if("avc"===e){const e=100,s=Math.ceil(t/16)*Math.ceil(r/16),n=ke.find((e=>s<=e.maxMacroblocks&&a<=e.maxBitrate))??i(ke),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="",s=1,n="6",o=t*r,c=be.find((e=>o<=e.maxPictureSize&&a<=e.maxBitrate))??i(be),d="B0";return`hev1.${e}${s}.${n}.${c.tier}${c.level}.${d}`}if("vp8"===e)return"vp8";if("vp9"===e){const e=t*r,s="08";return`vp09.${"00"}.${(ye.find((t=>e<=t.maxPictureSize&&a<=t.maxBitrate))??i(ye)).level.toString().padStart(2,"0")}.${s}`}if("av1"===e){const e=0,s=t*r,n=Te.find((e=>s<=e.maxPictureSize&&a<=e.maxBitrate))??i(Te),o="08";return`av01.${e}.${n.level.toString().padStart(2,"0")}${n.tier}.${o}`}throw new TypeError(`Unhandled codec '${e}'.`)},xe=e=>{const t=e.split(".");return[1,1,Number(t[1]),2,1,Number(t[2]),3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]},Pe=e=>{const t=e.split("."),r=Number(t[1]),i=t[2];return[129,(r<<5)+Number(i.slice(0,-1)),(("H"===i.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=e=>{const{codec:r,codecDescription:a,colorSpace:s,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:c,av1CodecInfo:l}=e;if("avc"===r){if(t(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${v(t)}`}if(!a||a.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${v(a.subarray(1,4))}`}if("hevc"===r){let e,t,r,i,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,r=C(o.generalProfileCompatibilityFlags),i=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!a||a.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const o=d(a),c=o.getUint8(1);e=c>>6&3,t=31&c,r=C(o.getUint32(2)),i=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+=r.toString(16).toUpperCase(),c+=".",c+=0===i?"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"===r)return"vp8";if("vp9"===r){if(!c){const t=e.width*e.height;let r=i(ye).level;for(const e of ye)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.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(Se)&&(t=t.slice(0,-15)),t}if("av1"===r){if(!l){const t=e.width*e.height;let r=i(ye).level;for(const e of ye)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}const t=l.profile,r=l.level.toString().padStart(2,"0"),a=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=s?.primaries?p[s.primaries]:1,h=s?.transfer?g[s.transfer]:1,u=s?.matrix?k[s.matrix]:1,m=s?.fullRange?1:0;let f=`av01.${t}.${r}${a}.${n}`;return f+=`.${o}.${c.toString().padStart(3,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${m}`,f.endsWith(ve)&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${r}'.`)},Ie=(e,t,r)=>{if("aac"===e)return t>=2&&r<=24e3?"mp4a.40.29":r<=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(pe.includes(e))return e;throw new TypeError(`Unhandled codec '${e}'.`)},Ee=e=>{const{codec:t,codecDescription:r,aacCodecInfo:i}=e;if("aac"===t){if(!i)throw new TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";return`mp4a.40.${Fe(r).objectType}`}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if(t&&pe.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Ae=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Be=[-1,1,2,3,4,5,6,8],Fe=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new s(e);let r=t.readBits(5);31===r&&(r=32+t.readBits(6));const i=t.readBits(4);let a=null;15===i?a=t.readBits(24):i<Ae.length&&(a=Ae[i]);const n=t.readBits(4);let o=null;return n>=1&&n<=7&&(o=Be[n]),{objectType:r,frequencyIndex:i,sampleRate:a,channelConfiguration:n,numberOfChannels:o}},Me=48e3,De=/^pcm-([usf])(\d+)+(be)?$/,ze=e=>{if(t(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 r=De.exec(e);let i;t(r),i="u"===r[1]?"unsigned":"s"===r[1]?"signed":"float";return{dataType:i,sampleSize:Number(r[2])/8,littleEndian:"be"!==r[3],silentValue:"pcm-u8"===e?128:0}},Re=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":e.startsWith("mp4a.40")||"mp4a.67"===e?"aac":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e?"mp3":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ulaw"===e?"ulaw":"alaw"===e?"alaw":De.test(e)?e:"webvtt"===e?"webvtt":null,Oe=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],Ue=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,Ne=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,Ve=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,Le=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,We=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(!Oe.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 WebCodecs 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.description&&!T(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 r=Object.keys(p);if(null!=t.primaries&&!r.includes(t.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);const i=Object.keys(g);if(null!=t.transfer&&!i.includes(t.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);const a=Object.keys(k);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(!Ue.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(!Ne.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(!Ve.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")&&!Le.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/.')},He=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm"],qe=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(!He.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 WebCodecs 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&&!T(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/.");if(!e.decoderConfig.description)throw new TypeError("Audio chunk metadata decoder configuration for AAC must include a description, which is expected to be an AudioSpecificConfig as specified in ISO 14496-3.")}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".');const t=42;if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<t)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("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(", ")}).`)},je=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.")};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class $e{constructor(e){this.mutex=new S,this.firstMediaStreamTimestamp=null,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateAndNormalizeTimestamp(e,t,r){t+=e.source._timestampOffset;let i=this.trackTimestampInfo.get(e);if(!i){if(!r)throw new Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:t},this.trackTimestampInfo.set(e,i)}if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);if(r&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),t<i.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 ${i.maxTimestampBeforeLastKeyPacket}s.`);return i.maxTimestamp=Math.max(i.maxTimestamp,t),t}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Qe extends $e{constructor(e,t){super(e),this.header=new Uint8Array(7),this.headerBitstream=new s(this.header),this.audioSpecificConfig=null,this.format=t,this.writer=e._writer}async start(){}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,r,i){const a=await this.mutex.acquire();try{if(this.validateAndNormalizeTimestamp(e,r.timestamp,"key"===r.type),!this.audioSpecificConfig){qe(i);const e=i?.decoderConfig?.description;t(e),this.audioSpecificConfig=Fe(c(e));const{objectType:r,frequencyIndex:a,channelConfiguration:s}=this.audioSpecificConfig,n=r-1;this.headerBitstream.writeBits(12,4095),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(2,0),this.headerBitstream.writeBits(1,1),this.headerBitstream.writeBits(2,n),this.headerBitstream.writeBits(4,a),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(3,s),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(1,0),this.headerBitstream.writeBits(1,0),this.headerBitstream.skipBits(13),this.headerBitstream.writeBits(11,2047),this.headerBitstream.writeBits(2,0)}const a=r.data.byteLength+this.header.byteLength;this.headerBitstream.pos=30,this.headerBitstream.writeBits(13,a);const s=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(r.data),this.format._options.onFrame){const e=new Uint8Array(a);e.set(this.header,0),e.set(r.data,this.header.byteLength),this.format._options.onFrame(e,s)}await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */var Ke,Ge;!function(e){e[e.IDR=5]="IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.SPS_EXT=13]="SPS_EXT"}(Ke||(Ke={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(Ge||(Ge={}));const Xe=e=>{const t=[];let r=0;for(;r<e.length;){let i=-1,a=0;for(let t=r;t<e.length-3;t++){if(0===e[t]&&0===e[t+1]&&1===e[t+2]){i=t,a=3;break}if(t<e.length-4&&0===e[t]&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]){i=t,a=4;break}}if(-1===i)break;if(r>0&&i>r){const a=e.subarray(r,i);a.length>0&&t.push(a)}r=i+a}if(r<e.length){const i=e.subarray(r);i.length>0&&t.push(i)}return t},Ye=(e,r)=>{const i=[];let a=0;const s=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;a+r<=e.length;){let n;1===r?n=s.getUint8(a):2===r?n=s.getUint16(a,!1):3===r?n=F(s,a,!1):4===r?n=s.getUint32(a,!1):(B(r),t(!1)),a+=r;const o=e.subarray(a,a+n);i.push(o),a+=n}return i},Je=e=>{const t=[],r=e.length;for(let i=0;i<r;i++)i+2<r&&0===e[i]&&0===e[i+1]&&3===e[i+2]?(t.push(0,0),i+=2):t.push(e[i]);return new Uint8Array(t)},Ze=new Uint8Array([0,0,0,1]),et=(e,t)=>{const r=e.reduce(((e,r)=>e+t+r.byteLength),0),i=new Uint8Array(r);let a=0;for(const r of e){const e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(t){case 1:e.setUint8(a,r.byteLength);break;case 2:e.setUint16(a,r.byteLength,!1);break;case 3:M(e,a,r.byteLength,!1);break;case 4:e.setUint32(a,r.byteLength,!1)}a+=t,i.set(r,a),a+=r.byteLength}return i},tt=(e,t)=>{if(t.description){const r=3&c(t.description)[4];return Ye(e,r+1)}return Xe(e)},rt=(e,t)=>{if(t.description){const r=3&c(t.description)[4];return et(e,r+1)}return(e=>{const t=e.reduce(((e,t)=>e+Ze.byteLength+t.byteLength),0),r=new Uint8Array(t);let i=0;for(const t of e)r.set(Ze,i),i+=Ze.byteLength,r.set(t,i),i+=t.byteLength;return r})(e)},it=e=>31&e[0],at=e=>{try{const r=Xe(e),i=r.filter((e=>it(e)===Ke.SPS)),a=r.filter((e=>it(e)===Ke.PPS)),s=r.filter((e=>it(e)===Ke.SPS_EXT));if(0===i.length)return null;if(0===a.length)return null;const n=i[0],o=st(n);t(null!==o);const c=100===o.profileIdc||110===o.profileIdc||122===o.profileIdc||144===o.profileIdc;return{configurationVersion:1,avcProfileIndication:o.profileIdc,profileCompatibility:o.constraintFlags,avcLevelIndication:o.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:i,pictureParameterSets:a,chromaFormat:c?o.chromaFormatIdc:null,bitDepthLumaMinus8:c?o.bitDepthLumaMinus8:null,bitDepthChromaMinus8:c?o.bitDepthChromaMinus8:null,sequenceParameterSetExt:c?s:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},st=e=>{try{const t=new s(Je(e));t.skipBits(1),t.skipBits(2);if(7!==t.readBits(5))return null;const r=t.readAlignedByte(),i=t.readAlignedByte(),a=t.readAlignedByte();n(t);let c=null,d=null,l=null;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){c=n(t),3===c&&t.skipBits(1),d=n(t),l=n(t),t.skipBits(1);if(t.readBits(1))for(let e=0;e<(3!==c?8:12);e++){if(t.readBits(1)){const r=e<6?16:64;let i=8,a=8;for(let e=0;e<r;e++){if(0!==a){a=(i+o(t)+256)%256}i=0===a?i:a}}}}n(t);const h=n(t);if(0===h)n(t);else if(1===h){t.skipBits(1),o(t),o(t);const e=n(t);for(let r=0;r<e;r++)o(t)}n(t),t.skipBits(1),n(t),n(t);return{profileIdc:r,constraintFlags:i,levelIdc:a,frameMbsOnlyFlag:t.readBits(1),chromaFormatIdc:c,bitDepthLumaMinus8:d,bitDepthChromaMinus8:l}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},nt=(e,t)=>{if(t.description){const r=3&c(t.description)[21];return Ye(e,r+1)}return Xe(e)},ot=e=>e[0]>>1&63,ct=e=>{try{const t=Xe(e),r=t.filter((e=>ot(e)===Ge.VPS_NUT)),i=t.filter((e=>ot(e)===Ge.SPS_NUT)),a=t.filter((e=>ot(e)===Ge.PPS_NUT)),c=t.filter((e=>ot(e)===Ge.PREFIX_SEI_NUT||ot(e)===Ge.SUFFIX_SEI_NUT));if(0===i.length||0===a.length)return null;const d=i[0],l=new s(Je(d));l.skipBits(16),l.readBits(4);const h=l.readBits(3),u=l.readBits(1),{general_profile_space:m,general_tier_flag:p,general_profile_idc:f,general_profile_compatibility_flags:g,general_constraint_indicator_flags:w,general_level_idc:k}=dt(l,h);n(l);const b=n(l);3===b&&l.skipBits(1),n(l),n(l),l.readBits(1)&&(n(l),n(l),n(l),n(l));const y=n(l),T=n(l);n(l);const S=l.readBits(1);for(let e=S?0:h;e<=h;e++)n(l),n(l),n(l);n(l),n(l),n(l),n(l),n(l),n(l),l.readBits(1)&&l.readBits(1)&&lt(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&(l.skipBits(4),l.skipBits(4),n(l),n(l),l.skipBits(1));const v=n(l);if(ht(l,v),l.readBits(1)){const e=n(l);for(let t=0;t<e;t++)n(l),l.skipBits(1)}l.skipBits(1),l.skipBits(1);let C=0;l.readBits(1)&&(C=mt(l,h));let x=0;if(a.length>0){const e=a[0],t=new s(Je(e));t.skipBits(16),n(t),n(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),n(t),n(t),o(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&n(t),o(t),o(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const r=t.readBits(1),i=t.readBits(1);x=r||i?r&&!i?2:!r&&i?3:0:0}const P=[...r.length?[{arrayCompleteness:1,nalUnitType:Ge.VPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Ge.SPS_NUT,nalUnits:i}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ge.PPS_NUT,nalUnits:a}]:[],...c.length?[{arrayCompleteness:1,nalUnitType:ot(c[0]),nalUnits:c}]:[]];return{configurationVersion:1,generalProfileSpace:m,generalTierFlag:p,generalProfileIdc:f,generalProfileCompatibilityFlags:g,generalConstraintIndicatorFlags:w,generalLevelIdc:k,minSpatialSegmentationIdc:C,parallelismType:x,chromaFormatIdc:b,bitDepthLumaMinus8:y,bitDepthChromaMinus8:T,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:h+1,temporalIdNested:u,lengthSizeMinusOne:3,arrays:P}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},dt=(e,t)=>{const r=e.readBits(2),i=e.readBits(1),a=e.readBits(5);let s=0;for(let t=0;t<32;t++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let t=0;t<6;t++)n[t]=e.readBits(8);const o=e.readBits(8),c=[],d=[];for(let r=0;r<t;r++)c.push(e.readBits(1)),d.push(e.readBits(1));if(t>0)for(let r=t;r<8;r++)e.skipBits(2);for(let r=0;r<t;r++)c[r]&&e.skipBits(88),d[r]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},lt=e=>{for(let t=0;t<4;t++)for(let r=0;r<(3===t?2:6);r++){if(e.readBits(1)){const r=Math.min(64,1<<4+(t<<1));t>1&&o(e);for(let t=0;t<r;t++)o(e)}else n(e)}},ht=(e,t)=>{const r=[];for(let i=0;i<t;i++)r[i]=ut(e,i,t,r)},ut=(e,t,r,i)=>{let a=0,s=0,o=0;if(0!==t&&(s=e.readBits(1)),s){if(t===r){o=t-(n(e)+1)}else o=t-1;e.readBits(1),n(e);const s=i[o]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=i[o]}else{const t=n(e),r=n(e);for(let r=0;r<t;r++)n(e),e.readBits(1);for(let t=0;t<r;t++)n(e),e.readBits(1);a=t+r}return a},mt=(e,t)=>{if(e.readBits(1)){255===e.readBits(8)&&(e.readBits(16),e.readBits(16))}if(e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),e.readBits(1),e.readBits(1)&&(e.readBits(8),e.readBits(8),e.readBits(8))),e.readBits(1)&&(n(e),n(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(n(e),n(e),n(e),n(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&n(e),e.readBits(1)&&pt(e,!0,t)),e.readBits(1)){e.readBits(1),e.readBits(1),e.readBits(1);const t=n(e);return n(e),n(e),n(e),n(e),t}return 0},pt=(e,t,r)=>{let i=!1,a=!1,s=!1;t&&(i=1===e.readBits(1),a=1===e.readBits(1),(i||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 t=0;t<=r;t++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let r=!1;t?n(e):r=1===e.readBits(1);let o=1;if(!r){o=n(e)+1}i&&ft(e,o,s),a&&ft(e,o,s)}},ft=(e,t,r)=>{for(let i=0;i<t;i++)n(e),n(e),r&&(n(e),n(e)),e.readBits(1)},gt=e=>{const t=new s(e);if(2!==t.readBits(2))return null;const r=t.readBits(1),a=(t.readBits(1)<<1)+r;3===a&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let n=8;if(a>=2){n=t.readBits(1)?12:10}const o=t.readBits(3);let c=0,d=0;if(7!==o){if(d=t.readBits(1),1===a||3===a){const e=t.readBits(1),r=t.readBits(1);c=e||r?e&&!r?2:1:3,t.skipBits(1)}else c=1}else c=3,d=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let h=i(ye).level;for(const e of ye)if(l<=e.maxPictureSize){h=e.level;break}return{profile:a,level:h,bitDepth:n,chromaSubsampling:c,videoFullRangeFlag:d,colourPrimaries:2===o?1:1===o?6:2,transferCharacteristics:2===o?1:1===o?6:2,matrixCoefficients:7===o?0:2===o?1:1===o?6:2}},wt=function*(e){const r=new s(e),i=()=>{let e=0;for(let t=0;t<8;t++){const i=r.readAlignedByte();if(e|=(127&i)<<7*t,!(128&i))break;if(7===t&&128&i)return null}return e>=2**32-1?null:e};for(;r.getBitsLeft()>=8;){r.skipBits(1);const a=r.readBits(4),s=r.readBits(1),n=r.readBits(1);let o;if(r.skipBits(1),s&&r.skipBits(8),n){const e=i();if(null===e)return;o=e}else o=Math.floor(r.getBitsLeft()/8);t(r.pos%8==0),yield{type:a,data:e.subarray(r.pos/8,r.pos/8+o)},r.skipBits(8*o)}},kt=e=>{for(const{type:t,data:r}of wt(e)){if(1!==t)continue;const e=new s(r),i=e.readBits(3);e.readBits(1);const a=e.readBits(1);let n=0,o=0,c=0;if(a)n=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(c=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const r=e.readBits(5);for(let i=0;i<=r;i++){e.skipBits(12);const r=e.readBits(5);if(0===i&&(n=r),r>7){const t=e.readBits(1);0===i&&(o=t)}if(t){if(e.readBits(1)){const t=c+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const d=e.readBits(4),l=e.readBits(4),h=d+1;e.skipBits(h);const u=l+1;e.skipBits(u);let m=0;if(m=a?0:e.readBits(1),m&&(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 r=0;if(r=e.readBits(1)?2:e.readBits(1),r>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const p=e.readBits(1);let f=8;if(2===i&&p){f=e.readBits(1)?12:10}else i<=2&&(f=p?10:8);let g=0;1!==i&&(g=e.readBits(1));let w=1,k=1,b=0;return g||(0===i?(w=1,k=1):1===i?(w=0,k=0):12===f&&(w=e.readBits(1),w&&(k=e.readBits(1))),w&&k&&(b=e.readBits(2))),{profile:i,level:n,tier:o,bitDepth:f,monochrome:g,chromaSubsamplingX:w,chromaSubsamplingY:k,chromaSamplePosition:b}}return null},bt=e=>{const t=d(e),r=t.getUint8(9),i=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+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}},yt=[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],Tt=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,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e[t-1-i];const i=new s(r);let a=0;for(;i.getBitsLeft()>97;)if(1===i.readBits(1)){a=i.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let n=0,o=!1,c=0;for(;i.getBitsLeft()>=97;){const e=i.pos,t=i.readBits(8),r=i.readBits(16),a=i.readBits(16);if(t>63||0!==r||0!==a){i.pos=e;break}if(i.skipBits(1),n++,n>64)break;i.clone().readBits(6)+1===n&&(o=!0,c=n)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const d=c;i.pos=0,i.skipBits(a);const l=Array(d).fill(0);for(let e=d-1;e>=0;e--)i.skipBits(40),l[e]=i.readBits(1);return{modeBlockflags:l}},St=(e,r,i)=>{switch(e){case"avc":{const e=tt(i,r);let t=e.some((e=>it(e)===Ke.IDR));if(!t&&(!Y()||(()=>{if(null!==J)return J;if("undefined"==typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?J=Number(e[1]):null})()>=144))for(const r of e){if(it(r)!==Ke.SEI)continue;const e=Je(r);let i=1;do{let r=0;for(;;){const t=e[i++];if(void 0===t)break;if(r+=t,t<255)break}let a=0;for(;;){const t=e[i++];if(void 0===t)break;if(a+=t,t<255)break}if(r===6){const r=new s(e);r.pos=8*i;const a=n(r),o=r.readBits(1);if(0===a&&1===o){t=!0;break}}i+=a}while(i<e.length-1)}return t?"key":"delta"}case"hevc":return nt(i,r).some((e=>{const t=ot(e);return Ge.BLA_W_LP<=t&&t<=Ge.RSV_IRAP_VCL23}))?"key":"delta";case"vp8":return 0===(1&i[0])?"key":"delta";case"vp9":{const e=new s(i);if(2!==e.readBits(2))return null;const t=e.readBits(1);3===(e.readBits(1)<<1)+t&&e.skipBits(1);if(e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:r}of wt(i))if(1===t){const t=new s(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new s(r);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:B(e),t(!1)}};var vt;!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(vt||(vt={}));const Ct=(e,t)=>{const r=d(e);let i=0;const a=r.getUint32(i,!0);i+=4;const s=l.decode(e.subarray(i,i+a));i+=a,a>0&&(t.raw??={},t.raw.vendor??=s);const n=r.getUint32(i,!0);i+=4;for(let a=0;a<n;a++){const a=r.getUint32(i,!0);i+=4;const s=l.decode(e.subarray(i,i+a));i+=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("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.tracksTotal??=i)}break;case"TRACKTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{const e=c.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.discsTotal??=i)}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),r=d(e),i=r.getUint32(0,!1),a=r.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=r.getUint32(8+a,!1),o=l.decode(e.subarray(12+a,12+a+n)),h=r.getUint32(a+n+28),u=e.subarray(a+n+32,a+n+32+h);t.images??=[],t.images.push({data:u,mimeType:s,kind:3===i?"coverFront":4===i?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},xt=(e,t,r)=>{const i=[e],a=h.encode("Mediabunny");let s=new Uint8Array(4+a.length),n=new DataView(s.buffer);n.setUint32(0,a.length,!0),s.set(a,4),i.push(s);const o=new Set,c=(e,t)=>{const r=`${e}=${t}`,a=h.encode(r);s=new Uint8Array(4+a.length),n=new DataView(s.buffer),n.setUint32(0,a.length,!0),s.set(a,4),i.push(s),o.add(e)};for(const{key:e,value:i}of te(t))switch(e){case"title":c("TITLE",i);break;case"description":c("DESCRIPTION",i);break;case"artist":c("ARTIST",i);break;case"album":c("ALBUM",i);break;case"albumArtist":c("ALBUMARTIST",i);break;case"genre":c("GENRE",i);break;case"date":{const e=t.raw?.DATE??t.raw?.date;c("DATE",e&&"string"==typeof e?e:i.toISOString().slice(0,10))}break;case"comment":c("COMMENT",i);break;case"lyrics":c("LYRICS",i);break;case"trackNumber":c("TRACKNUMBER",i.toString());break;case"tracksTotal":c("TRACKTOTAL",i.toString());break;case"discNumber":c("DISCNUMBER",i.toString());break;case"discsTotal":c("DISCTOTAL",i.toString());break;case"images":if(!r)break;for(const e of i){const t="coverFront"===e.kind?3:"coverBack"===e.kind?4:0,r=new Uint8Array(e.mimeType.length);for(let t=0;t<e.mimeType.length;t++)r[t]=e.mimeType.charCodeAt(t);const i=h.encode(e.description??""),a=new Uint8Array(8+r.length+4+i.length+16+4+e.data.length),s=d(a);s.setUint32(0,t,!1),s.setUint32(4,r.length,!1),a.set(r,8),s.setUint32(8+r.length,i.length,!1),a.set(i,12+r.length),s.setUint32(28+r.length+i.length,e.data.length,!1),a.set(e.data,32+r.length+i.length);c("METADATA_BLOCK_PICTURE",ae(a))}break;case"raw":break;default:B(e)}if(t.raw)for(const e in t.raw){const r=t.raw[e]??t.raw[e.toLowerCase()];"vendor"===e||null==r||o.has(e)||"string"==typeof r&&c(e,r)}const l=new Uint8Array(4);d(l).setUint32(0,o.size,!0),i.splice(2,0,l);const u=i.reduce(((e,t)=>e+t.length),0),m=new Uint8Array(u);let p=0;for(const e of i)m.set(e,p),p+=e.length;return m};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class Pt{constructor(e){this.input=e}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class _t{static supports(e,t){return!1}}class It{static supports(e,t){return!1}}class Et{static supports(e,t){return!1}}class At{static supports(e,t){return!1}}const Bt=[],Ft=[],Mt=[],Dt=[],zt=e=>{if(e.prototype instanceof _t){const t=e;if(Bt.includes(t))return void console.warn("Video decoder already registered.");Bt.push(t)}else{if(!(e.prototype instanceof It))throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.");{const t=e;if(Ft.includes(t))return void console.warn("Audio decoder already registered.");Ft.push(t)}}},Rt=e=>{if(e.prototype instanceof Et){const t=e;if(Mt.includes(t))return void console.warn("Video encoder already registered.");Mt.push(t)}else{if(!(e.prototype instanceof At))throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.");{const t=e;if(Dt.includes(t))return void console.warn("Audio encoder already registered.");Dt.push(t)}}},Ot=new Uint8Array(0);class Ut{constructor(e,t,r,i,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=r,this.duration=i,this.sequenceNumber=a,e===Ot&&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(r))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<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===Ot}get microsecondTimestamp(){return Math.trunc(L*this.timestamp)}get microsecondDuration(){return Math.trunc(L*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(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new Ut(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");return new Ut(this.data,this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,this.sequenceNumber,this.byteLength)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
ne();let Nt=-1/0,Vt=-1/0,Lt=null;"undefined"!=typeof FinalizationRegistry&&(Lt=new FinalizationRegistry((e=>{const t=Date.now();"video"===e.type?(t-Nt>=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."),Nt=t),"undefined"!=typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Vt>=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."),Vt=t),"undefined"!=typeof AudioData&&e.data instanceof AudioData&&e.data.close())})));const Wt=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Ht=new Set(Wt);class qt{get displayWidth(){return this.rotation%180==0?this.codedWidth:this.codedHeight}get displayHeight(){return this.rotation%180==0?this.codedHeight:this.codedWidth}get microsecondTimestamp(){return Math.trunc(L*this.timestamp)}get microsecondDuration(){return Math.trunc(L*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,r){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!r||"object"!=typeof r)throw new TypeError("init must be an object.");if(void 0===r.format||!Ht.has(r.format))throw new TypeError("init.format must be one of: "+Wt.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.");this._data=c(e).slice(),this._layout=r.layout??Xt(r.format,r.codedWidth,r.codedHeight),this.format=r.format,this.codedWidth=r.codedWidth,this.codedHeight=r.codedHeight,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new jt(r.colorSpace)}else if("undefined"!=typeof VideoFrame&&e 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.");this._data=e,this._layout=null,this.format=e.format,this.codedWidth=e.displayWidth,this.codedHeight=e.displayHeight,this.rotation=r?.rotation??0,this.timestamp=r?.timestamp??e.timestamp/1e6,this.duration=r?.duration??(e.duration??0)/1e6,this.colorSpace=new jt(e.colorSpace)}else{if(!("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{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 qt(new VideoFrame(e,{timestamp:Math.trunc(r.timestamp*L),duration:Math.trunc((r.duration??0)*L)||void 0}),r);let i=0,a=0;if("naturalWidth"in e?(i=e.naturalWidth,a=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,a=e.videoHeight):"width"in e&&(i=Number(e.width),a=Number(e.height)),!i||!a)throw new TypeError("Could not determine dimensions.");const s=new OffscreenCanvas(i,a),n=s.getContext("2d",{alpha:G(),willReadFrequently:!0});t(n),n.drawImage(e,0,0),this._data=s,this._layout=null,this.format="RGBX",this.codedWidth=i,this.codedHeight=a,this.rotation=r.rotation??0,this.timestamp=r.timestamp,this.duration=r.duration??0,this.colorSpace=new jt({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}Lt?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return t(null!==this._data),$t(this._data)?new qt(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(t(this._layout),new qt(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})):new qt(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation})}close(){this._closed||(Lt?.unregister(this),$t(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Gt(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. Please manually provide an RGB pixel format in the options instead.");if(t(null!==this._data),!$t(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),r=t.allocationSize(e);return t.close(),r}return $t(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}async copyTo(e,r={}){if(!T(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Gt(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. Please manually provide an RGB pixel format in the options instead.");if(t(null!==this._data),!$t(this._data)&&(r.colorSpace||r.format&&r.format!==this.format||r.layout||r.rect)){const t=this.toVideoFrame(),i=await t.copyTo(e,r);return t.close(),i}if($t(this._data))return this._data.copyTo(e,r);if(this._data instanceof Uint8Array){t(this._layout);return c(e).set(this._data),this._layout}{const r=this._data.getContext("2d");t(r);const i=r.getImageData(0,0,this.codedWidth,this.codedHeight);return c(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return t(null!==this._data),$t(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,r,i,a,s,n,o,c){let d=0,l=0,h=this.displayWidth,u=this.displayHeight,m=0,p=0,f=this.displayWidth,g=this.displayHeight;if(void 0!==s?(d=t,l=r,h=i,u=a,m=s,p=n,void 0!==o?(f=o,g=c):(f=h,g=u)):(m=t,p=r,void 0!==i&&(f=i,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(d))throw new TypeError("sx must be a number.");if(!Number.isFinite(l))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(u)||u<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(p))throw new TypeError("dy must be a number.");if(!Number.isFinite(f)||f<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:d,sy:l,sWidth:h,sHeight:u}=this._rotateSourceRegion(d,l,h,u,this.rotation));const w=this.toCanvasImageSource();e.save();const k=m+f/2,b=p+g/2;e.translate(k,b),e.rotate(this.rotation*Math.PI/180);const y=this.rotation%180==0?1:f/g;e.scale(1/y,y),e.drawImage(w,d,l,h,u,-f/2,-g/2,f,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&&Kt(t.crop,"options.");const r=e.canvas.width,i=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180==0?[this.codedWidth,this.codedHeight]:[this.codedHeight,this.codedWidth];let o,c,d,l;t.crop&&Qt(t.crop,s,n);const{sx:h,sy:u,sWidth:m,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,d=r,l=i;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],h="contain"===t.fit?Math.min(r/e,i/a):Math.max(r/e,i/a);d=e*h,l=a*h,o=(r-d)/2,c=(i-l)/2}e.save();const f=a%180==0?1:d/l;e.translate(r/2,i/2),e.rotate(a*Math.PI/180),e.scale(1/f,f),e.translate(-r/2,-i/2),e.drawImage(this.toCanvasImageSource(),h,u,m,p,o,c,d,l),e.restore()}_rotateSourceRegion(e,t,r,i,a){return 90===a?[e,t,r,i]=[t,this.codedHeight-e-r,i,r]:180===a?[e,t]=[this.codedWidth-e-r,this.codedHeight-t-i]:270===a&&([e,t,r,i]=[this.codedWidth-t-i,e,i,r]),{sx:e,sy:t,sWidth:r,sHeight:i}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(t(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask((()=>e.close())),e}return this._data}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()}}class jt{constructor(e){this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const $t=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,Qt=(e,r,i)=>{e.left=Math.min(e.left,r),e.top=Math.min(e.top,i),e.width=Math.min(e.width,r-e.left),e.height=Math.min(e.height,i-e.top),t(e.width>=0),t(e.height>=0)},Kt=(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.")},Gt=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.")}},Xt=(e,t,r)=>{const i=Yt(e),a=[];let s=0;for(const e of i){const i=Math.ceil(t/e.widthDivisor),n=Math.ceil(r/e.heightDivisor),o=i*e.sampleBytes,c=o*n;a.push({offset:s,stride:o}),s+=c}return a},Yt=e=>{const r=(e,t,r,i,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:r,heightDivisor:i},{sampleBytes:t,widthDivisor:r,heightDivisor:i}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return r(1,1,2,2,!1);case"I420P10":case"I420P12":return r(2,2,2,2,!1);case"I420A":return r(1,1,2,2,!0);case"I420AP10":case"I420AP12":return r(2,2,2,2,!0);case"I422":return r(1,1,2,1,!1);case"I422P10":case"I422P12":return r(2,2,2,1,!1);case"I422A":return r(1,1,2,1,!0);case"I422AP10":case"I422AP12":return r(2,2,2,1,!0);case"I444":return r(1,1,1,1,!1);case"I444P10":case"I444P12":return r(2,2,1,1,!1);case"I444A":return r(1,1,1,1,!0);case"I444AP10":case"I444AP12":return r(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:B(e),t(!1)}},Jt=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Zt{get microsecondTimestamp(){return Math.trunc(L*this.timestamp)}get microsecondDuration(){return Math.trunc(L*this.duration)}constructor(e){if(this._closed=!1,ar(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||"object"!=typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Jt.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/(er(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let r;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)r=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const i=this.numberOfFrames*this.numberOfChannels*er(this.format);if(r.byteLength<i)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}Lt?.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&&!Jt.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,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const i=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(i>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const a=er(t),s=tr(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?i:i*this.numberOfChannels)*a}copyTo(e,t){if(!T(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&&!Jt.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{planeIndex:r,format:i,frameCount:a,frameOffset:s}=t,n=i??this.format;if(!n)throw new Error("Destination format not determined");const o=this.numberOfFrames,c=this.numberOfChannels,l=s??0;if(l>=o)throw new RangeError("frameOffset out of range");const h=void 0!==a?a:o-l;if(h>o-l)throw new RangeError("frameCount out of range");const u=er(n),m=tr(n);if(m&&r>=c)throw new RangeError("planeIndex out of range");if(!m&&0!==r)throw new RangeError("planeIndex out of range");const p=(m?h:h*c)*u;if(e.byteLength<p)throw new RangeError("Destination buffer is too small");const f=d(e),g=ir(n);if(ar(this._data))if(m)if("f32-planar"===n)this._data.copyTo(e,{planeIndex:r,frameOffset:l,frameCount:h,format:"f32-planar"});else{const e=new ArrayBuffer(4*h),t=new Float32Array(e);this._data.copyTo(t,{planeIndex:r,frameOffset:l,frameCount:h,format:"f32-planar"});const i=new DataView(e);for(let e=0;e<h;e++){g(f,e*u,i.getFloat32(4*e,!0))}}else{const e=c,t=new Float32Array(h);for(let r=0;r<e;r++){this._data.copyTo(t,{planeIndex:r,frameOffset:l,frameCount:h,format:"f32-planar"});for(let i=0;i<h;i++){g(f,(i*e+r)*u,t[i])}}}else{const e=this._data,t=d(e),i=this.format,a=rr(i),s=er(i),n=tr(i);for(let e=0;e<h;e++)if(m){let i;i=n?(r*o+(e+l))*s:((e+l)*c+r)*s;g(f,e*u,a(t,i))}else for(let r=0;r<c;r++){let i;i=n?(r*o+(e+l))*s:((e+l)*c+r)*s;g(f,(e*c+r)*u,a(t,i))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(ar(this._data)){const e=new Zt(this._data.clone());return e.setTimestamp(this.timestamp),e}return new Zt({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(Lt?.unregister(this),ar(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(ar(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(tr(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let r=0;r<this.numberOfChannels;r++)this.copyTo(new Uint8Array(t,r*e,e),{planeIndex:r,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})}}return 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()})}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 r=0;r<this.numberOfChannels;r++)this.copyTo(t,{planeIndex:r,format:"f32-planar"}),e.copyToChannel(t,r);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,s=Math.floor(24e4/r);let n=0,o=a;for(;o>0;){const a=Math.min(s,o),c=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(c.subarray(t*a,(t+1)*a),t,n);yield new Zt({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:c}),n+=a,o-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=e.numberOfChannels,i=e.sampleRate,a=e.length,s=Math.floor(24e4/r);let n=0,o=a;const c=[];for(;o>0;){const a=Math.min(s,o),d=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(d.subarray(t*a,(t+1)*a),t,n);const l=new Zt({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:d});c.push(l),n+=a,o-=a}return c}}const er=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")}},tr=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},rr=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)}},ir=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,z(127.5*(r+1),0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,z(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,z(Math.round(2147483647*r),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},ar=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,sr=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.")},nr=e=>{if(!oe(e))throw new TypeError("timestamp must be a number.")},or=(e,t,r)=>r.verifyKeyPackets?t.then((async t=>{if(!t||"delta"===t.type)return t;const r=await e.determinePacketType(t);return r&&(t.type=r),t})):t;class cr{constructor(e){if(!(e instanceof yr))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(e={}){if(sr(e),this._track.input._disposed)throw new Ja;return or(this._track,this._track._backing.getFirstPacket(e),e)}getPacket(e,t={}){if(nr(e),sr(t),this._track.input._disposed)throw new Ja;return or(this._track,this._track._backing.getPacket(e,t),t)}getNextPacket(e,t={}){if(!(e instanceof Ut))throw new TypeError("packet must be an EncodedPacket.");if(sr(t),this._track.input._disposed)throw new Ja;return or(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,r={}){if(nr(e),sr(r),this._track.input._disposed)throw new Ja;if(!r.verifyKeyPackets)return this._track._backing.getKeyPacket(e,r);const i=await this._track._backing.getKeyPacket(e,r);if(!i)return i;t("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/this._track.timeResolution,r):i}async getNextKeyPacket(e,r={}){if(!(e instanceof Ut))throw new TypeError("packet must be an EncodedPacket.");if(sr(r),this._track.input._disposed)throw new Ja;if(!r.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,r);const i=await this._track._backing.getNextKeyPacket(e,r);if(!i)return i;t("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,r):i}packets(e,t,r={}){if(void 0!==e&&!(e instanceof Ut))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!r?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Ut))throw new TypeError("endPacket must be an EncodedPacket.");if(sr(r),this._track.input._disposed)throw new Ja;const i=[];let{promise:a,resolve:s}=I(),{promise:n,resolve:o}=I(),c=!1,d=!1,l=null;const h=[];(async()=>{let l=e??await this.getFirstPacket(r);for(;l&&!d&&!this._track.input._disposed&&!(t&&l.sequenceNumber>=t?.sequenceNumber);)i.length>Math.max(2,h.length)?(({promise:n,resolve:o}=I()),await n):(i.push(l),s(),({promise:a,resolve:s}=I()),l=await this.getNextPacket(l,r));c=!0,s()})().catch((e=>{l||(l=e,s())}));const u=this._track;return{async next(){for(;;){if(u.input._disposed)throw new Ja;if(d)return{value:void 0,done:!0};if(l)throw l;if(i.length>0){const e=i.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(d=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class dr{constructor(e,t){this.onSample=e,this.onError=t}}class lr{mediaSamplesInRange(e=0,t=1/0){nr(e),nr(t);const r=[];let i=!1,a=null,{promise:s,resolve:n}=I(),{promise:o,resolve:c}=I(),d=!1,l=!1,h=!1,u=null;(async()=>{const m=await this._createDecoder((o=>{c(),o.timestamp>=t&&(l=!0),l?o.close():(a&&(o.timestamp>e?(r.push(a),i=!0):a.close()),o.timestamp>=e&&(r.push(o),i=!0),a=i?null:o,r.length>0&&(n(),({promise:s,resolve:n}=I())))}),(e=>{u||(u=e,n())})),p=this._createPacketSink(),f=await p.getKeyPacket(e,{verifyKeyPackets:!0})??await p.getFirstPacket();let g,w=f;if(t<1/0){const e=await p.getPacket(t),r=e?"key"===e.type&&e.timestamp===t?e:await p.getNextKeyPacket(e,{verifyKeyPackets:!0}):null;r&&(g=r)}const k=p.packets(f??void 0,g);for(await k.next();w&&!l&&!this._track.input._disposed;){const e=hr(r.length);if(r.length+m.getDecodeQueueSize()>e){({promise:o,resolve:c}=I()),await o;continue}m.decode(w);const t=await k.next();if(t.done)break;w=t.value}await k.return(),h||this._track.input._disposed||await m.flush(),m.close(),!i&&a&&r.push(a),d=!0,n()})().catch((e=>{u||(u=e,n())}));const m=this._track,p=()=>{a?.close();for(const e of r)e.close()};return{async next(){for(;;){if(m.input._disposed)throw p(),new Ja;if(h)return{value:void 0,done:!0};if(u)throw p(),u;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(d)return{value:void 0,done:!0};await s}},return:async()=>(h=!0,l=!0,c(),n(),p(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e){(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),i=[],a=[];let{promise:s,resolve:n}=I(),{promise:o,resolve:c}=I(),d=!1,l=!1,h=null;const u=e=>{a.push(e),n(),({promise:s,resolve:n}=I())};(async()=>{const e=await this._createDecoder((e=>{if(c(),l)return void e.close();let t=0;for(;i.length>0&&e.timestamp-i[0]>-1e-10;)t++,i.shift();if(t>0)for(let r=0;r<t;r++)u(r<t-1?e.clone():e);else e.close()}),(e=>{h||(h=e,n())})),s=this._createPacketSink();let m=null,p=null,f=-1;const g=async()=>{t(p);let r=p;for(e.decode(r);r.sequenceNumber<f;){const i=hr(a.length);for(;a.length+e.getDecodeQueueSize()>i&&!l;)({promise:o,resolve:c}=I()),await o;if(l)break;const n=await s.getNextPacket(r);t(n),e.decode(n),r=n}f=-1},w=async()=>{await e.flush();for(let e=0;e<i.length;e++)u(null);i.length=0};for await(const e of r){if(nr(e),l||this._track.input._disposed)break;const t=await s.getPacket(e),r=t&&await s.getKeyPacket(e,{verifyKeyPackets:!0});r?(m&&(r.sequenceNumber!==p.sequenceNumber||t.timestamp<m.timestamp)&&(await g(),await w()),i.push(t.timestamp),f=Math.max(t.sequenceNumber,f),m=t,p=r):(-1!==f&&(await g(),await w()),u(null),m=null)}l||this._track.input._disposed||(-1!==f&&await g(),await w()),e.close(),d=!0,n()})().catch((e=>{h||(h=e,n())}));const m=this._track,p=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(m.input._disposed)throw p(),new Ja;if(l)return{value:void 0,done:!0};if(h)throw p(),h;if(a.length>0){const e=a.shift();return t(void 0!==e),c(),{value:e,done:!1}}if(d)return{value:void 0,done:!0};await s}},return:async()=>(l=!0,c(),n(),p(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const hr=e=>0===e?40:8;class ur extends dr{constructor(e,r,i,a,s,n){super(e,r),this.codec=i,this.decoderConfig=a,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new j,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const o=Bt.find((e=>e.supports(i,a)));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=a,this.customDecoder.onSample=e=>{if(!(e instanceof qt))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=>{if(this.alphaQueue.length>0){const r=this.alphaQueue.shift();t(void 0!==r),this.mergeAlpha(e,r)}else this.colorQueue.push(e)};if("avc"===i&&this.decoderConfig.description&&Y()){const e=(e=>{try{const t=d(e);let r=0;const i=t.getUint8(r++),a=t.getUint8(r++),s=t.getUint8(r++),n=t.getUint8(r++),o=3&t.getUint8(r++),c=31&t.getUint8(r++),l=[];for(let i=0;i<c;i++){const i=t.getUint16(r,!1);r+=2,l.push(e.subarray(r,r+i)),r+=i}const h=t.getUint8(r++),u=[];for(let i=0;i<h;i++){const i=t.getUint16(r,!1);r+=2,u.push(e.subarray(r,r+i)),r+=i}const m={configurationVersion:i,avcProfileIndication:a,profileCompatibility:s,avcLevelIndication:n,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:u,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&r+4<=e.length){const i=3&t.getUint8(r++),a=7&t.getUint8(r++),s=7&t.getUint8(r++),n=t.getUint8(r++);m.chromaFormat=i,m.bitDepthLumaMinus8=a,m.bitDepthChromaMinus8=s;const o=[];for(let i=0;i<n;i++){const i=t.getUint16(r,!1);r+=2,o.push(e.subarray(r,r+i)),r+=i}m.sequenceParameterSetExt=o}return m}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}})(c(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=st(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const r=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=r,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(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(t(this.decoder),Q()||_(this.inputTimestamps,e.timestamp,(e=>e)),Y()&&0===this.currentPacketIndex&&"avc"===this.codec){const t=tt(e.data,this.decoderConfig).filter((e=>{const t=it(e);return!(t>=20&&t<=31)})),r=rt(t,this.decoderConfig);e=new Ut(r,e.type,e.timestamp,e.duration)}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new mr}catch(t){return console.error("Due to an error, only color data will be decoded.",t),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const r=this.colorQueue.shift();t(void 0!==r),this.mergeAlpha(r,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();t(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},r=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=r,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const r=St(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===r),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(r??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){return nt(e,this.decoderConfig).some((e=>{const t=ot(e);return t===Ge.RASL_N||t===Ge.RASL_R}))}sampleHandler(e){if(Q()){if(this.sampleQueue.length>0&&e.timestamp>=i(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}_(this.sampleQueue,e,(e=>e.timestamp))}else{const r=this.inputTimestamps.shift();t(void 0!==r),e.setTimestamp(r),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}mergeAlpha(e,r){if(!r){const t=new qt(e);return void this.sampleHandler(t)}t(this.merger),this.merger.update(e,r),e.close(),r.close();const i=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:e.duration??void 0}),a=new qt(i);this.sampleHandler(a)}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call((()=>this.customDecoder.flush())):(t(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),this.colorQueue.forEach((e=>e.close())),this.colorQueue.length=0,this.alphaQueue.forEach((e=>e?.close())),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Q()){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())):(t(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}}class mr{constructor(){"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)}createProgram(){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){const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){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 i=this.gl.getAttribLocation(this.program,"a_position"),a=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){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}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class pr extends lr{constructor(e){if(!(e instanceof Tr))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,r){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 i=this._track.codec,a=this._track.rotation,s=await this._track.getDecoderConfig(),n=this._track.timeResolution;return t(i&&s),new ur(e,r,i,s,a,n)}_createPacketSink(){return new cr(this._track)}async getSample(e){nr(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class fr{constructor(e,t={}){if(this._nextCanvasIndex=0,!(e instanceof Tr))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&&Kt(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.");const r=t.rotation??e.rotation,[i,a]=r%180==0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],s=t.crop;s&&Qt(s,i,a);let[n,o]=s?[s.width,s.height]:[i,a];const c=n/o;void 0!==t.width&&void 0===t.height?(n=t.width,o=Math.round(n/c)):void 0===t.width&&void 0!==t.height?(o=t.height,n=Math.round(o*c)):void 0!==t.width&&void 0!==t.height&&(n=t.width,o=t.height),this._videoTrack=e,this._alpha=t.alpha??!1,this._width=n,this._height=o,this._rotation=r,this._crop=s,this._fit=t.fit??"fill",this._videoSampleSink=new pr(e),this._canvasPool=Array.from({length:t.poolSize??0},(()=>null))}_videoSampleToWrappedCanvas(e){let r=this._canvasPool[this._nextCanvasIndex],i=!1;r||("undefined"!=typeof document?(r=document.createElement("canvas"),r.width=this._width,r.height=this._height):r=new OffscreenCanvas(this._width,this._height),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),i=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=r.getContext("2d",{alpha:this._alpha||G()});t(a),a.resetTransform(),i||(!this._alpha&&G()?(a.fillStyle="black",a.fillRect(0,0,this._width,this._height)):a.clearRect(0,0,this._width,this._height)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});const s={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),s}async getCanvas(e){nr(e);const t=await this._videoSampleSink.getSample(e);return t&&this._videoSampleToWrappedCanvas(t)}canvases(e=0,t=1/0){return D(this._videoSampleSink.samples(e,t),(e=>this._videoSampleToWrappedCanvas(e)))}canvasesAtTimestamps(e){return D(this._videoSampleSink.samplesAtTimestamps(e),(e=>e&&this._videoSampleToWrappedCanvas(e)))}}class gr extends dr{constructor(e,t,r,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new j,this.customDecoderQueueSize=0,this.currentTimestamp=null;const a=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const r=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const a=i.sampleRate;t.setTimestamp(Math.round(r*a)/a),e(t)},s=Ft.find((e=>e.supports(r,i)));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof Zt))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoderCallSerializer.call((()=>this.customDecoder.init()));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new Zt(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(t(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call((()=>this.customDecoder.decode(e))).then((()=>this.customDecoderQueueSize--))):(t(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call((()=>this.customDecoder.flush())):(t(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call((()=>this.customDecoder.close())):(t(this.decoder),this.decoder.close())}}class wr extends dr{constructor(e,r,i){super(e,r),this.decoderConfig=i,this.currentTimestamp=null,t(pe.includes(i.codec)),this.codec=i.codec;const{dataType:a,sampleSize:s,littleEndian:n}=ze(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,r=0,i=~e;128&i&&(i&=-129,t=-1),r=5+((240&i)>>4);const a=(1<<r|(15&i)<<r-4|1<<r-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===a?this.readInputValue=(e,t)=>(e=>{let t=0,r=0,i=85^e;128&i&&(i&=-129,t=-1),r=4+((240&i)>>4);let a=0;return a=4!==r?1<<r|(15&i)<<r-4|1<<r-5:i<<1|1,0===t?a:-a})(e.getUint8(t)):t(!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):t(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>F(e,t,n)-2**23:"signed"===a?this.readInputValue=(e,t)=>((e,t,r)=>F(e,t,r)<<8>>8)(e,t,n):t(!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):t(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):t(!1);break;default:B(s),t(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,r)=>e.setUint8(t,r+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r<<8,!0);break;case 4:this.outputSampleSize=4,"float"===a?(this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0);break;default:B(s),t(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=d(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(i),s=new DataView(a);for(let e=0;e<r*this.decoderConfig.numberOfChannels;e++){const r=e*this.inputSampleSize,i=e*this.outputSampleSize,a=this.readInputValue(t,r);this.writeOutputValue(s,i,a)}const n=r/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 Zt({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:o});this.onSample(c)}async flush(){}close(){}}class kr extends lr{constructor(e){if(!(e instanceof Sr))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,r){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 i=this._track.codec,a=await this._track.getDecoderConfig();return t(i&&a),pe.includes(a.codec)?new wr(e,r,a):new gr(e,r,i,a)}_createPacketSink(){return new cr(this._track)}async getSample(e){nr(e);for await(const t of this.mediaSamplesAtTimestamps([e]))return t;throw new Error("Internal error: Iterator returned nothing.")}samples(e=0,t=1/0){return this.mediaSamplesInRange(e,t)}samplesAtTimestamps(e){return this.mediaSamplesAtTimestamps(e)}}class br{constructor(e){if(!(e instanceof Sr))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new kr(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e){nr(e);const t=await this._audioSampleSink.getSample(e);return t&&this._audioSampleToWrappedArrayBuffer(t)}buffers(e=0,t=1/0){return D(this._audioSampleSink.samples(e,t),(e=>this._audioSampleToWrappedArrayBuffer(e)))}buffersAtTimestamps(e){return D(this._audioSampleSink.samplesAtTimestamps(e),(e=>e&&this._audioSampleToWrappedArrayBuffer(e)))}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class yr{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Tr}isAudioTrack(){return this instanceof Sr}get id(){return this._backing.getId()}get internalCodecId(){return this._backing.getInternalCodecId()}get languageCode(){return this._backing.getLanguageCode()}get name(){return this._backing.getName()}get timeResolution(){return this._backing.getTimeResolution()}get disposition(){return this._backing.getDisposition()}getFirstTimestamp(){return this._backing.getFirstTimestamp()}computeDuration(){return this._backing.computeDuration()}async computePacketStats(e=1/0){const t=new cr(this);let r=1/0,i=-1/0,a=0,s=0;for await(const n of t.packets(void 0,void 0,{metadataOnly:!0})){if(a>=e&&n.timestamp>=i)break;r=Math.min(r,n.timestamp),i=Math.max(i,n.timestamp+n.duration),a++,s+=n.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(i-r)).toPrecision(16)):0,averageBitrate:a?Number((8*s/(i-r)).toPrecision(16)):0}}}class Tr extends yr{constructor(e,t){super(e,t),this._backing=t}get type(){return"video"}get codec(){return this._backing.getCodec()}get codedWidth(){return this._backing.getCodedWidth()}get codedHeight(){return this._backing.getCodedHeight()}get rotation(){return this._backing.getRotation()}get displayWidth(){return this._backing.getRotation()%180==0?this._backing.getCodedWidth():this._backing.getCodedHeight()}get displayHeight(){return this._backing.getRotation()%180==0?this._backing.getCodedHeight():this._backing.getCodedWidth()}getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}canBeTransparent(){return this._backing.canBeTransparent()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const r=this._backing.getCodec();if(t(null!==r),Bt.some((t=>t.supports(r,e))))return!0;if("undefined"==typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ut))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");if(null===this.codec)return null;const r=await this.getDecoderConfig();return t(r),St(this.codec,r,e.data)}}class Sr extends yr{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}get codec(){return this._backing.getCodec()}get numberOfChannels(){return this._backing.getNumberOfChannels()}get sampleRate(){return this._backing.getSampleRate()}getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await this._backing.getDecoderConfig();return e?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const r=this._backing.getCodec();if(t(null!==r),Ft.some((t=>t.supports(r,e))))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"==typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Ut))throw new TypeError("packet must be an EncodedPacket.");return null===this.codec?null:"key"}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const vr=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`}return t},Cr=16,xr=e=>{let t=ds(e);const r=ks(e,4);let i=8;1===t&&(t=ms(e),i=16);const a=t-i;return a<0?null:{name:r,totalSize:t,headerSize:i,contentSize:a}},Pr=e=>hs(e)/65536,_r=e=>hs(e)/1073741824,Ir=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;const r=is(e);if(t|=127&r,!(128&r))break}return t},Er=e=>{let t=ss(e);return e.skip(2),t=Math.min(t,e.remainingLength),l.decode(rs(e,t))},Ar=e=>{const t=xr(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const r=ds(e);e.skip(4);const i=rs(e,t.contentSize-8);switch(r){case 1:return l.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new ce(i,"image/jpeg");case 14:return new ce(i,"image/png");case 27:return new ce(i,"image/bmp");default:return i}};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class Br extends Pt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.currentFragment=null,this.lastReadFragment=null,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map((e=>e.computeDuration())));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.tracks.map((e=>e.inputTrack))}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.tracks.map((e=>e.inputTrack.getCodecParameterString())));return vr({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some((e=>"video"===e.info?.type)),hasAudio:this.tracks.some((e=>"audio"===e.info?.type)),codecStrings:e.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,8,Cr);if(t instanceof Promise&&(t=await t),!t)break;const r=e,i=xr(t);if(!i)break;if("ftyp"===i.name){const e=ks(t,4);this.isQuickTime="qt  "===e}else if("moov"===i.name){let e=this.reader.requestSlice(t.filePos,i.contentSize);if(e instanceof Promise&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks.sort(((e,t)=>Number(t.disposition.default)-Number(e.disposition.default)));for(const e of this.tracks){const t=e.editListPreviousSegmentDurations/this.movieTimescale;e.editListOffset-=Math.round(t*e.timescale)}break}e=r+i.totalSize}if(this.isFragmented&&null!==this.reader.fileSize){let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),t(e);const r=ds(e),i=this.reader.fileSize-r;if(i>=0&&i<=this.reader.fileSize-Cr){let e=this.reader.requestSliceRange(i,8,Cr);if(e instanceof Promise&&(e=await e),e){const t=xr(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=await r),r&&this.readContiguousBoxes(r)}}}}})()}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};e.sampleTable=r,t(this.moovSlice);const a=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(a),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&pe.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){t("audio"===e.info?.type);const a=ze(e.info.codec),s=[],n=[];for(let t=0;t<r.sampleToChunk.length;t++){const o=r.sampleToChunk[t],c=r.sampleToChunk[t+1],d=(c?c.startChunkIndex:r.chunkOffsets.length)-o.startChunkIndex;for(let t=0;t<d;t++){const c=o.startSampleIndex+t*o.samplesPerChunk,d=c+o.samplesPerChunk,l=P(r.sampleTimingEntries,c,(e=>e.startIndex)),h=r.sampleTimingEntries[l],u=P(r.sampleTimingEntries,d,(e=>e.startIndex)),m=r.sampleTimingEntries[u],p=h.startDecodeTimestamp+(c-h.startIndex)*h.delta,f=m.startDecodeTimestamp+(d-m.startIndex)*m.delta-p,g=i(s);g&&g.delta===f?g.count++:s.push({startIndex:o.startChunkIndex+t,startDecodeTimestamp:p,count:1,delta:f});const w=o.samplesPerChunk*a.sampleSize*e.info.numberOfChannels;n.push(w)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}r.sampleTimingEntries=s,r.sampleSizes=n}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const e of r.sampleTimingEntries)for(let t=0;t<e.count;t++)r.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+t*e.delta,sampleIndex:e.startIndex+t});for(const e of r.sampleCompositionTimeOffsets)for(let t=0;t<e.count;t++){const i=e.startIndex+t,a=r.presentationTimestamps[i];a&&(a.presentationTimestamp+=e.offset)}r.presentationTimestamps.sort(((e,t)=>e.presentationTimestamp-t.presentationTimestamp)),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;e<r.presentationTimestamps.length;e++)r.presentationTimestampIndexMap[r.presentationTimestamps[e].sampleIndex]=e}return r}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let r=this.reader.requestSliceRange(e,8,Cr);r instanceof Promise&&(r=await r),t(r);const i=xr(r);t("moof"===i?.name);let a=this.reader.requestSlice(e,i.totalSize);a instanceof Promise&&(a=await a),t(a),this.traverseBox(a);const s=this.lastReadFragment;t(s&&s.moofOffset===e);for(const[,e]of s.trackData){const t=e.track,{fragmentPositionCache:r}=t;if(!e.startTimestampIsFinal){const i=t.fragmentLookupTable.find((e=>e.moofOffset===s.moofOffset));if(i)Nr(e,i.timestamp);else{const t=P(r,s.moofOffset-1,(e=>e.moofOffset));if(-1!==t){const i=r[t];Nr(e,i.endTimestamp)}}e.startTimestampIsFinal=!0}const i=P(r,e.startTimestamp,(e=>e.startTimestamp));-1!==i&&r[i].moofOffset===s.moofOffset||r.splice(i+1,0,{moofOffset:s.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp})}return s}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){if(!this.traverseBox(e))break}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,r=xr(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){const a=e.filePos,n=xr(e);if(!n)return!1;const o=e.filePos,c=a+n.totalSize;switch(n.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"wave":this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mvhd":{const t=is(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=ds(e),this.movieDurationInTimescale=ms(e)):(e.skip(8),this.movieTimescale=ds(e),this.movieDurationInTimescale=ds(e))}break;case"trak":{const t={id:-1,demuxer:this,inputTrack:null,disposition:{...ue},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:R,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(o,n.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info)if("video"===t.info.type&&-1!==t.info.width){const e=t;t.inputTrack=new Tr(this.input,new Mr(e)),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.inputTrack=new Sr(this.input,new Dr(e)),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const i=this.currentTrack;if(!i)break;const a=is(e),s=!!(1&ns(e));if(i.disposition.default=s,0===a)e.skip(8),i.id=ds(e),e.skip(4),i.durationInMovieTimescale=ds(e);else{if(1!==a)throw new Error(`Incorrect track header version ${a}.`);e.skip(16),i.id=ds(e),e.skip(4),i.durationInMovieTimescale=ms(e)}e.skip(16);const n=[Pr(e),Pr(e),_r(e),Pr(e),Pr(e),_r(e),Pr(e),Pr(e),_r(e)],o=r(U(Vr(n),90));t(0===o||90===o||180===o||270===o),i.rotation=o}break;case"elst":{const t=this.currentTrack;if(!t)break;const r=is(e);e.skip(3);let i=!1,a=0;const s=ds(e);for(let n=0;n<s;n++){const s=1===r?ms(e):ds(e),n=1===r?ps(e):hs(e),o=Pr(e);if(0!==s){if(i){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,i=!0}else a+=s}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const r=is(e);e.skip(3),0===r?(e.skip(8),t.timescale=ds(e),t.durationInMediaTimescale=ds(e)):1===r&&(e.skip(16),t.timescale=ds(e),t.durationInMediaTimescale=ms(e));let i=ss(e);if(i>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&i))+t.languageCode,i>>=5;V(t.languageCode)||(t.languageCode=R)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const r=ks(e,4);"vide"===r?t.info={type:"video",width:-1,height:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===r&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=a,this.readContiguousBoxes(e.slice(o,n.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const r=is(e);e.skip(3);const i=ds(e);for(let a=0;a<i;a++){const i=e.filePos,a=xr(e);if(!a)break;t.internalCodecId=a.name;const s=a.name.toLowerCase();if("video"===t.info.type)"avc1"===s||"avc3"===s?(t.info.codec="avc",t.info.avcType="avc1"===s?1:3):"hvc1"===s||"hev1"===s?t.info.codec="hevc":"vp08"===s?t.info.codec="vp8":"vp09"===s?t.info.codec="vp9":"av01"===s?t.info.codec="av1":console.warn(`Unsupported video codec (sample entry type '${a.name}').`),e.skip(24),t.info.width=ss(e),t.info.height=ss(e),e.skip(50),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos));else{"mp4a"===s||("opus"===s?t.info.codec="opus":"flac"===s?t.info.codec="flac":"twos"===s||"sowt"===s||"raw "===s||"in24"===s||"in32"===s||"fl32"===s||"fl64"===s||"lpcm"===s||"ipcm"===s||"fpcm"===s||("ulaw"===s?t.info.codec="ulaw":"alaw"===s?t.info.codec="alaw":console.warn(`Unsupported audio codec (sample entry type '${a.name}').`))),e.skip(8);const n=ss(e);e.skip(6);let o=ss(e),c=ss(e);e.skip(4);let d=ds(e)/65536;if(0===r&&n>0)if(1===n)e.skip(4),c=8*ds(e),e.skip(8);else if(2===n){e.skip(4),d=ws(e),o=ds(e),e.skip(4),c=ds(e);const r=ds(e);if(e.skip(8),"lpcm"===s){const e=c+7>>3,i=Boolean(1&r),a=Boolean(2&r),s=4&r?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=a?"pcm-f32be":"pcm-f32"):s&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=a?"pcm-s16be":"pcm-s16":3===e?t.info.codec=a?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=a?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&console.warn("Unsupported PCM format.")}}"opus"===t.info.codec&&(d=Me),t.info.numberOfChannels=o,t.info.sampleRate=d,"twos"===s?8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16be":(console.warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null):"sowt"===s?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):"raw "===s?t.info.codec="pcm-u8":"in24"===s?t.info.codec="pcm-s24be":"in32"===s?t.info.codec="pcm-s32be":"fl32"===s?t.info.codec="pcm-f32be":"fl64"===s?t.info.codec="pcm-f64be":"ipcm"===s?t.info.codec="pcm-s16be":"fpcm"===s&&(t.info.codec="pcm-f32be"),this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos))}}}break;case"avcC":{const r=this.currentTrack;if(!r)break;t(r.info),r.info.codecDescription=rs(e,n.contentSize)}break;case"hvcC":{const r=this.currentTrack;if(!r)break;t(r.info),r.info.codecDescription=rs(e,n.contentSize)}break;case"vpcC":{const r=this.currentTrack;if(!r)break;t("video"===r.info?.type),e.skip(4);const i=is(e),a=is(e),s=is(e),n=s>>4,o=s>>1&7,c=1&s,d=is(e),l=is(e),h=is(e);r.info.vp9CodecInfo={profile:i,level:a,bitDepth:n,chromaSubsampling:o,videoFullRangeFlag:c,colourPrimaries:d,transferCharacteristics:l,matrixCoefficients:h}}break;case"av1C":{const r=this.currentTrack;if(!r)break;t("video"===r.info?.type),e.skip(1);const i=is(e),a=i>>5,s=31&i,n=is(e),o=n>>7,c=n>>6&1,d=n>>4&1,l=n>>3&1,h=n>>2&1,u=3&n,m=2===a&&c?n>>5&1?12:10:c?10:8;r.info.av1CodecInfo={profile:a,level:s,tier:o,bitDepth:m,monochrome:d,chromaSubsamplingX:l,chromaSubsamplingY:h,chromaSamplePosition:u}}break;case"colr":{const r=this.currentTrack;if(!r)break;t("video"===r.info?.type);if("nclx"!==ks(e,4))break;const i=ss(e),a=ss(e),s=ss(e),n=Boolean(128&is(e));r.info.colorSpace={primaries:f[i],transfer:w[a],matrix:b[s],fullRange:n}}break;case"esds":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(4);t(3===is(e)),Ir(e),e.skip(2);const i=is(e),a=!!(64&i),s=!!(32&i);if(!!(128&i)&&e.skip(2),a){const t=is(e);e.skip(t)}s&&e.skip(2);t(4===is(e));const n=Ir(e),o=e.filePos,c=is(e);if(64===c||103===c?(r.info.codec="aac",r.info.aacCodecInfo={isMpeg2:103===c}):105===c||107===c?r.info.codec="mp3":221===c?r.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${c}) - discarding track.`),e.skip(12),n>e.filePos-o){t(5===is(e));const i=Ir(e);if(r.info.codecDescription=rs(e,i),"aac"===r.info.codec){const e=Fe(r.info.codecDescription);null!==e.numberOfChannels&&(r.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(r.info.sampleRate=e.sampleRate)}}}break;case"enda":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type);255&ss(e)&&("pcm-s16be"===r.info.codec?r.info.codec="pcm-s16":"pcm-s24be"===r.info.codec?r.info.codec="pcm-s24":"pcm-s32be"===r.info.codec?r.info.codec="pcm-s32":"pcm-f32be"===r.info.codec?r.info.codec="pcm-f32":"pcm-f64be"===r.info.codec&&(r.info.codec="pcm-f64"))}break;case"pcmC":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(4);const i=is(e),a=Boolean(1&i),s=is(e);"pcm-s16be"===r.info.codec?a?16===s?r.info.codec="pcm-s16":24===s?r.info.codec="pcm-s24":32===s?r.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${s}.`),r.info.codec=null):16===s?r.info.codec="pcm-s16be":24===s?r.info.codec="pcm-s24be":32===s?r.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${s}.`),r.info.codec=null):"pcm-f32be"===r.info.codec&&(a?32===s?r.info.codec="pcm-f32":64===s?r.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${s}.`),r.info.codec=null):32===s?r.info.codec="pcm-f32be":64===s?r.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${s}.`),r.info.codec=null));break}case"dOps":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(1);const i=is(e),a=ss(e),s=ds(e),n=os(e),o=is(e);let c;c=0!==o?rs(e,2+i):new Uint8Array(0);const d=new Uint8Array(19+c.byteLength),l=new DataView(d.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,i),l.setUint16(10,a,!0),l.setUint32(12,s,!0),l.setInt16(16,n,!0),l.setUint8(18,o),d.set(c,19),r.info.codecDescription=d,r.info.numberOfChannels=i}break;case"dfLa":{const r=this.currentTrack;if(!r)break;t("audio"===r.info?.type),e.skip(4);const i=127,a=128,s=e.filePos;for(;e.filePos<c;){const t=is(e),s=ns(e);if((t&i)===vt.STREAMINFO){e.skip(10);const t=ds(e),i=t>>>12,a=1+(t>>9&7);r.info.sampleRate=i,r.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(t&a)break}const n=e.filePos;e.filePos=s;const o=rs(e,n-s),d=new Uint8Array(4+o.byteLength);new DataView(d.buffer).setUint32(0,1716281667,!1),d.set(o,4),r.info.codecDescription=d}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ds(e);let i=0,a=0;for(let s=0;s<r;s++){const r=ds(e),s=ds(e);t.sampleTable.sampleTimingEntries.push({startIndex:i,startDecodeTimestamp:a,count:r,delta:s}),i+=r,a+=r*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ds(e);let i=0;for(let a=0;a<r;a++){const r=ds(e),a=hs(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:i,count:r,offset:a}),i+=r}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ds(e),i=ds(e);if(0===r)for(let r=0;r<i;r++){const r=ds(e);t.sampleTable.sampleSizes.push(r)}else t.sampleTable.sampleSizes.push(r)}break;case"stz2":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),e.skip(3);const r=is(e),i=ds(e),a=rs(e,Math.ceil(i*r/8)),n=new s(a);for(let e=0;e<i;e++){const e=n.readBits(r);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 r=ds(e);for(let i=0;i<r;i++){const r=ds(e)-1;t.sampleTable.keySampleIndices.push(r)}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 r=ds(e);for(let i=0;i<r;i++){const r=ds(e)-1,i=ds(e),a=ds(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:i,sampleDescriptionIndex:a})}let i=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=i,e<t.sampleTable.sampleToChunk.length-1){i+=(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 r=ds(e);for(let i=0;i<r;i++){const r=ds(e);t.sampleTable.chunkOffsets.push(r)}}break;case"co64":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const r=ds(e);for(let i=0;i<r;i++){const r=ms(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(o,n.contentSize));break;case"mehd":{const t=is(e);e.skip(3);const r=1===t?ms(e):ds(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);const t=ds(e),r=ds(e),i=ds(e),a=ds(e),s=ds(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:i,defaultSampleSize:a,defaultSampleFlags:s})}break;case"tfra":{const t=is(e);e.skip(3);const r=ds(e),i=this.tracks.find((e=>e.id===r));if(!i)break;const a=ds(e),s=(12&a)>>2,n=3&a,o=[is,ss,ns,ds],c=o[(48&a)>>4],d=o[s],l=o[n],h=ds(e);for(let r=0;r<h;r++){const r=1===t?ms(e):ds(e),a=1===t?ms(e):ds(e);c(e),d(e),l(e),i.fragmentLookupTable.push({timestamp:r,moofOffset:a})}i.fragmentLookupTable.sort(((e,t)=>e.timestamp-t.timestamp));for(let e=0;e<i.fragmentLookupTable.length-1;e++){const t=i.fragmentLookupTable[e],r=i.fragmentLookupTable[e+1];t.timestamp===r.timestamp&&(i.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:a,moofSize:n.totalSize,implicitBaseDataOffset:a,trackData:new Map},this.readContiguousBoxes(e.slice(o,n.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(t(this.currentFragment),this.readContiguousBoxes(e.slice(o,n.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){const{currentFragmentState:r}=this.currentTrack;t(r),null!==r.startTimestamp&&(Nr(e,r.startTimestamp),e.startTimestampIsFinal=!0)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"tfhd":{t(this.currentFragment),e.skip(1);const r=ns(e),i=Boolean(1&r),a=Boolean(2&r),s=Boolean(8&r),n=Boolean(16&r),o=Boolean(32&r),c=Boolean(65536&r),d=Boolean(131072&r),l=ds(e),h=this.tracks.find((e=>e.id===l));if(!h)break;const u=this.fragmentTrackDefaults.find((e=>e.trackId===l));this.currentTrack=h,h.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:u?.defaultSampleDescriptionIndex??null,defaultSampleDuration:u?.defaultSampleDuration??null,defaultSampleSize:u?.defaultSampleSize??null,defaultSampleFlags:u?.defaultSampleFlags??null,startTimestamp:null},i?h.currentFragmentState.baseDataOffset=ms(e):d&&(h.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),a&&(h.currentFragmentState.sampleDescriptionIndex=ds(e)),s&&(h.currentFragmentState.defaultSampleDuration=ds(e)),n&&(h.currentFragmentState.defaultSampleSize=ds(e)),o&&(h.currentFragmentState.defaultSampleFlags=ds(e)),c&&(h.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const r=this.currentTrack;if(!r)break;t(r.currentFragmentState);const i=is(e);e.skip(3);const a=0===i?ds(e):ms(e);r.currentFragmentState.startTimestamp=a}break;case"trun":{const r=this.currentTrack;if(!r)break;if(t(this.currentFragment),t(r.currentFragmentState),this.currentFragment.trackData.has(r.id)){console.warn("Can't have two trun boxes for the same track in one fragment. Ignoring...");break}const a=is(e),s=ns(e),n=Boolean(1&s),o=Boolean(4&s),c=Boolean(256&s),d=Boolean(512&s),l=Boolean(1024&s),h=Boolean(2048&s),u=ds(e);let m=r.currentFragmentState.baseDataOffset;n&&(m+=hs(e));let p=null;o&&(p=ds(e));let f=m;if(0===u){this.currentFragment.implicitBaseDataOffset=f;break}let g=0;const w={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1};this.currentFragment.trackData.set(r.id,w);for(let i=0;i<u;i++){let s,n,o;c?s=ds(e):(t(null!==r.currentFragmentState.defaultSampleDuration),s=r.currentFragmentState.defaultSampleDuration),d?n=ds(e):(t(null!==r.currentFragmentState.defaultSampleSize),n=r.currentFragmentState.defaultSampleSize),l?o=ds(e):(t(null!==r.currentFragmentState.defaultSampleFlags),o=r.currentFragmentState.defaultSampleFlags),0===i&&null!==p&&(o=p);let u=0;h&&(u=0===a?ds(e):hs(e));const m=!(65536&o);w.samples.push({presentationTimestamp:g+u,duration:s,byteOffset:f,byteSize:n,isKeyFrame:m}),f+=n,g+=s}w.presentationTimestamps=w.samples.map(((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t}))).sort(((e,t)=>e.presentationTimestamp-t.presentationTimestamp));for(let e=0;e<w.presentationTimestamps.length;e++){const t=w.presentationTimestamps[e],r=w.samples[t.sampleIndex];if(null===w.firstKeyFrameTimestamp&&r.isKeyFrame&&(w.firstKeyFrameTimestamp=r.presentationTimestamp),e<w.presentationTimestamps.length-1){const i=w.presentationTimestamps[e+1];r.duration=i.presentationTimestamp-t.presentationTimestamp}}const k=w.samples[w.presentationTimestamps[0].sampleIndex],b=w.samples[i(w.presentationTimestamps).sampleIndex];w.startTimestamp=k.presentationTimestamp,w.endTimestamp=b.presentationTimestamp+b.duration,this.currentFragment.implicitBaseDataOffset=f}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(const{boxInfo:e,slice:r}of t){if("meta"!==e.name&&!this.currentTrack){const t=r.filePos;this.metadataTags.raw??={},"©"===e.name[0]?this.metadataTags.raw[e.name]??=Er(r):this.metadataTags.raw[e.name]??=rs(r,e.contentSize),r.filePos=t}switch(e.name){case"meta":r.skip(-e.headerSize),this.traverseBox(r);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=l.decode(rs(r,e.contentSize)):this.metadataTags.title??=Er(r);break;case"©des":this.currentTrack||(this.metadataTags.description??=Er(r));break;case"©ART":this.currentTrack||(this.metadataTags.artist??=Er(r));break;case"©alb":this.currentTrack||(this.metadataTags.album??=Er(r));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=Er(r));break;case"©gen":this.currentTrack||(this.metadataTags.genre??=Er(r));break;case"©day":if(!this.currentTrack){const e=new Date(Er(r));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"©cmt":this.currentTrack||(this.metadataTags.comment??=Er(r));break;case"©lyr":this.currentTrack||(this.metadataTags.lyrics??=Er(r))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==ds(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(o,n.contentSize)):this.readContiguousBoxes(e.slice(o+4,n.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=ds(e);for(let r=0;r<t;r++){const t=ds(e);e.skip(4);const i=l.decode(rs(e,t-8));this.currentMetadataKeys.set(r+1,i)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(o,n.contentSize));for(const{boxInfo:e,slice:r}of t){let t=e.name;const i=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(i)&&(t=this.currentMetadataKeys.get(i));const a=Ar(r);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 ce?(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),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=d(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),r>0&&(this.metadataTags.tracksTotal??=r)}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=d(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),r>0&&(this.metadataTags.discsTotal??=r)}}}}}return e.filePos=c,!0}}class Fr{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}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}getDisposition(){return this.internalTrack.disposition}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}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 O(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=zr(i,r),s=await this.fetchPacketForSampleIndex(a,t);return Lr(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,(e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=P(t.presentationTimestamps,r,(e=>e.presentationTimestamp));return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}}),r,r,t):s}async getNextPacket(e,t){const r=this.packetToSampleIndex.get(e);if(void 0!==r)return this.fetchPacketForSampleIndex(r+1,t);const i=this.packetToFragmentLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,(e=>{if(e===i.fragment){const t=e.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<t.samples.length)return{sampleIndex:i.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 r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Rr(i,r),s=await this.fetchPacketForSampleIndex(a,t);return Lr(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,(e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const i=A(t.presentationTimestamps,(e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r));return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}}),r,r,t):s}async getNextKeyPacket(e,r){const i=this.packetToSampleIndex.get(e);if(void 0!==i){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),t=Ur(e,i);return this.fetchPacketForSampleIndex(t,r)}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 r=e.trackData.get(this.internalTrack.id);if(r&&null!==r.firstKeyFrameTimestamp){const e=r.samples.findIndex((e=>e.isKeyFrame));return t(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}}),-1/0,1/0,r)}async fetchPacketForSampleIndex(e,r){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Or(i,e);if(!a)return null;let s;if(r.metadataOnly)s=Ot;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);e instanceof Promise&&(e=await e),t(e),s=rs(e,a.sampleSize)}const n=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new Ut(s,a.isKeyFrame?"key":"delta",n,o,e,a.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,r,i){if(-1===r)return null;const a=e.trackData.get(this.internalTrack.id).samples[r];let s;if(t(a),i.metadataOnly)s=Ot;else{let e=this.internalTrack.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);e instanceof Promise&&(e=await e),t(e),s=rs(e,a.byteSize)}const n=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=a.duration/this.internalTrack.timescale,c=new Ut(s,a.isKeyFrame?"key":"delta",n,o,e.moofOffset+r,a.byteSize);return this.packetToFragmentLocation.set(c,{fragment:e,sampleIndex:r}),c}async performFragmentedLookup(e,r,i,a,s){const n=this.internalTrack.demuxer;let o=null,c=null,d=-1;if(e){const{sampleIndex:t,correctSampleFound:i}=r(e);if(i)return this.fetchPacketInFragment(e,t,s);-1!==t&&(c=e,d=t)}const l=P(this.internalTrack.fragmentLookupTable,i,(e=>e.timestamp)),h=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,u=P(this.internalTrack.fragmentPositionCache,i,(e=>e.startTimestamp)),m=-1!==u?this.internalTrack.fragmentPositionCache[u]:null,p=Math.max(h?.moofOffset??0,m?.moofOffset??0)||null;let f;for(e?null===p||e.moofOffset>=p?(f=e.moofOffset+e.moofSize,o=e):f=p:f=p??0;;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=n.reader.requestSliceRange(f,8,Cr);if(e instanceof Promise&&(e=await e),!e)break;const t=f,i=xr(e);if(!i)break;if("moof"===i.name){o=await n.readFragment(t);const{sampleIndex:e,correctSampleFound:i}=r(o);if(i)return this.fetchPacketInFragment(o,e,s);-1!==e&&(c=o,d=e)}f=t+i.totalSize}if(h&&(!c||c.moofOffset<h.moofOffset)){const e=this.internalTrack.fragmentLookupTable[l-1];t(!e||e.timestamp<h.timestamp);const i=e?.timestamp??-1/0;return this.performFragmentedLookup(null,r,i,a,s)}return c?this.fetchPacketInFragment(c,d,s):null}}class Mr extends Fr{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}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&&kt(e.data)}}else{const e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&gt(e.data)}return{codec:_e(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class Dr extends Fr{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Ee(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}const zr=(e,t)=>{if(e.presentationTimestamps){const r=P(e.presentationTimestamps,t,(e=>e.presentationTimestamp));return-1===r?-1:e.presentationTimestamps[r].sampleIndex}{const r=P(e.sampleTimingEntries,t,(e=>e.startDecodeTimestamp));if(-1===r)return-1;const i=e.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((t-i.startDecodeTimestamp)/i.delta),i.count-1)}},Rr=(e,t)=>{if(!e.keySampleIndices)return zr(e,t);if(e.presentationTimestamps){const r=P(e.presentationTimestamps,t,(e=>e.presentationTimestamp));if(-1===r)return-1;for(let t=r;t>=0;t--){const r=e.presentationTimestamps[t].sampleIndex;if(-1!==x(e.keySampleIndices,r,(e=>e)))return r}return-1}{const r=zr(e,t),i=P(e.keySampleIndices,r,(e=>e));return e.keySampleIndices[i]??-1}},Or=(e,r)=>{const i=P(e.sampleTimingEntries,r,(e=>e.startIndex)),a=e.sampleTimingEntries[i];if(!a||a.startIndex+a.count<=r)return null;let s=a.startDecodeTimestamp+(r-a.startIndex)*a.delta;const n=P(e.sampleCompositionTimeOffsets,r,(e=>e.startIndex)),o=e.sampleCompositionTimeOffsets[n];o&&r-o.startIndex<o.count&&(s+=o.offset);const c=e.sampleSizes[Math.min(r,e.sampleSizes.length-1)],d=P(e.sampleToChunk,r,(e=>e.startSampleIndex)),l=e.sampleToChunk[d];t(l);const h=l.startChunkIndex+Math.floor((r-l.startSampleIndex)/l.samplesPerChunk),u=e.chunkOffsets[h],m=l.startSampleIndex+(h-l.startChunkIndex)*l.samplesPerChunk;let p=0,f=u;if(1===e.sampleSizes.length)f+=c*(r-m),p+=c*l.samplesPerChunk;else for(let t=m;t<m+l.samplesPerChunk;t++){const i=e.sampleSizes[t];t<r&&(f+=i),p+=i}let g=a.delta;if(e.presentationTimestamps){const i=e.presentationTimestampIndexMap[r];if(t(void 0!==i),i<e.presentationTimestamps.length-1){g=e.presentationTimestamps[i+1].presentationTimestamp-s}}return{presentationTimestamp:s,duration:g,sampleOffset:f,sampleSize:c,chunkOffset:u,chunkSize:p,isKeyFrame:!e.keySampleIndices||-1!==x(e.keySampleIndices,r,(e=>e))}},Ur=(e,t)=>{if(!e.keySampleIndices)return t+1;const r=P(e.keySampleIndices,t,(e=>e));return e.keySampleIndices[r+1]??-1},Nr=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const r of e.samples)r.presentationTimestamp+=t;for(const r of e.presentationTimestamps)r.presentationTimestamp+=t},Vr=e=>{const[t,,,r]=e,i=Math.hypot(t,r),a=t/i,s=r/i,n=-Math.atan2(s,a)*(180/Math.PI);return Number.isFinite(n)?n:0},Lr=e=>0===e.sampleSizes.length;
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class Wr{constructor(e){this.value=e}}class Hr{constructor(e){this.value=e}}class qr{constructor(e){this.value=e}}class jr{constructor(e){this.value=e}}var $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.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"}($r||($r={}));const Qr=[$r.EBML,$r.Segment],Kr=[$r.SeekHead,$r.Info,$r.Cluster,$r.Tracks,$r.Cues,$r.Attachments,$r.Chapters,$r.Tags],Gr=[...Qr,...Kr],Xr=e=>e<256?1:e<65536?2:e<1<<24?3:e<2**32?4:e<2**40?5:6,Yr=e=>e<256n?1:e<65536n?2:e<1n<<24n?3:e<1n<<32n?4:e<1n<<40n?5:e<1n<<48n?6:e<1n<<56n?7:8,Jr=e=>e>=-64&&e<64?1:e>=-8192&&e<8192?2:e>=-1048576&&e<1<<20?3:e>=-(1<<27)&&e<1<<27?4:e>=-(2**34)&&e<2**34?5:6;class Zr{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=Xr(e)){let r=0;switch(t){case 6:this.helperView.setUint8(r++,e/2**40|0);case 5:this.helperView.setUint8(r++,e/2**32|0);case 4:this.helperView.setUint8(r++,e>>24);case 3:this.helperView.setUint8(r++,e>>16);case 2:this.helperView.setUint8(r++,e>>8);case 1:this.helperView.setUint8(r++,e);break;default:throw new Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,r))}writeUnsignedBigInt(e,t=Yr(e)){let r=0;for(let i=t-1;i>=0;i--)this.helperView.setUint8(r++,Number(e>>BigInt(8*i)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=Jr(e)){e<0&&(e+=2**(8*t)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=(e=>{if(e<127)return 1;if(e<16383)return 2;if(e<2097151)return 3;if(e<268435455)return 4;if(e<2**35-1)return 5;if(e<2**42-1)return 6;throw new Error("EBML varint size not supported "+e)})(e)){let r=0;switch(t){case 1:this.helperView.setUint8(r++,128|e);break;case 2:this.helperView.setUint8(r++,64|e>>8),this.helperView.setUint8(r++,e);break;case 3:this.helperView.setUint8(r++,32|e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 4:this.helperView.setUint8(r++,16|e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 5:this.helperView.setUint8(r++,8|e/2**32&7),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;case 6:this.helperView.setUint8(r++,4|e/2**40&3),this.helperView.setUint8(r++,e/2**32|0),this.helperView.setUint8(r++,e>>24),this.helperView.setUint8(r++,e>>16),this.helperView.setUint8(r++,e>>8),this.helperView.setUint8(r++,e);break;default:throw new Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,r))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map((e=>e.charCodeAt(0)))))}writeEBML(e){if(null!==e)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),r=-1===e.size?1:e.size??4;-1===e.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);const i=this.writer.getPos();if(this.dataOffsets.set(e,i),this.writeEBML(e.data),-1!==e.size){const e=this.writer.getPos()-i,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,r),this.writer.seek(a)}}else if("number"==typeof e.data){const t=e.size??Xr(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if("bigint"==typeof e.data){const t=e.size??Yr(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if("string"==typeof e.data)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof Wr)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof Hr)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof qr){const t=e.size??Jr(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof jr){const t=h.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else B(e.data)}}const ei=16,ti=e=>{const t=is(e);if(e.skip(-1),0===t)return null;let r=1,i=128;for(;!(t&i);)r++,i>>=1;return r},ri=e=>{const t=is(e);if(0===t)return null;let r=1,i=128;for(;!(t&i);)r++,i>>=1;let a=t&i-1;for(let t=1;t<r;t++)a*=256,a+=is(e);return a},ii=(e,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let r=0;for(let i=0;i<t;i++)r*=256,r+=is(e);return r},ai=e=>{const t=ti(e);if(null===t)return null;return ii(e,t)},si=e=>{let t=is(e);return 255===t?t=null:(e.skip(-1),t=ri(e),72057594037927940===t&&(t=null)),t},ni=e=>{const t=ai(e);if(null===t)return null;return{id:t,size:si(e)}},oi=(e,t)=>{const r=rs(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return String.fromCharCode(...r.subarray(0,i))},ci=(e,t)=>{const r=rs(e,t);let i=0;for(;i<t&&0!==r[i];)i+=1;return l.decode(r.subarray(0,i))},di=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?gs(e):ws(e)},li=async(e,t,r,i)=>{const a=new Set(r);let s=t;for(;null===i||s<i;){let t=e.requestSliceRange(s,2,ei);if(t instanceof Promise&&(t=await t),!t)break;const r=ni(t);if(!r)break;if(a.has(r.id))return{pos:s,found:!0};mi(r.size),s=t.filePos+r.size}return{pos:null!==i&&i>s?i:s,found:!1}},hi=async(e,t,r,i)=>{const a=new Set(r);let s=t;for(;s<i;){let t=e.requestSliceRange(s,0,Math.min(65536,i-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=ai(t);if(null!==e&&a.has(e))return s;s++}}return null},ui={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function mi(e){if(null===e)throw new Error("Undefined element size is used in a place where it is not supported.")}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const pi=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");if(e.codecStrings.length>0){t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`}return t};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */var fi,gi,wi;!function(e){e[e.None=0]="None",e[e.Xiph=1]="Xiph",e[e.FixedSize=2]="FixedSize",e[e.Ebml=3]="Ebml"}(fi||(fi={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(gi||(gi={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(wi||(wi={}));const ki=[{id:$r.SeekHead,flag:"seekHeadSeen"},{id:$r.Info,flag:"infoSeen"},{id:$r.Tracks,flag:"tracksSeen"},{id:$r.Cues,flag:"cuesSeen"}],bi=10485760;class yi extends Pt{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map((e=>e.computeDuration())));return Math.max(0,...t)}async getTracks(){return await this.readMetadata(),this.segments.flatMap((e=>e.tracks.map((e=>e.inputTrack))))}async getMimeType(){await this.readMetadata();const e=await this.getTracks(),t=await Promise.all(e.map((e=>e.getCodecParameterString())));return pi({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 e of this.segments)e.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(e),e.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,ei);if(t instanceof Promise&&(t=await t),!t)break;const r=ni(t);if(!r)break;const a=r.id;let s=r.size;const n=t.filePos;if(a===$r.EBML){mi(s);let e=this.reader.requestSlice(n,s);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(a===$r.Segment){if(await this.readSegment(n,s),null===s)break;if(null===this.reader.fileSize)break}else if(a===$r.Cluster){if(null===this.reader.fileSize)break;if(null===s){s=(await li(this.reader,n,Gr,this.reader.fileSize)).pos-n}const e=i(this.segments);e&&(e.elementEndPos=n+s)}mi(s),e=n+s}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:null===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||r<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(r,2,ei);if(e instanceof Promise&&(e=await e),!e)break;const t=r,i=ni(e);if(!i||!Kr.includes(i.id)&&i.id!==$r.Void){const e=await hi(this.reader,t,Kr,Math.min(this.currentSegment.elementEndPos??1/0,t+bi));if(e){r=e;continue}break}const{id:a,size:s}=i,n=e.filePos,o=ki.findIndex((e=>e.id===a));if(-1!==o){const e=ki[o].flag;this.currentSegment[e]=!0,mi(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===$r.Tags||a===$r.Attachments){a===$r.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,mi(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===$r.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(null===s)break;r=n+s}if(this.currentSegment.seekEntries.sort(((e,t)=>e.segmentPosition-t.segmentPosition)),null!==this.reader.fileSize)for(const t of this.currentSegment.seekEntries){const r=ki.find((e=>e.id===t.id));if(!r)continue;if(this.currentSegment[r.flag])continue;let i=this.reader.requestSliceRange(e+t.segmentPosition,2,ei);if(i instanceof Promise&&(i=await i),!i)continue;const a=ni(i);if(!a)continue;const{id:s,size:n}=a;if(s!==r.id)continue;mi(n),this.currentSegment[r.flag]=!0;let o=this.reader.requestSlice(i.filePos,n);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3),this.currentSegment.tracks.sort(((e,t)=>Number(t.disposition.default)-Number(e.disposition.default)));const i=new Map(this.currentSegment.tracks.map((e=>[e.id,e])));for(const e of this.currentSegment.cuePoints){const t=i.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort(((e,t)=>e.time-t.time));for(let t=0;t<e.cuePoints.length-1;t++){const r=e.cuePoints[t],i=e.cuePoints[t+1];r.time===i.time&&(e.cuePoints.splice(t+1,1),t--)}}let a=null,s=-1/0;for(const e of this.currentSegment.tracks)e.cuePoints.length>s&&(s=e.cuePoints.length,a=e);for(const e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,r){if(r.lastReadCluster?.elementStartPos===e)return r.lastReadCluster;let a=this.reader.requestSliceRange(e,2,ei);a instanceof Promise&&(a=await a),t(a);const s=e,n=ni(a);t(n);t(n.id===$r.Cluster);let o=n.size;const c=a.filePos;if(null===o){o=(await li(this.reader,c,Gr,r.elementEndPos)).pos-c}let d=this.reader.requestSlice(c,o);d instanceof Promise&&(d=await d);const l={segment:r,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=l,d){const e=this.readContiguousElements(d,Gr);l.elementEndPos=e}for(const[,e]of l.trackData){const r=e.track;t(e.blocks.length>0);let a=!1;for(let t=0;t<e.blocks.length;t++){const r=e.blocks[t];r.timestamp+=l.timestamp,a||=r.lacing!==fi.None}e.presentationTimestamps=e.blocks.map(((e,t)=>({timestamp:e.timestamp,blockIndex:t}))).sort(((e,t)=>e.timestamp-t.timestamp));for(let t=0;t<e.presentationTimestamps.length;t++){const i=e.presentationTimestamps[t],a=e.blocks[i.blockIndex];if(null===e.firstKeyFrameTimestamp&&a.isKeyFrame&&(e.firstKeyFrameTimestamp=a.timestamp),t<e.presentationTimestamps.length-1){const r=e.presentationTimestamps[t+1];a.duration=r.timestamp-a.timestamp}else 0===a.duration&&null!=r.defaultDuration&&a.lacing===fi.None&&(a.duration=r.defaultDuration)}a&&(this.expandLacedBlocks(e.blocks,r),e.presentationTimestamps=e.blocks.map(((e,t)=>({timestamp:e.timestamp,blockIndex:t}))).sort(((e,t)=>e.timestamp-t.timestamp)));const n=e.blocks[e.presentationTimestamps[0].blockIndex],o=e.blocks[i(e.presentationTimestamps).blockIndex];e.startTimestamp=n.timestamp,e.endTimestamp=o.timestamp+o.duration;const c=P(r.clusterPositionCache,e.startTimestamp,(e=>e.startTimestamp));-1!==c&&r.clusterPositionCache[c].elementStartPos===s||r.clusterPositionCache.splice(c+1,0,{elementStartPos:l.elementStartPos,startTimestamp:e.startTimestamp})}return r.lastReadCluster=l,l}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){const i=e.segment.tracks.find((e=>e.id===t));if(!i)return null;r={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,r){for(let i=0;i<e.length;i++){const a=e[i];if(a.lacing===fi.None)continue;a.decoded||(a.data=this.decodeBlockData(r,a.data),a.decoded=!0);const s=es.tempFromBytes(a.data),n=[],o=is(s)+1;switch(a.lacing){case fi.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;s.bufferPos<s.length;){const r=is(s);if(t+=r,r<255){n.push(t),e+=t;break}}}n.push(s.length-(s.bufferPos+e))}break;case fi.FixedSize:{const e=s.length-1,t=Math.floor(e/o);for(let e=0;e<o;e++)n.push(t)}break;case fi.Ebml:{const e=ri(s);t(null!==e);let r=e;n.push(r);let i=r;for(let e=1;e<o-1;e++){const e=s.bufferPos,a=ri(s);t(null!==a);r+=a-((1<<7*(s.bufferPos-e)-1)-1),n.push(r),i+=r}n.push(s.length-(s.bufferPos+i))}break;default:t(!1)}t(n.length===o),e.splice(i,1);const c=a.duration||o*(r.defaultDuration??0);for(let t=0;t<o;t++){const r=n[t],d=rs(s,r),l=a.timestamp+c*t/o,h=c/o;e.splice(i+t,0,{timestamp:l,duration:h,isKeyFrame:a.isKeyFrame,data:d,lacing:fi.None,decoded:!0,mainAdditional:a.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(const r of e.seekEntries){if(r.id!==$r.Tags||e.tagsSeen){if(r.id!==$r.Attachments||e.attachmentsSeen)continue}else;let i=this.reader.requestSliceRange(e.dataStartPos+r.segmentPosition,2,ei);if(i instanceof Promise&&(i=await i),!i)continue;const a=ni(i);if(!a||a.id!==r.id)continue;const{size:s}=a;mi(s),t(!this.currentSegment),this.currentSegment=e;let n=this.reader.requestSlice(i.filePos,s);n instanceof Promise&&(n=await n),n&&this.readContiguousElements(n),this.currentSegment=null,r.id===$r.Tags?e.tagsSeen=!0:r.id===$r.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){const r=e.filePos;for(;e.filePos-r<=e.length-2;){const r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}traverseElement(e,i){const a=ni(e);if(!a)return!1;if(i&&i.includes(a.id))return!1;const{id:s,size:n}=a,o=e.filePos;switch(mi(n),s){case $r.DocType:this.isWebM="webm"===oi(e,n);break;case $r.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 $r.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=ii(e,n)}break;case $r.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=ii(e,n)}break;case $r.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=ii(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case $r.Duration:if(!this.currentSegment)break;this.currentSegment.duration=di(e,n);break;case $r.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ue},inputTrack:null,codecId:null,codecPrivate:null,defaultDuration:null,name:null,languageCode:R,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,n)),this.currentTrack.decodingInstructions.some((e=>"decompress"!==e.data?.type||e.scope!==gi.Block||e.data.algorithm!==wi.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){this.currentTrack.codecId===ui.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ui.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ui.vp8?this.currentTrack.info.codec="vp8":t===ui.vp9?this.currentTrack.info.codec="vp9":t===ui.av1&&(this.currentTrack.info.codec="av1");const e=this.currentTrack,r=new Tr(this.input,new Si(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type&&-1!==this.currentTrack.info.numberOfChannels&&-1!==this.currentTrack.info.sampleRate){t===ui.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2")},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===ui.mp3?this.currentTrack.info.codec="mp3":t===ui.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Me):t===ui.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ui.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack,r=new Sr(this.input,new vi(e));this.currentTrack.inputTrack=r,this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case $r.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=ii(e,n);break;case $r.TrackType:{if(!this.currentTrack)break;const t=ii(e,n);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:-1,sampleRate:-1,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case $r.FlagEnabled:if(!this.currentTrack)break;ii(e,n)||(this.currentSegment.tracks.pop(),this.currentTrack=null);break;case $r.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!ii(e,n);break;case $r.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!ii(e,n);break;case $r.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!ii(e,n);break;case $r.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!ii(e,n);break;case $r.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!ii(e,n);break;case $r.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!ii(e,n);break;case $r.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=oi(e,n);break;case $r.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=rs(e,n);break;case $r.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDuration=this.currentTrack.segment.timestampFactor*ii(e,n)/1e9;break;case $r.Name:if(!this.currentTrack)break;this.currentTrack.name=ci(e,n);break;case $r.Language:if(!this.currentTrack)break;if(this.currentTrack.languageCode!==R)break;this.currentTrack.languageCode=oi(e,n),V(this.currentTrack.languageCode)||(this.currentTrack.languageCode=R);break;case $r.LanguageBCP47:{if(!this.currentTrack)break;const t=oi(e,n).split("-")[0];this.currentTrack.languageCode=t||R}break;case $r.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case $r.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=ii(e,n);break;case $r.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=ii(e,n);break;case $r.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===ii(e,n);break;case $r.Colour:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,n));break;case $r.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=ii(e,n),r=b[t]??null;this.currentTrack.info.colorSpace.matrix=r}break;case $r.Range:if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===ii(e,n);break;case $r.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=ii(e,n),r=w[t]??null;this.currentTrack.info.colorSpace.transfer=r}break;case $r.Primaries:{if("video"!==this.currentTrack?.info?.type||!this.currentTrack.info.colorSpace)break;const t=ii(e,n),r=f[t]??null;this.currentTrack.info.colorSpace.primaries=r}break;case $r.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case $r.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-di(e,n);try{this.currentTrack.info.rotation=r(t)}catch{}}break;case $r.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(o,n));break;case $r.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=di(e,n);break;case $r.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=ii(e,n);break;case $r.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=ii(e,n);break;case $r.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case $r.CueTime:this.currentCueTime=ii(e,n);break;case $r.CueTrackPositions:{if(null===this.currentCueTime)break;t(this.currentSegment);const r={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(r),this.readContiguousElements(e.slice(o,n)),-1!==r.trackId&&-1!==r.clusterPosition||this.currentSegment.cuePoints.pop()}break;case $r.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=ii(e,n)}break;case $r.CueClusterPosition:{const r=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!r)break;t(this.currentSegment),r.clusterPosition=this.currentSegment.dataStartPos+ii(e,n)}break;case $r.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=ii(e,n);break;case $r.SimpleBlock:{if(!this.currentCluster)break;const t=ri(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=os(e),a=is(e),s=a>>1&3;let c=!!(128&a);"audio"===r.track.info?.type&&r.track.info.codec&&(c=!0);const d=rs(e,n-(e.filePos-o)),l=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:i,duration:0,isKeyFrame:c,data:d,lacing:s,decoded:!l,mainAdditional:null})}break;case $r.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case $r.Block:{if(!this.currentCluster)break;const t=ri(e);if(null===t)break;const r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;const i=os(e),a=is(e)>>1&3,s=rs(e,n-(e.filePos-o)),c=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:i,duration:0,isKeyFrame:!0,data:s,lacing:a,decoded:!c,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case $r.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case $r.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 $r.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=rs(e,n);break;case $r.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=ii(e,n);break;case $r.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=ii(e,n);break;case $r.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case $r.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case $r.Targets:this.readContiguousElements(e.slice(o,n));break;case $r.TargetTypeValue:50!==ii(e,n)&&(this.currentTagTargetIsMovie=!1);break;case $r.TagTrackUID:case $r.TagEditionUID:case $r.TagChapterUID:case $r.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case $r.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case $r.TagName:this.currentSimpleTagName=ci(e,n);break;case $r.TagString:{if(!this.currentSimpleTagName)break;const t=ci(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case $r.TagBinary:{if(!this.currentSimpleTagName)break;const t=rs(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case $r.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 de(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 r="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?r="coverFront":t.startsWith("back.")&&(r="coverBack")}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:r,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case $r.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let r=0n;for(let i=0;i<t;i++)r<<=8n,r+=BigInt(is(e));return r})(e,n);break;case $r.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ci(e,n);break;case $r.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=oi(e,n);break;case $r.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=rs(e,n);break;case $r.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ci(e,n);break;case $r.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,n)),this.currentTrack.decodingInstructions.sort(((e,t)=>t.order-e.order));break;case $r.ContentEncoding:this.currentDecodingInstruction={order:0,scope:gi.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case $r.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=ii(e,n);break;case $r.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=ii(e,n);break;case $r.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:wi.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case $r.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=ii(e,n);break;case $r.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=rs(e,n);break;case $r.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,r){t(e.decodingInstructions.length>0);let i=r;for(const r of e.decodingInstructions)if(t(r.data),"decompress"===r.data.type)if(r.data.algorithm===wi.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??=e)}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}}}}class Ti{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}async getFirstTimestamp(){const e=await this.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}getTimeResolution(){return this.internalTrack.segment.timestampFactor}getDisposition(){return this.internalTrack.disposition}async getFirstPacket(e){return this.performClusterLookup(null,(e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1}),-1/0,1/0,e)}intoTimescale(e){return O(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const r=this.intoTimescale(e);return this.performClusterLookup(null,(e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=P(t.presentationTimestamps,r,(e=>e.timestamp));return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}}),r,r,t)}async getNextPacket(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);if(r.blockIndex+1<t.blocks.length)return{blockIndex:r.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 r=this.intoTimescale(e);return this.performClusterLookup(null,(e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const i=A(t.presentationTimestamps,(e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=r));return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}}),r,r,t)}async getNextKeyPacket(e,r){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).blocks.findIndex(((e,t)=>e.isKeyFrame&&t>i.blockIndex));if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const r=e.trackData.get(this.internalTrack.id);if(r&&null!==r.firstKeyFrameTimestamp){const e=r.blocks.findIndex((e=>e.isKeyFrame));return t(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}}),-1/0,1/0,r)}async fetchPacketInCluster(e,r,i){if(-1===r)return null;const a=e.trackData.get(this.internalTrack.id).blocks[r];t(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0);const s=i.metadataOnly?Ot: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=i.metadataOnly?Ot:a.mainAdditional,c.alphaByteLength=a.mainAdditional.byteLength);const d=new Ut(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+r,a.data.byteLength,c);return this.packetToClusterLocation.set(d,{cluster:e,blockIndex:r}),d}async performClusterLookup(e,r,i,a,s){const{demuxer:n,segment:o}=this.internalTrack;let c=null,d=null,l=-1;if(e){const{blockIndex:t,correctBlockFound:i}=r(e);if(i)return this.fetchPacketInCluster(e,t,s);-1!==t&&(d=e,l=t)}const h=P(this.internalTrack.cuePoints,i,(e=>e.time)),u=-1!==h?this.internalTrack.cuePoints[h]:null,m=P(this.internalTrack.clusterPositionCache,i,(e=>e.startTimestamp)),p=-1!==m?this.internalTrack.clusterPositionCache[m]:null,f=Math.max(u?.clusterPosition??0,p?.elementStartPos??0)||null;let g;for(e?null===f||e.elementStartPos>=f?(g=e.elementEndPos,c=e):g=f:g=f??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,ei);if(e instanceof Promise&&(e=await e),!e)break;const i=g,h=ni(e);if(!h||!Kr.includes(h.id)&&h.id!==$r.Void){const e=await hi(n.reader,i,Kr,Math.min(o.elementEndPos??1/0,i+bi));if(e){g=e;continue}break}const u=h.id;let m=h.size;const p=e.filePos;if(u===$r.Cluster){c=await n.readCluster(i,o),m=c.elementEndPos-p;const{blockIndex:e,correctBlockFound:t}=r(c);if(t)return this.fetchPacketInCluster(c,e,s);-1!==e&&(d=c,l=e)}if(null===m){t(u!==$r.Cluster);m=(await li(n.reader,p,Gr,o.elementEndPos)).pos-p}const f=p+m;if(null===o.elementEndPos){let e=n.reader.requestSliceRange(f,2,ei);if(e instanceof Promise&&(e=await e),!e)break;if(ai(e)===$r.Segment){o.elementEndPos=f;break}}g=f}if(u&&(!d||d.elementStartPos<u.clusterPosition)){const e=this.internalTrack.cuePoints[h-1];t(!e||e.time<u.time);const i=e?.time??-1/0;return this.performClusterLookup(null,r,i,a,s)}return d?this.fetchPacketInCluster(d,l,s):null}}class Si extends Ti{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}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;return("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({})),{codec:_e({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?at(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?ct(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?gt(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?kt(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0}})():null}}class vi extends Ti{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:Ee({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}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const Ci=[44100,48e3,32e3],xi=[-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],Pi=1483304551,_i=1231971951,Ii=(e,t,r,i,a)=>0===t?0:1===t?Math.floor(144*r/(i<<e))+a:2===t?Math.floor(144*r/i)+a:4*(Math.floor(12*r/i)+a),Ei=(e,t)=>3===e?3===t?21:36:3===t?13:21,Ai=(e,t)=>{const r=e>>>24,i=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==r&&255!==i&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==r)return{header:null,bytesAdvanced:1};if(224&~i)return{header:null,bytesAdvanced:1};let n=0,o=0;16&i?n=8&i?0:1:(n=1,o=1);const c=i>>3&3,d=i>>1&3,l=(a>>2&3)%3,h=s>>6&3,u=s>>4&3,m=s>>3&1,p=s>>2&1,f=3&s,g=xi[16*n*4+16*d+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const w=1e3*g,k=Ci[l]>>n+o,b=Ii(n,d,w,k,a>>1&1);if(null!==t&&t<b)return{header:null,bytesAdvanced:1};let y;return y=3===c?3===d?384:1152:3===d?384:2===d?1152:576,{header:{totalSize:b,mpegVersionId:c,layer:d,bitrate:w,frequencyIndex:l,sampleRate:k,channel:h,modeExtension:u,copyright:m,original:p,emphasis:f,audioSamplesInFrame:y},bytesAdvanced:1}},Bi=e=>{let t=2130706432,r=0;for(;0!==t;)r>>=1,r|=e&t,t>>=8;return r};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
var Fi,Mi;!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}(Fi||(Fi={})),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"}(Mi||(Mi={}));const Di=128,zi=["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"],Ri=(e,t)=>{const r=rs(e,t),i=Z(r.indexOf(0),r.length),a=r.subarray(0,i);let s="";for(let e=0;e<a.length;e++)s+=String.fromCharCode(a[e]);return s.trimEnd()},Oi=e=>{const t=e.filePos,r=ks(e,3),i=is(e),a=is(e),s=is(e),n=ds(e);if("ID3"!==r||255===i||255===a||2155905152&n)return e.filePos=t,null;return{majorVersion:i,revision:a,flags:s,size:Bi(n)}},Ui=(e,t,r)=>{if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const i=rs(e,t.size),a=new Ni(t,i);if(t.flags&Fi.Footer&&a.removeFooter(),t.flags&Fi.Unsynchronisation&&3===t.majorVersion&&a.ununsynchronizeAll(),t.flags&Fi.ExtendedHeader){const e=a.readU32();3===t.majorVersion?a.pos+=e:a.pos+=e-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){const e=a.readId3V2Frame();if(!e)break;const i=a.pos,s=a.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&Fi.Unsynchronisation)),n)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),a.pos=s;else if(o)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),a.pos=s;else{switch(c&&a.ununsynchronizeRegion(a.pos,s),r.raw??={},"T"===e.id[0]?r.raw[e.id]??=a.readId3V2EncodingAndText(s):r.raw[e.id]??=a.readBytes(e.size),a.pos=i,e.id){case"TIT2":case"TT2":r.title??=a.readId3V2EncodingAndText(s);break;case"TIT3":case"TT3":r.description??=a.readId3V2EncodingAndText(s);break;case"TPE1":case"TP1":r.artist??=a.readId3V2EncodingAndText(s);break;case"TALB":case"TAL":r.album??=a.readId3V2EncodingAndText(s);break;case"TPE2":case"TP2":r.albumArtist??=a.readId3V2EncodingAndText(s);break;case"TRCK":case"TRK":{const e=a.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.tracksTotal??=i)}break;case"TPOS":case"TPA":{const e=a.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.discsTotal??=i)}break;case"TCON":case"TCO":{const e=a.readId3V2EncodingAndText(s);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==zi[e]){r.genre??=zi[e];break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==zi[e]){r.genre??=zi[e];break}}r.genre??=e}break;case"TDRC":case"TDAT":{const e=a.readId3V2EncodingAndText(s),t=new Date(e);Number.isNaN(t.getTime())||(r.date??=t)}break;case"TYER":case"TYE":{const e=a.readId3V2EncodingAndText(s),t=Number.parseInt(e,10);Number.isInteger(t)&&(r.date??=new Date(t,0,1))}break;case"USLT":case"ULT":{const e=a.readU8();a.pos+=3,a.readId3V2Text(e,s),r.lyrics??=a.readId3V2Text(e,s)}break;case"COMM":case"COM":{const e=a.readU8();a.pos+=3,a.readId3V2Text(e,s),r.comment??=a.readId3V2Text(e,s)}break;case"APIC":case"PIC":{const e=a.readId3V2TextEncoding();let i;if(2===t.majorVersion){const e=a.readAscii(3);i="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else i=a.readId3V2Text(e,s);const n=a.readU8(),o=a.readId3V2Text(e,s).trimEnd(),c=s-a.pos;if(c>=0){const e=a.readBytes(c);r.images||(r.images=[]),r.images.push({data:e,mimeType:i,kind:3===n?"coverFront":4===n?"coverBack":"unknown",description:o})}}break;default:a.pos+=e.size}a.pos=s}}};class Ni{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 r=this.bytes[t];if(e.push(r),255===r&&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 r=[];for(let i=e;i<t;i++){const e=this.bytes[i];if(r.push(e),255===e&&i!==t-1){0===this.bytes[i+1]&&i++}}const i=this.bytes.subarray(0,e),a=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+r.length+a.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(a,i.length+r.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+1);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 r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(2===this.header.majorVersion){const e=this.readAscii(3);if("\0\0\0"===e)return null;return{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 r=4===this.header.majorVersion?Bi(t):t;const i=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(r)){const e=4===this.header.majorVersion?t:Bi(t);s(e)&&(r=e)}return this.pos=a,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const r=this.pos,i=this.readBytes(t-this.pos);switch(e){case Mi.ISO_8859_1:{let e="";for(let t=0;t<i.length;t++){const a=i[t];if(0===a){this.pos=r+t+1;break}e+=String.fromCharCode(a)}return e}case Mi.UTF_16_WITH_BOM:if(255===i[0]&&254===i[1]){const e=new TextDecoder("utf-16le"),t=Z(i.findIndex(((e,t)=>0===e&&0===i[t+1]&&t%2==0)),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}if(254===i[0]&&255===i[1]){const e=new TextDecoder("utf-16be"),t=Z(i.findIndex(((e,t)=>0===e&&0===i[t+1]&&t%2==0)),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}{const e=Z(i.findIndex((e=>0===e)),i.length);return this.pos=r+Math.min(e+1,i.length),l.decode(i.subarray(0,e))}case Mi.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Z(i.findIndex(((e,t)=>0===e&&0===i[t+1]&&t%2==0)),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(0,t))}case Mi.UTF_8:{const e=Z(i.findIndex((e=>0===e)),i.length);return this.pos=r+Math.min(e+1,i.length),l.decode(i.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Vi{constructor(e){this.helper=new Uint8Array(8),this.helperView=d(this.helper),this.writer=e}writeId3V2Tag(e){const t=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);const r=this.writer.getPos(),i=new Set;for(const{key:t,value:r}of te(e))switch(t){case"title":this.writeId3V2TextFrame("TIT2",r),i.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",r),i.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",r),i.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",r),i.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",r),i.add("TPE2");break;case"trackNumber":{const t=void 0!==e.tracksTotal?`${r}/${e.tracksTotal}`:r.toString();this.writeId3V2TextFrame("TRCK",t),i.add("TRCK")}break;case"discNumber":{const t=void 0!==e.discsTotal?`${r}/${e.discsTotal}`:r.toString();this.writeId3V2TextFrame("TPOS",t),i.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",r),i.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",r.toISOString().slice(0,10)),i.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(r),i.add("USLT");break;case"comment":this.writeId3V2CommentFrame(r),i.add("COMM");break;case"images":{const e={coverFront:3,coverBack:4,unknown:0};for(const t of r){const r=e[t.kind]??0,i=t.description??"";this.writeId3V2ApicFrame(t.mimeType,r,i,t.data)}}break;case"tracksTotal":case"discsTotal":case"raw":break;default:B(t)}if(e.raw)for(const t in e.raw){const r=e.raw[t];if(null==r||4!==t.length||i.has(t))continue;let a;if("string"==typeof r){const e=h.encode(r);a=new Uint8Array(e.byteLength+2),a[0]=Mi.UTF_8,a.set(e,1)}else{if(!(r instanceof Uint8Array))continue;a=r}this.writeAscii(t),this.writeSynchsafeU32(a.byteLength),this.writeU16(0),this.writer.write(a)}const a=this.writer.getPos(),s=a-r;return this.writer.seek(t+6),this.writeSynchsafeU32(s),this.writer.seek(a),s+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32((e=>{let t=127,r=0,i=e;for(;2147483647^t;)r=i&~t,r<<=1,r|=i&t,t=(t+1<<8)-1,i=r;return r})(e))}writeIsoString(e){const t=new Uint8Array(e.length+1);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);t[e.length]=0,this.writer.write(t)}writeUtf8String(e){const t=h.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){const r=u(t),i=1+(r?t.length:h.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(i),this.writeU16(0),this.writeU8(r?Mi.ISO_8859_1:Mi.UTF_8),r?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){const t=u(e),r=5+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(r),this.writeU16(0),this.writeU8(t?Mi.ISO_8859_1:Mi.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(""),this.writeIsoString(e)):(this.writeUtf8String(""),this.writeUtf8String(e))}writeId3V2CommentFrame(e){const t=u(e),r=5+(t?e.length:h.encode(e).byteLength)+1;this.writeAscii("COMM"),this.writeSynchsafeU32(r),this.writeU16(0),this.writeU8(t?Mi.ISO_8859_1:Mi.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(""),this.writeIsoString(e)):(this.writeUtf8String(""),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,r,i){const a=u(e)&&u(r),s=a?r.length:h.encode(r).byteLength,n=1+e.length+1+1+s+1+i.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(a?Mi.ISO_8859_1:Mi.UTF_8),a?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),a?this.writeIsoString(r):this.writeUtf8String(r),this.writer.write(i)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const Li=async(e,t,r)=>{let i=t;for(;null===r||i<r;){let t=e.requestSlice(i,4);if(t instanceof Promise&&(t=await t),!t)break;const r=ds(t),a=Ai(r,null!==e.fileSize?e.fileSize-i:null);if(a.header)return{header:a.header,startPos:i};i+=a.bytesAdvanced}return null};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Wi extends Pt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.tracks=[],this.readingMutex=new S,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.tracks=[new Sr(this.input,new Hi(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=Oi(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Li(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 r=Ei(t.mpegVersionId,t.channel);let i=this.reader.requestSlice(e.startPos+r,4);if(i instanceof Promise&&(i=await i),i){const e=ds(i);if(e===Pi||e===_i)return}this.firstFrameHeader||(this.firstFrameHeader=t),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return t(e),e.computeDuration()}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,r=!1;for(;;){let t=this.reader.requestSlice(e,10);if(t instanceof Promise&&(t=await t),!t)break;const i=Oi(t);if(!i)break;r=!0;let a=this.reader.requestSlice(t.filePos,i.size);if(a instanceof Promise&&(a=await a),!a)break;Ui(a,i,this.metadataTags),e=t.filePos+i.size}if(!r&&null!==this.reader.fileSize&&this.reader.fileSize>=Di){let e=this.reader.requestSlice(this.reader.fileSize-Di,Di);e instanceof Promise&&(e=await e),t(e);"TAG"===ks(e,3)&&((e,t)=>{const r=e.filePos;t.raw??={},t.raw.TAG??=rs(e,125),e.filePos=r;const i=Ri(e,30);i&&(t.title??=i);const a=Ri(e,30);a&&(t.artist??=a);const s=Ri(e,30);s&&(t.album??=s);const n=Ri(e,4),o=Number.parseInt(n,10);Number.isInteger(o)&&o>0&&(t.date??=new Date(o,0,1));const c=rs(e,30);let d;if(0===c[28]&&0!==c[29]){const r=c[29];r>0&&(t.trackNumber??=r),e.skip(-30),d=Ri(e,28),e.skip(2)}else e.skip(-30),d=Ri(e,30);d&&(t.comment??=d);const l=is(e);l<zi.length&&(t.genre??=zi[l])})(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Hi{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return R}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...ue}}async getDecoderConfig(){return t(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 r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=Ot;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=rs(e,r.dataSize)}return new Ut(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=x(this.demuxer.loadedSamples,e.timestamp,(e=>e.timestamp));if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=P(this.demuxer.loadedSamples,e,(e=>e.timestamp));if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const qi=1399285583,ji=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=2147483648&t?t<<1^79764919:t<<1;ji[e]=t>>>0&4294967295}const $i=e=>{const t=d(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let i=0;for(let t=0;t<e.length;t++){const r=e[t];i=(i<<8^ji[i>>>24^r])>>>0}return t.setUint32(22,r,!0),i},Qi=(e,r,i)=>{let a=0,s=null;if(e.length>0)if("vorbis"===r.codec){t(r.vorbisInfo);const n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(r.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=r.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let c=i;const d=r.vorbisInfo.modeBlockflags[o];if(s=r.vorbisInfo.blocksizes[d],1===d){const t=1+(1|n),i=e[0]&t?1:0;c=r.vorbisInfo.blocksizes[i]}a=null!==c?c+s>>2:0}else if("opus"===r.codec){a=(e=>{const t=e[0]>>3;return{durationInSamples:yt[t]}})(e).durationInSamples}return{durationInSamples:a,vorbisBlockSize:s}},Ki=e=>{let t="audio/ogg";if(e.codecStrings){t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`}return t},Gi=27,Xi=282,Yi=e=>{const t=e.filePos;if(ls(e)!==qi)return null;e.skip(1);const r=is(e),i=fs(e),a=ls(e),s=ls(e),n=ls(e),o=is(e),c=new Uint8Array(o);for(let t=0;t<o;t++)c[t]=is(e);const d=27+o,l=c.reduce(((e,t)=>e+t),0);return{headerStartPos:t,totalSize:d+l,dataStartPos:t+d,dataSize:l,headerType:r,granulePosition:i,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},Ji=(e,t)=>{for(;e.filePos<t-3;){const t=ls(e),r=79;if((255&t)===r||(t>>>8&255)===r||(t>>>16&255)===r||(t>>>24&255)===r){if(e.skip(-4),t===qi)return!0;e.skip(1)}}return!1};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class Zi extends Pt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.tracks=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Gi,Xi);if(t instanceof Promise&&(t=await t),!t)break;const r=Yi(t);if(!r)break;if(!!!(2&r.headerType))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(const e of this.bitstreams){const t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&1===t.data[0]&&118===t.data[1]&&111===t.data[2]&&114===t.data[3]&&98===t.data[4]&&105===t.data[5]&&115===t.data[6]?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&79===t.data[0]&&112===t.data[1]&&117===t.data[2]&&115===t.data[3]&&72===t.data[4]&&101===t.data[5]&&97===t.data[6]&&100===t.data[7]&&await this.readOpusMetadata(t,e),null!==e.codecInfo.codec&&this.tracks.push(new Sr(this.input,new ea(e,this))))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;if(r=await this.findNextPacketStart(i),!r)return;const a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a)return;if(3!==i.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(i.data.length);const o=new Uint8Array(1+s.length+e.data.length+i.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(i.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+i.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:Tt(a.data).modeBlockflags},Ct(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const r=await this.findNextPacketStart(e);if(!r)return;const i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;const a=bt(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=Me,t.codecInfo.opusInfo={preSkip:a.preSkip},Ct(i.data.subarray(8),this.metadataTags)}async readPacket(e,r){t(r<e.lacingValues.length);let i=0;for(let t=0;t<r;t++)i+=e.lacingValues[t];let a=e,s=i,n=r;const o=[];e:for(;;){let r=this.reader.requestSlice(a.dataStartPos,a.dataSize);r instanceof Promise&&(r=await r),t(r);const c=rs(r,a.dataSize);for(;;){if(n===a.lacingValues.length){o.push(c.subarray(i,s));break}const e=a.lacingValues[n];if(s+=e,e<255){o.push(c.subarray(i,s));break e}n++}let d=a.headerStartPos+a.totalSize;for(;;){let t=this.reader.requestSliceRange(d,Gi,Xi);if(t instanceof Promise&&(t=await t),!t)return null;const r=Yi(t);if(!r)return null;if(a=r,a.serialNumber===e.serialNumber)break;d=a.headerStartPos+a.totalSize}i=0,s=0,n=0}const c=o.reduce(((e,t)=>e+t.length),0),d=new Uint8Array(c);let l=0;for(let e=0;e<o.length;e++){const t=o[e];d.set(t,l),l+=t.length}return{data:d,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 r=this.reader.requestSliceRange(t,Gi,Xi);if(r instanceof Promise&&(r=await r),!r)return null;const i=Yi(r);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};t=i.headerStartPos+i.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.tracks.map((e=>e.getCodecParameterString())));return Ki({codecStrings:e.filter(Boolean)})}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){const e=await this.getTracks(),t=await Promise.all(e.map((e=>e.computeDuration())));return Math.max(0,...t)}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class ea{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new S,this.internalSampleRate="opus"===e.codecInfo.codec?Me:e.sampleRate}getId(){return this.bitstream.serialNumber}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return t(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 R}getDisposition(){return{...ue}}async getFirstTimestamp(){return 0}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(t(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:i,vorbisBlockSize:a}=Qi(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Ut(r.metadataOnly?Ot:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),s}async getFirstPacket(e){t(this.bitstream.lastMetadataPacket);const r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(t(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const a=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const r=this.encodedPacketToMetadata.get(e);if(!r)throw new Error("Packet was not created from this track.");const i=await this.demuxer.findNextPacketStart(r.packet);if(!i)return null;const a=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,r){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,r);const i=O(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(r);if(i<0)return null;t(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,r=Math.floor((e+n)/2);let a=r;for(;;){const e=Math.min(a+65307,n-Gi);let c=this.demuxer.reader.requestSlice(a,e-a);c instanceof Promise&&(c=await c),t(c);if(!Ji(c,e)){n=r+Gi;continue e}let d=this.demuxer.reader.requestSliceRange(c.filePos,Gi,Xi);d instanceof Promise&&(d=await d),t(d);const l=Yi(d);t(l);let h=!1;if(l.serialNumber===this.bitstream.serialNumber)h=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);e instanceof Promise&&(e=await e),t(e);const r=rs(e,l.totalSize);h=$i(r)===l.checksum}if(!h){a=l.headerStartPos+4;continue}if(h&&l.serialNumber!==this.bitstream.serialNumber){a=l.headerStartPos+l.totalSize;continue}if(!(-1===l.granulePosition)){this.granulePositionToTimestampInSamples(l.granulePosition)>i?n=l.headerStartPos:(s=l,o.push(l));continue e}a=l.headerStartPos+l.totalSize}}let c=a.startPage;for(const e of o){if(e.granulePosition===s.granulePosition)break;(!c||e.headerStartPos>c.headerStartPos)&&(c=e)}let d=c;const l=[d];for(;d.serialNumber!==this.bitstream.serialNumber||d.granulePosition!==s.granulePosition;){const e=d.headerStartPos+d.totalSize;let r=this.demuxer.reader.requestSliceRange(e,Gi,Xi);r instanceof Promise&&(r=await r),t(r);const i=Yi(r);t(i),d=i,d.serialNumber===this.bitstream.serialNumber&&l.push(d)}t(-1!==d.granulePosition);let h,u,m=null,p=d,f=0;if(d.headerStartPos===a.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),u=!0,m=0;else{h=0,u=!1;for(let e=d.lacingValues.length-1;e>=0;e--){if(d.lacingValues[e]<255){m=e+1;break}}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");f=m-1;const e={data:Ot,endPage:p,endSegmentIndex:f};if(await this.demuxer.findNextPacketStart(e)){const e=ra(l,d,m);t(e);const r=ta(l,e.page,e.segmentIndex);r&&(d=r.page,m=r.segmentIndex)}else for(;;){const e=ra(l,d,m);if(!e)break;const t=ta(l,e.page,e.segmentIndex);if(!t)break;if(d=t.page,m=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,f=e.segmentIndex;break}}}let g=null,w=null;for(;null!==d;){t(null!==m);const e=await this.demuxer.readPacket(d,m);if(!e)break;if(!(d.headerStartPos===a.startPage.headerStartPos&&m<a.startSegmentIndex)){let a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:h,vorbisLastBlocksize:w?.vorbisBlockSize??null},r);t(a);let s=this.encodedPacketToMetadata.get(a);if(t(s),u||e.endPage.headerStartPos!==p.headerStartPos||e.endSegmentIndex!==f?h+=s.durationInSamples:(h=this.granulePositionToTimestampInSamples(d.granulePosition),u=!0,a=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:h-s.durationInSamples,vorbisLastBlocksize:w?.vorbisBlockSize??null},r),t(a),s=this.encodedPacketToMetadata.get(a),t(s)),g=a,w=s,u&&(Math.max(h,0)>i||Math.max(s.timestampInSamples,0)===i))break}const s=await this.demuxer.findNextPacketStart(e);if(!s)break;d=s.startPage,m=s.startSegmentIndex}return g}async getPacketSequential(e,r){const a=await this.sequentialScanMutex.acquire();try{const a=O(e*this.internalSampleRate);e=a/this.internalSampleRate;const s=P(this.sequentialScanCache,a,(e=>e.timestampInSamples));let n;if(-1!==s){const e=this.sequentialScanCache[s];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},r)}else n=await this.getFirstPacket(r);let o=0;for(;n&&n.timestamp<e;){const a=await this.getNextPacket(n,r);if(!a||a.timestamp>e)break;if(n=a,o++,100===o){o=0;const e=this.encodedPacketToMetadata.get(n);t(e),this.sequentialScanCache.length>0&&t(i(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{a()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ta=(e,r,i)=>{let a=r,s=i;e:for(;;){for(s--;s>=0;s--){if(a.lacingValues[s]<255){s++;break e}}t(-1===s);if(!(1&a.headerType)){s=0;break}const r=E(e,(e=>e.headerStartPos<a.headerStartPos));if(!r)return null;a=r,s=a.lacingValues.length}if(t(-1!==s),s===a.lacingValues.length){const r=e[e.indexOf(a)+1];t(r),a=r,s=0}return{page:a,segmentIndex:s}},ra=(e,t,r)=>{if(r>0)return{page:t,segmentIndex:r-1};const i=E(e,(e=>e.headerStartPos<t.headerStartPos));return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
var ia;!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"}(ia||(ia={}));class aa extends Pt{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.tracks=[],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),t(e);const r=ks(e,4),i="RIFX"!==r,a="RF64"===r,s=cs(e,i);let n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==ks(e,4))throw new Error("Invalid WAVE file - wrong format");let o=0,c=null,d=e.filePos;for(;null===n||d<n;){let e=this.reader.requestSlice(d,8);if(e instanceof Promise&&(e=await e),!e)break;const t=ks(e,4),r=cs(e,i),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,r,i);else if("data"===t){if(c??=r,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,r);if(e instanceof Promise&&(e=await e),!e)break;const t=us(e,i);c=us(e,i),n=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(s,r,i):"ID3 "!==t&&"id3 "!==t||await this.parseId3Chunk(s,r);d=s+r+(1&r),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 l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.tracks.push(new Sr(this.input,new na(this)))})()}async parseFmtChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let a=as(i,r);const s=as(i,r),n=cs(i,r);i.skip(4);const o=as(i,r);let c;if(c=14===t?8:as(i,r),t>=18&&357!==a){const e=as(i,r),s=t-18;if(Math.min(s,e)>=22&&a===ia.EXTENSIBLE){i.skip(6);const e=rs(i,16);a=e[0]|e[1]<<8}}a!==ia.MULAW&&a!==ia.ALAW||(c=8),this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;const a=ks(i,4);if("INFO"!==a&&"INF0"!==a)return;let s=i.filePos;for(;s<=e+t-8;){i.filePos=s;const e=ks(i,4),t=cs(i,r),a=rs(i,t);let n=0;for(let e=0;e<a.length&&0!==a[e];e++)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),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}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 r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;const i=Oi(r);if(i){const t=r.slice(e+10,i.size);Ui(t,i,this.metadataTags)}}getCodec(){if(t(this.audioInfo),this.audioInfo.format===ia.MULAW)return"ulaw";if(this.audioInfo.format===ia.ALAW)return"alaw";if(this.audioInfo.format===ia.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===ia.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}async getMimeType(){return"audio/wav"}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return t(e),e.computeDuration()}async getTracks(){return await this.readMetadata(),this.tracks}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const sa=2048;class na{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(t(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return R}getDisposition(){return{...ue}}async getFirstTimestamp(){return 0}async getPacketAtIndex(e,r){t(this.demuxer.audioInfo);const i=e*sa*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const a=Math.min(sa*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,a);if(e instanceof Promise&&(e=await e),!e)return null}let s;if(r.metadataOnly)s=Ot;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,a);e instanceof Promise&&(e=await e),t(e),s=rs(e,a)}const n=e*sa/this.demuxer.audioInfo.sampleRate,o=a/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,n),new Ut(s,"key",n,o,e,a)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,r){t(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/sa,(this.demuxer.dataSize-1)/(sa*this.demuxer.audioInfo.blockSizeInBytes))),a=await this.getPacketAtIndex(i,r);if(a)return a;if(0===i)return null;t(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,r);for(;s;){const e=await this.getNextPacket(s,r);if(!e)break;s=e}return s}getNextPacket(e,r){t(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/sa);return this.getPacketAtIndex(i+1,r)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const oa=e=>{const t=e.filePos,r=rs(e,9),i=new s(r);if(4095!==i.readBits(12))return null;i.skipBits(1);if(0!==i.readBits(2))return null;const a=i.readBits(1),n=i.readBits(2)+1,o=i.readBits(4);if(15===o)return null;i.skipBits(1);const c=i.readBits(3);if(0===c)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 d=i.readBits(13);i.skipBits(11);const l=i.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return 1===a?e.filePos-=2:h=i.readBits(16),{objectType:n,samplingFrequencyIndex:o,channelConfiguration:c,frameLength:d,numberOfAacFrames:l,crcCheck:h,startPos:t}},ca=1024;class da extends Pt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.tracks=[],this.readingMutex=new S,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();t(this.firstFrameHeader),this.tracks=[new Sr(this.input,new la(this))]})()}async advanceReader(){let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const r=oa(e);if(!r)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&r.startPos+r.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=r);const i=Ae[r.samplingFrequencyIndex];t(void 0!==i);const a=ca/i,s=r.crcCheck?9:7,n={timestamp:this.nextTimestampInSamples/i,duration:a,dataStart:r.startPos+s,dataSize:r.frameLength-s};this.loadedSamples.push(n),this.nextTimestampInSamples+=ca,this.lastLoadedPos=r.startPos+r.frameLength}async getMimeType(){return"audio/aac"}async getTracks(){return await this.readMetadata(),this.tracks}async computeDuration(){await this.readMetadata();const e=this.tracks[0];return t(e),e.computeDuration()}async getMetadataTags(){return{}}}class la{constructor(e){this.demuxer=e}getId(){return 1}async getFirstTimestamp(){return 0}getTimeResolution(){return this.getSampleRate()/ca}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getName(){return null}getLanguageCode(){return R}getCodec(){return"aac"}getInternalCodecId(){return t(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){t(this.demuxer.firstFrameHeader);const e=Be[this.demuxer.firstFrameHeader.channelConfiguration];return t(void 0!==e),e}getSampleRate(){t(this.demuxer.firstFrameHeader);const e=Ae[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return t(void 0!==e),e}getDisposition(){return{...ue}}async getDecoderConfig(){t(this.demuxer.firstFrameHeader);const e=new Uint8Array(3),r=new s(e),{objectType:i,samplingFrequencyIndex:a,channelConfiguration:n}=this.demuxer.firstFrameHeader;return i>31?(r.writeBits(5,31),r.writeBits(6,i-32)):r.writeBits(5,i),r.writeBits(4,a),r.writeBits(4,n),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate(),description:e.subarray(0,Math.ceil((r.pos-1)/8))}}async getPacketAtIndex(e,t){if(-1===e)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let i;if(t.metadataOnly)i=Ot;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=rs(e,r.dataSize)}return new Ut(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=x(this.demuxer.loadedSamples,e.timestamp,(e=>e.timestamp));if(-1===r)throw new Error("Packet was not created from this track.");const i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const r=P(this.demuxer.loadedSamples,e,(e=>e.timestamp));if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(r,t);if(r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const ha=e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null,ua=e=>{let t=0;const r=new s(rs(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);const i=[],a=t-1,n=new s(rs(e,a)),o=8-t-1;for(let e=0;e<o;e++)i.unshift(r.readBits(1));for(let e=0;e<a;e++)for(let e=0;e<8;e++){const t=n.readBits(1);e<2||i.unshift(t)}return i.reduce(((e,t,r)=>e|t<<r),0)},ma=(e,r)=>"uncommon-u16"===r?ss(e)+1:"uncommon-u8"===r?is(e)+1:"number"==typeof r?r:(B(r),void t(!1));
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class pa extends Pt{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.track=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new S,this.lastSampleLoaded=!1,this.reader=e._reader}async computeDuration(){return await this.readMetadata(),t(this.track),this.track.computeDuration()}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTracks(){return await this.readMetadata(),t(this.track),[this.track]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??=(async()=>{for(;null===this.reader.fileSize||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,null===r)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);t(r);const i=is(r),a=ns(r),n=!!(128&i);switch(127&i){case vt.STREAMINFO:{let r=this.reader.requestSlice(e,a);if(r instanceof Promise&&(r=await r),t(r),null===r)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const i=rs(r,34),n=new s(i),o=n.readBits(16),c=n.readBits(16),d=n.readBits(24),l=n.readBits(24),h=n.readBits(20),u=n.readBits(3)+1;n.readBits(5);const m=n.readBits(36);n.skipBits(128);const p=new Uint8Array(42);p.set(new Uint8Array([102,76,97,67]),0),p.set(new Uint8Array([128,0,0,34]),4),p.set(i,8),this.audioInfo={numberOfChannels:u,sampleRate:h,totalSamples:m,minimumBlockSize:o,maximumBlockSize:c,minimumFrameSize:d,maximumFrameSize:l,description:p},this.track=new Sr(this.input,new fa(this));break}case vt.VORBIS_COMMENT:{let r=this.reader.requestSlice(e,a);r instanceof Promise&&(r=await r),t(r),Ct(rs(r,a),this.metadataTags);break}case vt.PICTURE:{let r=this.reader.requestSlice(e,a);r instanceof Promise&&(r=await r),t(r);const i=ds(r),s=ds(r),n=l.decode(rs(r,s)),o=ds(r),c=l.decode(rs(r,o));r.skip(16);const d=ds(r),h=rs(r,d);this.metadataTags.images??=[],this.metadataTags.images.push({data:h,mimeType:n,kind:3===i?"coverFront":4===i?"coverBack":"unknown",description:c});break}}if(e+=a,n){this.lastLoadedPos=e;break}}})()}async readNextFlacFrame({startPos:e,isFirstPacket:r}){t(this.audioInfo);const i=this.audioInfo.maximumFrameSize+16,a=await this.reader.requestSliceRange(e,this.audioInfo.minimumFrameSize,i);if(!a)return null;const s=this.readFlacFrameHeader({slice:a,isFirstPacket:r});if(!s)return null;for(a.filePos=e+this.audioInfo.minimumFrameSize;;){if(a.filePos>a.end-6)return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:a.end-e,isLastFrame:!0};if(255===is(a)){const t=a.filePos;if(is(a)!==(1===this.blockingBit?249:248)){a.filePos=t;continue}a.skip(-2);const r=a.filePos-e,i=this.readFlacFrameHeader({slice:a,isFirstPacket:!1});if(!i){a.filePos=t;continue}if(0===this.blockingBit){if(i.num-s.num!=1){a.filePos=t;continue}}else if(i.num-s.num!==s.blockSize){a.filePos=t;continue}return{num:s.num,blockSize:s.blockSize,sampleRate:s.sampleRate,size:r,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:r}){const i=e.filePos,a=rs(e,4),n=new s(a);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){t(r);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){t(!r);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");t(!r);if(0!==n.readBits(1))return null}const o=ha(n.readBits(4));if(!o)return null;t(this.audioInfo);const c=((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}})(n.readBits(4),this.audioInfo.sampleRate);if(!c)return null;n.readBits(4),n.readBits(3);if(0!==n.readBits(1))return null;const d=ua(e),l=ma(e,o),h=((e,t)=>"uncommon-u16"===t?ss(e):"uncommon-u16-10"===t?10*ss(e):"uncommon-u8"===t?is(e):"number"==typeof t?t:null)(e,c);if(null===h)return null;if(h!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,m=is(e);e.skip(-u),e.skip(-1);const p=(e=>{let t=0;for(const r of e){t^=r;for(let e=0;e<8;e++)128&t?t=t<<1^7:t<<=1,t&=255}return t})(rs(e,u));return m!==p?null:{num:d,blockSize:l,sampleRate:h}}async advanceReader(){await this.readMetadata(),t(null!==this.lastLoadedPos),t(this.audioInfo);const e=this.lastLoadedPos,r=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!r)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],a={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:r.blockSize,byteOffset:e,byteSize:r.size};this.lastLoadedPos=this.lastLoadedPos+r.size,this.loadedSamples.push(a),r.isLastFrame&&(this.lastSampleLoaded=!0)}}class fa{constructor(e){this.demuxer=e}getId(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}async computeDuration(){const e=await this.getPacket(1/0,{metadataOnly:!0});return(e?.timestamp??0)+(e?.duration??0)}getSampleRate(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return R}getTimeResolution(){return t(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getDisposition(){return{...ue}}async getFirstTimestamp(){return 0}async getDecoderConfig(){return t(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,r){if(t(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const i=await this.demuxer.readingMutex.acquire();try{for(;;){const t=P(this.demuxer.loadedSamples,e,(e=>e.blockOffset/this.demuxer.audioInfo.sampleRate));if(-1===t){await this.demuxer.advanceReader();continue}const i=this.demuxer.loadedSamples[t],a=i.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+i.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(t,r);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,r);await this.demuxer.advanceReader()}}finally{i()}}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const r=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&r>=this.demuxer.loadedSamples.length)return null;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,r){const i=this.demuxer.loadedSamples[e];if(!i)return null;let a;if(r.metadataOnly)a=Ot;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;a=rs(e,i.byteSize)}t(this.demuxer.audioInfo);const s=i.blockOffset/this.demuxer.audioInfo.sampleRate,n=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Ut(a,"key",s,n,e,i.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class ga{}class wa extends ga{async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);return"ftyp"!==ks(t,4)?null:ks(t,4)}_createDemuxer(e){return new Br(e)}}class ka extends wa{async _canReadInput(e){const t=await this._getMajorBrand(e);return!!t&&"qt  "!==t}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class ba extends wa{async _canReadInput(e){return"qt  "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class ya extends ga{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,ei);if(r instanceof Promise&&(r=await r),!r)return!1;const i=ti(r);if(null===i)return!1;if(i<1||i>8)return!1;if(ii(r,i)!==$r.EBML)return!1;const a=si(r);if(null===a)return!1;let s=e._reader.requestSlice(r.filePos,a);if(s instanceof Promise&&(s=await s),!s)return!1;const n=r.filePos;for(;s.filePos<=n+a-2;){const e=ni(s);if(!e)break;const{id:r,size:i}=e,a=s.filePos;if(null===i)return!1;switch(r){case $r.EBMLVersion:if(1!==ii(s,i))return!1;break;case $r.EBMLReadVersion:if(1!==ii(s,i))return!1;break;case $r.DocType:if(oi(s,i)!==t)return!1;break;case $r.DocTypeVersion:if(ii(s,i)>4)return!1}s.filePos=a+i}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new yi(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ta extends ya{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Sa extends ga{async _canReadInput(e){let t=e._reader.requestSlice(0,10);if(t instanceof Promise&&(t=await t),!t)return!1;let r=0,i=!1;for(;;){let t=e._reader.requestSlice(r,10);if(t instanceof Promise&&(t=await t),!t)break;const a=Oi(t);if(!a)break;i=!0,r=t.filePos+a.size}const a=await Li(e._reader,r,r+4096);if(!a)return!1;if(i)return!0;r=a.startPos+a.header.totalSize;const s=await Li(e._reader,r,r+4);if(!s)return!1;const n=a.header,o=s.header;return n.channel===o.channel&&n.sampleRate===o.sampleRate}_createDemuxer(e){return new Wi(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class va extends ga{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const r=ks(t,4);if("RIFF"!==r&&"RIFX"!==r&&"RF64"!==r)return!1;t.skip(4);return"WAVE"===ks(t,4)}_createDemuxer(e){return new aa(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Ca extends ga{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===ks(t,4)}_createDemuxer(e){return new Zi(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class xa extends ga{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"fLaC"===ks(t,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new pa(e)}}class Pa extends ga{async _canReadInput(e){let t=e._reader.requestSliceRange(0,7,9);if(t instanceof Promise&&(t=await t),!t)return!1;const r=oa(t);if(!r)return!1;if(t=e._reader.requestSliceRange(r.frameLength,7,9),t instanceof Promise&&(t=await t),!t)return!1;const i=oa(t);return!!i&&(r.objectType===i.objectType&&r.samplingFrequencyIndex===i.samplingFrequencyIndex&&r.channelConfiguration===i.channelConfiguration)}_createDemuxer(e){return new da(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}const _a=new ka,Ia=new ba,Ea=new ya,Aa=new Ta,Ba=new Sa,Fa=new va,Ma=new Ca,Da=new Pa,za=new xa,Ra=[_a,Ia,Ea,Aa,Fa,Ma,za,Ba,Da];var Oa={},Ua=e({__proto__:null,default:Oa},[Oa]);
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
const Na=void 0!==Ua?Ua:void 0;class Va{constructor(){this._disposed=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new Ja;return this._sizePromise??=Promise.resolve(this._retrieveSize())}async getSize(){if(this._disposed)throw new Ja;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}}class La extends Va{constructor(e){if(!(e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=c(e),this._view=d(e)}_retrieveSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this.onread?.(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class Wa extends Va{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&&(!oe(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Xa({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:Ga.fileSystem})}_retrieveSize(){const e=this._blob.size;return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Q()){t=this._blob.slice(e.currentPos).stream().getReader()}else t=null;this._readers.set(e,t)}for(;e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:r,value:i}=await t.read();if(r)throw this._orchestrator.forgetWorker(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{const t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this.onread?.(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}e.running=!1}_dispose(){this._orchestrator.dispose()}}const Ha=524288,qa=(e,t,r)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))){let e=null;try{"undefined"!=typeof window&&void 0!==window.location&&(e=new URL(r instanceof Request?r.url:r,window.location.href).origin)}catch{}if(("undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)};class ja extends Va{constructor(e,t={}){if(!("string"==typeof e||e instanceof URL||"undefined"!=typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!=typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!=typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!=typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!oe(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.fetchFn&&"function"!=typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");super(),this._existingResponses=new WeakMap,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??qa,this._orchestrator=new Xa({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:2,runWorker:this._runWorker.bind(this),prefetchProfile:Ga.network})}async _retrieveSize(){const e=new AbortController,t=await q(this._options.fetchFn??fetch,this._url,W(this._options.requestInit??{},{headers:{Range:"bytes=0-"},signal:e.signal}),this._getRetryDelay,(()=>this._disposed));if(!t.ok)throw new Error(`Error fetching ${String(this._url)}: ${t.status} ${t.statusText}`);let r,i;if(206===t.status)i=this._getTotalLengthFromRangeResponse(t),r=this._orchestrator.createWorker(0,Math.min(i,Ha));else{const e=t.headers.get("Content-Length");if(!e)throw new Error(`HTTP response (status ${t.status}) must surface Content-Length header.`);i=Number(e),r=this._orchestrator.createWorker(0,i),this._orchestrator.options.maxCacheSize=1/0,console.warn("HTTP server did not respond with 206 Partial Content, meaning the entire remote resource now has to be downloaded. For efficient media file streaming across a network, please make sure your server supports range requests.")}return this._orchestrator.fileSize=i,this._existingResponses.set(r,{response:t,abortController:e}),this._orchestrator.runWorker(r),i}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;;){const r=this._existingResponses.get(e);this._existingResponses.delete(e);let i=r?.abortController,a=r?.response;if(i||(i=new AbortController,a=await q(this._options.fetchFn??fetch,this._url,W(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,(()=>this._disposed))),t(a),!a.ok)throw new Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(e.currentPos>0&&206!==a.status)throw new Error("HTTP server did not respond with 206 Partial Content to a range request. To enable efficient media file streaming across a network, please make sure your server supports range requests.");if(!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const s=a.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return i.abort(),void(e.running=!1);let t;try{t=await s.read()}catch(e){if(this._disposed)throw e;const t=this._getRetryDelay(1,e,this._url);if(null!==t){console.error("Error while reading response stream. Attempting to resume.",e),await new Promise((e=>setTimeout(e,1e3*t)));break}throw e}if(e.aborted)break;const{done:r,value:a}=t;if(r){if(e.currentPos>=e.targetPos)return this._orchestrator.forgetWorker(e),void(e.running=!1);break}this.onread?.(e.currentPos,e.currentPos+a.length),this._orchestrator.supplyWorkerData(e,a)}if(e.aborted)break}e.running=!1}_getTotalLengthFromRangeResponse(e){const t=e.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e)return Number(e[1])}const r=e.headers.get("Content-Length");if(r)return Number(r);throw new Error("Partial HTTP response (status 206) must surface either Content-Range or Content-Length header.")}_dispose(){this._orchestrator.dispose()}}class $a extends Va{constructor(e,r={}){if("string"!=typeof e)throw new TypeError("filePath must be a string.");if(!r||"object"!=typeof r)throw new TypeError("options must be an object.");if(void 0!==r.maxCacheSize&&(!oe(r.maxCacheSize)||r.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._fileHandle=null,this._streamSource=new Qa({getSize:async()=>{this._fileHandle=await Na.fs.open(e,"r");return(await this._fileHandle.stat()).size},read:async(e,r)=>{t(this._fileHandle);const i=new Uint8Array(r-e);return await this._fileHandle.read(i,0,r-e,e),i},maxCacheSize:r.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,t){return this._streamSource._read(e,t)}_retrieveSize(){return this._streamSource._retrieveSize()}_dispose(){this._streamSource._dispose(),this._fileHandle?.close(),this._fileHandle=null}}class Qa extends Va{constructor(e){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if("function"!=typeof e.getSize)throw new TypeError("options.getSize must be a function.");if("function"!=typeof e.read)throw new TypeError("options.read must be a function.");if(void 0!==e.dispose&&"function"!=typeof e.dispose)throw new TypeError("options.dispose, when provided, must be a function.");if(void 0!==e.maxCacheSize&&(!oe(e.maxCacheSize)||e.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw new TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new Xa({maxCacheSize:e.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:Ga[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_retrieveSize(){const e=this._options.getSize();if(e instanceof Promise)return e.then((e=>{if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}));if(!Number.isInteger(e)||e<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=e,e}_read(e,t){return this._orchestrator.read(e,t)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,r=e.targetPos;let i=this._options.read(e.currentPos,r);if(i instanceof Promise&&(i=await i),e.aborted)break;if(i instanceof Uint8Array){if(i=c(i),i.length!==r-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${r-e.currentPos} bytes, but got ${i.length}.`);this.onread?.(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{if(!(i instanceof ReadableStream))throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.");{const a=i.getReader();for(;e.currentPos<r&&!e.aborted;){const{done:i,value:s}=await a.read();if(i){if(e.currentPos<r)throw new Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${r-t} bytes, but got ${e.currentPos-t}`);break}if(!(s instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const n=c(s);this.onread?.(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}}e.running=!1}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}class Ka extends Va{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&&(!oe(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??16777216}_retrieveSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const r=P(this._cache,e,(e=>e.start)),i=-1!==r?this._cache[r]:null;if(i&&i.start<=e&&t<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let a=e;const s=new Uint8Array(t-e);if(-1!==r)for(let i=r;i<this._cache.length;i++){const r=this._cache[i];if(r.start>=t)break;const n=Math.max(e,r.start);n>a&&this._throwDueToCacheMiss();const o=Math.min(t,r.end);n<o&&(s.set(r.bytes.subarray(n-r.start,o-r.start),n-e),a=o)}if(a===t)return{bytes:s,view:d(s),offset:e};this._currentIndex>a&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:c}=I();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 r=this._currentIndex,i=this._currentIndex+t.byteLength;for(let e=0;e<this._pendingSlices.length;e++){const a=this._pendingSlices[e],s=Math.max(r,a.start),n=Math.min(i,a.end);s<n&&(a.bytes.set(t.subarray(s-r,n-r),s-a.start),n===a.end&&(a.resolve({bytes:a.bytes,view:d(a.bytes),offset:a.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:r,end:i,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}}const Ga={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>{const r=65536;return{start:e=Math.floor((e-r)/r)*r,end:t=Math.ceil((t+r)/r)*r}},network:(e,t,r)=>{const i=65536;e=Math.max(0,Math.floor((e-i)/i)*i);for(const i of r){const r=8388608,a=Math.max((i.startPos+i.targetPos)/2,i.targetPos-r);if(ee(e,t,a,i.targetPos)){const e=i.targetPos-i.startPos,a=Math.ceil((e+1)/r)*r,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,a);t=Math.max(t,i.startPos+n)}}return{start:e,end:t=Math.max(t,e+Ha)}}};class Xa{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1}read(e,r){t(null!==this.fileSize);const i=this.options.prefetchProfile(e,r,this.workers),a=Math.max(i.start,0),s=Math.min(i.end,this.fileSize);t(a<=e&&r<=s);let n=null;const o=P(this.cache,e,(e=>e.start)),c=-1!==o?this.cache[o]:null;c&&c.start<=e&&r<=c.end&&(c.age=this.nextAge++,n={bytes:c.bytes,view:c.view,offset:c.start});const l=P(this.cache,a,(e=>e.start)),h=n?null:new Uint8Array(r-e);let u=0,m=a;const p=[];if(-1!==l){for(let i=l;i<this.cache.length;i++){const n=this.cache[i];if(n.start>=s)break;if(n.end<=a)continue;const o=Math.max(a,n.start),c=Math.min(s,n.end);if(t(o<=c),m<o&&p.push({start:m,end:o}),m=c,h){const t=Math.max(e,n.start),i=Math.min(r,n.end);if(t<i){const r=t-e;h.set(n.bytes.subarray(t-n.start,i-n.start),r),r===u&&(u=i-e)}}n.age=this.nextAge++}m<s&&p.push({start:m,end:s})}else p.push({start:a,end:s});if(h&&u>=h.length&&(n={bytes:h,view:d(h),offset:e}),0===p.length)return t(n),n;const{promise:f,resolve:g,reject:w}=I(),k=[];for(const t of p){const i=Math.max(e,t.start),a=Math.min(r,t.end);i===t.start&&a===t.end?k.push(t):i<a&&k.push({start:i,end:a})}for(const t of p){const r=h&&{start:e,bytes:h,holes:k,resolve:g,reject:w};let i=!1;for(const e of this.workers){const a=2**17;if(ee(t.start-a,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end),i=!0,r&&!e.pendingSlices.includes(r)&&e.pendingSlices.push(r),e.running||this.runWorker(e);break}}if(!i){const e=this.createWorker(t.start,t.end);r&&(e.pendingSlices=[r]),this.runWorker(e)}}return n||(t(h),n=f.then((t=>({bytes:t,view:d(t),offset:e})))),n}createWorker(e,t){const r={startPos:e,currentPos:e,targetPos:t,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};for(this.workers.push(r);this.workers.length>this.options.maxWorkerCount;){let e=0,t=this.workers[0];for(let r=1;r<this.workers.length;r++){const i=this.workers[r];i.age<t.age&&(e=r,t=i)}if(t.running&&t.pendingSlices.length>0)break;t.aborted=!0,this.workers.splice(e,1)}return r}runWorker(e){t(!e.running),t(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}))}supplyWorkerData(e,r){t(!e.aborted);const i=e.currentPos,a=i+r.length;this.insertIntoCache({start:i,end:a,bytes:r,view:d(r),age:this.nextAge++}),e.currentPos+=r.length,e.targetPos=Math.max(e.targetPos,e.currentPos);for(let t=0;t<e.pendingSlices.length;t++){const s=e.pendingSlices[t],n=Math.max(i,s.start),o=Math.min(a,s.start+s.bytes.length);n<o&&s.bytes.set(r.subarray(n-i,o-i),n-s.start);for(let e=0;e<s.holes.length;e++){const t=s.holes[e];i<=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(t,1),t--)}for(let t=0;t<this.workers.length;t++){const r=this.workers[t];e===r||r.running||ee(i,a,r.currentPos,r.targetPos)&&(this.workers.splice(t,1),t--)}}forgetWorker(e){const r=this.workers.indexOf(e);t(-1!==r),this.workers.splice(r,1)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=P(this.cache,e.start,(e=>e.start))+1;if(t>0){const r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){const i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=d(i),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){const t=this.cache[r];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(r,1),this.currentCacheSize-=t.bytes.length,r--;continue}const i=new Uint8Array(t.end-e.start);i.set(e.bytes,0),i.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=i,e.view=d(i),e.end=t.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let r=1;r<this.cache.length;r++){const i=this.cache[r];i.age<t.age&&(e=r,t=i)}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}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */ne();class Ya{get disposed(){return this._disposed}constructor(e){if(this._demuxerPromise=null,this._format=null,this._disposed=!1,!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some((e=>!(e instanceof ga))))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Va))throw new TypeError("options.source must be a Source.");if(e.source._disposed)throw new Error("options.source must not be disposed.");this._formats=e.formats,this._source=e.source,this._reader=new Za(e.source)}_getDemuxer(){return this._demuxerPromise??=(async()=>{this._reader.fileSize=await this._source.getSizeOrNull();for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,e._createDemuxer(this)}throw new Error("Input has an unsupported or unrecognizable format.")})()}get source(){return this._source}async getFormat(){return await this._getDemuxer(),t(this._format),this._format}async computeDuration(){return(await this._getDemuxer()).computeDuration()}async getTracks(){return(await this._getDemuxer()).getTracks()}async getVideoTracks(){return(await this.getTracks()).filter((e=>e.isVideoTrack()))}async getAudioTracks(){return(await this.getTracks()).filter((e=>e.isAudioTrack()))}async getPrimaryVideoTrack(){return(await this.getTracks()).find((e=>e.isVideoTrack()))??null}async getPrimaryAudioTrack(){return(await this.getTracks()).find((e=>e.isAudioTrack()))??null}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){this._disposed||(this._disposed=!0,this._source._disposed=!0,this._source._dispose())}[Symbol.dispose](){this.dispose()}}class Ja extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Za{constructor(e){this.source=e}requestSlice(e,t){if(this.source._disposed)throw new Ja;if(null!==this.fileSize&&e+t>this.fileSize)return null;const r=e+t,i=this.source._read(e,r);return i instanceof Promise?i.then((t=>t?new es(t.bytes,t.view,t.offset,e,r):null)):i?new es(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,r,i){if(this.source._disposed)throw new Ja;if(null!==this.fileSize)return this.requestSlice(e,z(this.fileSize-e,r,i));{const a=this.requestSlice(e,i),s=a=>{if(a)return a;const s=a=>(t(null!==a),this.requestSlice(e,z(a-e,r,i))),n=this.source._retrieveSize();return n instanceof Promise?n.then(s):s(n)};return a instanceof Promise?a.then(s):s(a)}}}class es{constructor(e,t,r,i,a){this.bytes=e,this.view=t,this.offset=r,this.start=i,this.end=a,this.bufferPos=i-r}static tempFromBytes(e){return new es(e,d(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new es(this.bytes,this.view,this.offset,e,e+t)}}const ts=(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.`)},rs=(e,t)=>{ts(e,t);const r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},is=e=>(ts(e,1),e.view.getUint8(e.bufferPos++)),as=(e,t)=>{ts(e,2);const r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},ss=e=>{ts(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},ns=e=>{ts(e,3);const t=F(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},os=e=>{ts(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},cs=(e,t)=>{ts(e,4);const r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},ds=e=>{ts(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},ls=e=>{ts(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},hs=e=>{ts(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},us=(e,t)=>{let r,i;return t?(r=cs(e,!0),i=cs(e,!0)):(i=cs(e,!1),r=cs(e,!1)),4294967296*i+r},ms=e=>4294967296*ds(e)+ds(e),ps=e=>4294967296*hs(e)+ds(e),fs=e=>{const t=ls(e),r=(e=>{ts(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*r+t},gs=e=>{ts(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},ws=e=>{ts(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},ks=(e,t)=>{ts(e,t);let r="";for(let i=0;i<t;i++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r},bs=new Uint8Array([102,76,97,67]);class ys extends $e{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.writer=e._writer,this.format=t}async start(){this.writer.write(bs)}writeHeader({bitsPerSample:e,minimumBlockSize:r,maximumBlockSize:i,minimumFrameSize:a,maximumFrameSize:n,sampleRate:o,channels:c,totalSamples:d}){t(4===this.writer.getPos());const l=!he(this.output._metadataTags),h=new s(new Uint8Array(4));h.writeBits(1,Number(!l)),h.writeBits(7,vt.STREAMINFO),h.writeBits(24,34),this.writer.write(h.bytes);const u=new s(new Uint8Array(18));if(u.writeBits(16,r),u.writeBits(16,i),u.writeBits(24,a),u.writeBits(24,n),u.writeBits(20,o),u.writeBits(3,c-1),u.writeBits(5,e-1),d>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");u.writeBits(4,0),u.writeBits(32,d),this.writer.write(u.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){const r=32+e.mimeType.length+(e.description?.length??0)+e.data.length,i=new Uint8Array(r);let a=0;const n=d(i);n.setUint32(a,"coverFront"===e.kind?3:"coverBack"===e.kind?4:0),a+=4,n.setUint32(a,e.mimeType.length),a+=4,i.set(h.encode(e.mimeType),8),a+=e.mimeType.length,n.setUint32(a,e.description?.length??0),a+=4,i.set(h.encode(e.description??""),a),a+=e.description?.length??0,a+=16,n.setUint32(a,e.data.length),a+=4,i.set(e.data,a),a+=e.data.length,t(a===r);const o=new s(new Uint8Array(4));o.writeBits(1,0),o.writeBits(7,vt.PICTURE),o.writeBits(24,r),this.writer.write(o.bytes),this.writer.write(i)}writeVorbisCommentAndPictureBlock(){if(this.writer.seek(38+bs.byteLength),he(this.output._metadataTags))return void(this.metadataWritten=!0);const e=this.output._metadataTags.images??[];for(const t of e)this.writePictureBlock(t);const t=xt(new Uint8Array(0),this.output._metadataTags,!1),r=new s(new Uint8Array(4));r.writeBits(1,1),r.writeBits(7,vt.VORBIS_COMMENT),r.writeBits(24,t.length),this.writer.write(r.bytes),this.writer.write(t),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw new Error("FLAC does not support video.")}async addEncodedAudioPacket(e,r,i){const a=await this.mutex.acquire();qe(i),t(i),t(i.decoderConfig),t(i.decoderConfig.description);try{if(this.validateAndNormalizeTimestamp(e,r.timestamp,"key"===r.type),null===this.sampleRate&&(this.sampleRate=i.decoderConfig.sampleRate),null===this.channels&&(this.channels=i.decoderConfig.numberOfChannels),null===this.bitsPerSample){const e=new s(c(i.decoderConfig.description));e.skipBits(167);const t=e.readBits(5)+1;this.bitsPerSample=t}this.metadataWritten||this.writeVorbisCommentAndPictureBlock();const t=es.tempFromBytes(r.data);rs(t,2);const a=rs(t,2),n=new s(a),o=ha(n.readBits(4));if(null===o)throw new Error("Invalid FLAC frame: Invalid block size.");ua(t);const d=ma(t,o);this.blockSizes.push(d),this.frameSizes.push(r.data.length);const l=this.writer.getPos();this.writer.write(r.data),this.format._options.onFrame&&this.format._options.onFrame(r.data,l),await this.writer.flush()}finally{a()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();let r=1/0,i=0,a=1/0,s=0,n=0;for(let e=0;e<this.blockSizes.length;e++){a=Math.min(a,this.frameSizes[e]),s=Math.max(s,this.frameSizes[e]),i=Math.max(i,this.blockSizes[e]),n+=this.blockSizes[e];e===this.blockSizes.length-1||(r=Math.min(r,this.blockSizes[e]))}t(null!==this.sampleRate),t(null!==this.channels),t(null!==this.bitsPerSample),this.writer.seek(4),this.writeHeader({minimumBlockSize:r,maximumBlockSize:i,minimumFrameSize:a,maximumFrameSize:s,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:n}),e()}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const Ts=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Ss=/^WEBVTT(.|\n)*?\n{2}/,vs=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class Cs{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){let t;if(e=e.replaceAll("\r\n","\n").replaceAll("\r","\n"),Ts.lastIndex=0,!this.preambleText){if(!Ss.test(e))throw new Error("WebVTT preamble incorrect.");t=Ts.exec(e);const r=e.slice(0,t?.index??e.length).trimEnd();if(!r)throw new Error("No WebVTT preamble provided.");this.preambleText=r,t&&(e=e.slice(t.index),Ts.lastIndex=0)}for(;t=Ts.exec(e);){const r=e.slice(0,t.index),i=t[1],a=t.index+t[0].length,s=e.indexOf("\n",a)+1,n=e.slice(a,s).trim();let o=e.indexOf("\n\n",a);-1===o&&(o=e.length);const c=Ps(t[2]),d=Ps(t[3])-c,l=e.slice(s,o).trim();e=e.slice(o).trimStart(),Ts.lastIndex=0;const h={timestamp:c/1e3,duration:d/1e3,text:l,identifier:i,settings:n,notes:r},u={};this.preambleEmitted||(u.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(h,u)}}}const xs=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Ps=e=>{const t=xs.exec(e);if(!t)throw new Error("Expected match.");return 36e5*Number(t[1]||"0")+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])},_s=e=>{const t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),i=Math.floor(e%6e4/1e3),a=e%1e3;return t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+a.toString().padStart(3,"0")};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class Is{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,Math.floor(e/2**32),!1),this.helperView.setUint32(4,e,!1),this.writer.write(this.helper.subarray(0,8))}writeAscii(e){for(let t=0;t<e.length;t++)this.helperView.setUint8(t%8,e.charCodeAt(t)),t%8==7&&this.writer.write(this.helper);e.length%8!=0&&this.writer.write(this.helper.subarray(0,e.length%8))}writeBox(e){if(this.offsets.set(e,this.writer.getPos()),e.contents&&!e.children)this.writeBoxHeader(e,e.size??e.contents.byteLength+8),this.writer.write(e.contents);else{const t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(const t of e.children)t&&this.writeBox(t);const r=this.writer.getPos(),i=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(r)}}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 r=this.offsets.get(e);t(void 0!==r);const i=this.writer.getPos();this.writer.seek(r),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children){return this.measureBoxHeader(e)+e.contents.byteLength}{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const r of e.children)r&&(t+=this.measureBox(r));return t}}}const Es=new Uint8Array(8),As=new DataView(Es.buffer),Bs=e=>[(e%256+256)%256],Fs=e=>(As.setUint16(0,e,!1),[Es[0],Es[1]]),Ms=e=>(As.setInt16(0,e,!1),[Es[0],Es[1]]),Ds=e=>(As.setUint32(0,e,!1),[Es[1],Es[2],Es[3]]),zs=e=>(As.setUint32(0,e,!1),[Es[0],Es[1],Es[2],Es[3]]),Rs=e=>(As.setInt32(0,e,!1),[Es[0],Es[1],Es[2],Es[3]]),Os=e=>(As.setUint32(0,Math.floor(e/2**32),!1),As.setUint32(4,e,!1),[Es[0],Es[1],Es[2],Es[3],Es[4],Es[5],Es[6],Es[7]]),Us=e=>(As.setInt16(0,256*e,!1),[Es[0],Es[1]]),Ns=e=>(As.setInt32(0,65536*e,!1),[Es[0],Es[1],Es[2],Es[3]]),Vs=e=>(As.setInt32(0,2**30*e,!1),[Es[0],Es[1],Es[2],Es[3]]),Ls=(e,t)=>{const r=[];let i=e;do{let e=127&i;i>>=7,r.length>0&&(e|=128),r.push(e),void 0!==t&&t--}while(i>0||t);return r.reverse()},Ws=(e,t=!1)=>{const r=Array(e.length).fill(null).map(((t,r)=>e.charCodeAt(r)));return t&&r.push(0),r},Hs=e=>{let t=null;for(const r of e)(!t||r.timestamp>t.timestamp)&&(t=r);return t},qs=e=>{const t=e*(Math.PI/180),r=Math.round(Math.cos(t)),i=Math.round(Math.sin(t));return[r,i,0,-i,r,0,0,0,1]},js=qs(0),$s=e=>[Ns(e[0]),Ns(e[1]),Vs(e[2]),Ns(e[3]),Ns(e[4]),Vs(e[5]),Ns(e[6]),Ns(e[7]),Vs(e[8])],Qs=(e,t,r)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:r}),Ks=(e,t,r,i,a)=>Qs(e,[Bs(t),Ds(r),i??[]],a),Gs=e=>({type:"mdat",largeSize:e}),Xs=e=>Qs("moov",void 0,[Ys(e.creationTime,e.trackDatas),...e.trackDatas.map((t=>Js(t,e.creationTime))),e.isFragmented?Fn(e.trackDatas):null,$n(e)]),Ys=(e,t)=>{const r=So(Math.max(0,...t.filter((e=>e.samples.length>0)).map((e=>{const t=Hs(e.samples);return t.timestamp+t.duration}))),yo),i=Math.max(0,...t.map((e=>e.track.id)))+1,s=!a(e)||!a(r),n=s?Os:zs;return Ks("mvhd",+s,0,[n(e),n(e),zs(yo),n(r),Ns(1),Us(1),Array(10).fill(0),$s(js),Array(24).fill(0),zs(i)])},Js=(e,t)=>{const r=To(e);return Qs("trak",void 0,[Zs(e,t),en(e,t),void 0!==r.name?Qs("udta",void 0,[Qs("name",[...h.encode(r.name)])]):null])},Zs=(e,t)=>{const r=Hs(e.samples),i=So(r?r.timestamp+r.duration:0,yo),s=!a(t)||!a(i),n=s?Os:zs;let o;if("video"===e.type){const t=e.track.metadata.rotation;o=qs(t??0)}else o=js;let c=2;return!1!==e.track.metadata.disposition?.default&&(c|=1),Ks("tkhd",+s,c,[n(t),n(t),zs(e.track.id),zs(0),n(i),Array(8).fill(0),Fs(0),Fs(e.track.id),Us("audio"===e.type?1:0),Fs(0),$s(o),Ns("video"===e.type?e.info.width:0),Ns("video"===e.type?e.info.height:0)])},en=(e,t)=>Qs("mdia",void 0,[tn(e,t),sn(!0,rn[e.type],an[e.type]),nn(e)]),tn=(e,t)=>{const r=Hs(e.samples),i=So(r?r.timestamp+r.duration:0,e.timescale),s=!a(t)||!a(i),n=s?Os:zs;return Ks("mdhd",+s,0,[n(t),n(t),zs(e.timescale),n(i),Fs(no(e.track.metadata.languageCode??R)),Fs(0)])},rn={video:"vide",audio:"soun",subtitle:"text"},an={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},sn=(e,t,r,i="\0\0\0\0")=>Ks("hdlr",0,0,[e?Ws("mhlr"):zs(0),Ws(t),Ws(i),zs(0),zs(0),Ws(r,!0)]),nn=e=>Qs("minf",void 0,[on[e.type](),cn(),hn(e)]),on={video:()=>Ks("vmhd",0,1,[Fs(0),Fs(0),Fs(0),Fs(0)]),audio:()=>Ks("smhd",0,0,[Fs(0),Fs(0)]),subtitle:()=>Ks("nmhd",0,0)},cn=()=>Qs("dinf",void 0,[dn()]),dn=()=>Ks("dref",0,0,[zs(1)],[ln()]),ln=()=>Ks("url ",0,1),hn=e=>{const t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some((e=>0!==e.sampleCompositionTimeOffset));return Qs("stbl",void 0,[un(e),xn(e),t?An(e):null,t?Bn(e):null,_n(e),In(e),En(e),Pn(e)])},un=e=>{let r;if("video"===e.type)r=mn(eo(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){const i=ro(e.track.source._codec,e.muxer.isQuickTime);t(i),r=gn(i,e)}else"subtitle"===e.type&&(r=Cn(ao[e.track.source._codec],e));return t(r),Ks("stsd",0,0,[zs(1)],[r])},mn=(e,t)=>Qs(e,[Array(6).fill(0),Fs(1),Fs(0),Fs(0),Array(12).fill(0),Fs(t.info.width),Fs(t.info.height),zs(4718592),zs(4718592),zs(0),Fs(1),Array(32).fill(0),Fs(24),Ms(65535)],[to[t.track.source._codec](t),y(t.info.decoderConfig.colorSpace)?pn(t):null]),pn=e=>Qs("colr",[Ws("nclx"),Fs(p[e.info.decoderConfig.colorSpace.primaries]),Fs(g[e.info.decoderConfig.colorSpace.transfer]),Fs(k[e.info.decoderConfig.colorSpace.matrix]),Bs((e.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),fn=e=>{if(!e.info.decoderConfig)return null;const t=e.info.decoderConfig,r=t.codec.split("."),i=Number(r[1]),a=Number(r[2]),s=(Number(r[3])<<4)+((r[4]?Number(r[4]):1)<<1)+(r[8]?Number(r[8]):Number(t.colorSpace?.fullRange??0)),n=r[5]?Number(r[5]):t.colorSpace?.primaries?p[t.colorSpace.primaries]:2,o=r[6]?Number(r[6]):t.colorSpace?.transfer?g[t.colorSpace.transfer]:2,c=r[7]?Number(r[7]):t.colorSpace?.matrix?k[t.colorSpace.matrix]:2;return Ks("vpcC",1,0,[Bs(i),Bs(a),Bs(s),Bs(n),Bs(o),Bs(c),Fs(0)])},gn=(e,t)=>{let r,i=0,a=16;if(pe.includes(t.track.source._codec)){const e=t.track.source._codec,{sampleSize:r}=ze(e);a=8*r,a>16&&(i=1)}return r=0===i?[Array(6).fill(0),Fs(1),Fs(i),Fs(0),zs(0),Fs(t.info.numberOfChannels),Fs(a),Fs(0),Fs(0),Fs(t.info.sampleRate<65536?t.info.sampleRate:0),Fs(0)]:[Array(6).fill(0),Fs(1),Fs(i),Fs(0),zs(0),Fs(t.info.numberOfChannels),Fs(Math.min(a,16)),Fs(0),Fs(0),Fs(t.info.sampleRate<65536?t.info.sampleRate:0),Fs(0),zs(1),zs(a/8),zs(t.info.numberOfChannels*a/8),zs(2)],Qs(e,r,[io(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},wn=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 r=[...Bs(t),...Bs(21),...Ds(0),...zs(0),...zs(0)];if(e.info.decoderConfig.description){const t=c(e.info.decoderConfig.description);r=[...r,...Bs(5),...Ls(t.byteLength),...t]}return r=[...Fs(1),...Bs(0),...Bs(4),...Ls(r.length),...r,...Bs(6),...Bs(1),...Bs(2)],r=[...Bs(3),...Ls(r.length),...r],Ks("esds",0,0,r)},kn=e=>Qs("wave",void 0,[bn(e),yn(e),Qs("\0\0\0\0")]),bn=e=>Qs("frma",[Ws(ro(e.track.source._codec,e.muxer.isQuickTime))]),yn=e=>{const{littleEndian:t}=ze(e.track.source._codec);return Qs("enda",[Fs(+t)])},Tn=e=>{let r=e.info.numberOfChannels,i=3840,a=e.info.sampleRate,s=0,n=0,o=new Uint8Array(0);const d=e.info.decoderConfig?.description;if(d){t(d.byteLength>=18);const e=c(d),l=bt(e);r=l.outputChannelCount,i=l.preSkip,a=l.inputSampleRate,s=l.outputGain,n=l.channelMappingFamily,l.channelMappingTable&&(o=l.channelMappingTable)}return Qs("dOps",[Bs(0),Bs(r),Fs(i),zs(a),Ms(s),Bs(n),...o])},Sn=e=>{const r=e.info.decoderConfig?.description;t(r);const i=c(r);return Ks("dfLa",0,0,[...i.subarray(4)])},vn=e=>{const{littleEndian:t,sampleSize:r}=ze(e.track.source._codec);return Ks("pcmC",0,0,[Bs(+t),Bs(8*r)])},Cn=(e,t)=>Qs(e,[Array(6).fill(0),Fs(1)],[so[t.track.source._codec](t)]),xn=e=>Ks("stts",0,0,[zs(e.timeToSampleTable.length),e.timeToSampleTable.map((e=>[zs(e.sampleCount),zs(e.sampleDelta)]))]),Pn=e=>{if(e.samples.every((e=>"key"===e.type)))return null;const t=[...e.samples.entries()].filter((([,e])=>"key"===e.type));return Ks("stss",0,0,[zs(t.length),t.map((([e])=>zs(e+1)))])},_n=e=>Ks("stsc",0,0,[zs(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map((e=>[zs(e.firstChunk),zs(e.samplesPerChunk),zs(1)]))]),In=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){const{sampleSize:t}=ze(e.track.source._codec);return Ks("stsz",0,0,[zs(t*e.info.numberOfChannels),zs(e.samples.reduce(((t,r)=>t+So(r.duration,e.timescale)),0))])}return Ks("stsz",0,0,[zs(0),zs(e.samples.length),e.samples.map((e=>zs(e.size)))])},En=e=>e.finalizedChunks.length>0&&i(e.finalizedChunks).offset>=2**32?Ks("co64",0,0,[zs(e.finalizedChunks.length),e.finalizedChunks.map((e=>Os(e.offset)))]):Ks("stco",0,0,[zs(e.finalizedChunks.length),e.finalizedChunks.map((e=>zs(e.offset)))]),An=e=>Ks("ctts",1,0,[zs(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map((e=>[zs(e.sampleCount),Rs(e.sampleCompositionTimeOffset)]))]),Bn=e=>{let r=1/0,i=-1/0,a=1/0,s=-1/0;t(e.compositionTimeOffsetTable.length>0),t(e.samples.length>0);for(let t=0;t<e.compositionTimeOffsetTable.length;t++){const a=e.compositionTimeOffsetTable[t];r=Math.min(r,a.sampleCompositionTimeOffset),i=Math.max(i,a.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){const r=e.samples[t];a=Math.min(a,So(r.timestamp,e.timescale)),s=Math.max(s,So(r.timestamp+r.duration,e.timescale))}const n=Math.max(-r,0);return s>=2**31?null:Ks("cslg",0,0,[Rs(n),Rs(r),Rs(i),Rs(a),Rs(s)])},Fn=e=>Qs("mvex",void 0,e.map(Mn)),Mn=e=>Ks("trex",0,0,[zs(e.track.id),zs(1),zs(0),zs(0),zs(0)]),Dn=(e,t)=>Qs("moof",void 0,[zn(e),...t.map(On)]),zn=e=>Ks("mfhd",0,0,[zs(e)]),Rn=e=>{let t=0,r=0;const i="delta"===e.type;return r|=+i,t|=i?1:2,t<<24|r<<16},On=e=>Qs("traf",void 0,[Un(e),Nn(e),Vn(e)]),Un=e=>{t(e.currentChunk);let r=0;r|=8,r|=16,r|=32,r|=131072;const i=e.currentChunk.samples[1]??e.currentChunk.samples[0],a={duration:i.timescaleUnitsToNextSample,size:i.size,flags:Rn(i)};return Ks("tfhd",0,131128,[zs(e.track.id),zs(a.duration),zs(a.size),zs(a.flags)])},Nn=e=>(t(e.currentChunk),Ks("tfdt",1,0,[Os(So(e.currentChunk.startTimestamp,e.timescale))])),Vn=e=>{t(e.currentChunk);const r=e.currentChunk.samples.map((e=>e.timescaleUnitsToNextSample)),i=e.currentChunk.samples.map((e=>e.size)),a=e.currentChunk.samples.map(Rn),s=e.currentChunk.samples.map((t=>So(t.timestamp-t.decodeTimestamp,e.timescale))),n=new Set(r),o=new Set(i),c=new Set(a),d=new Set(s),l=2===c.size&&a[0]!==a[1],h=n.size>1,u=o.size>1,m=!l&&c.size>1,p=d.size>1||[...d].some((e=>0!==e));let f=0;return f|=1,f|=4*+l,f|=256*+h,f|=512*+u,f|=1024*+m,f|=2048*+p,Ks("trun",1,f,[zs(e.currentChunk.samples.length),zs(e.currentChunk.offset-e.currentChunk.moofOffset||0),l?zs(a[0]):[],e.currentChunk.samples.map(((e,t)=>[h?zs(r[t]):[],u?zs(i[t]):[],m?zs(a[t]):[],p?Rs(s[t]):[]]))])},Ln=(e,t)=>Ks("tfra",1,0,[zs(e.track.id),zs(63),zs(e.finalizedChunks.length),e.finalizedChunks.map((r=>[Os(So(r.samples[0].timestamp,e.timescale)),Os(r.moofOffset),zs(t+1),zs(1),zs(1)]))]),Wn=()=>Ks("mfro",0,0,[zs(0)]),Hn=()=>Qs("vtte"),qn=(e,t,r,i,a)=>Qs("vttc",void 0,[null!==a?Qs("vsid",[Rs(a)]):null,null!==r?Qs("iden",[...h.encode(r)]):null,null!==t?Qs("ctim",[...h.encode(_s(t))]):null,null!==i?Qs("sttg",[...h.encode(i)]):null,Qs("payl",[...h.encode(e)])]),jn=e=>Qs("vtta",[...h.encode(e)]),$n=e=>{const t=[],r=e.format._options.metadataFormat??"auto",i=e.output._metadataTags;if("mdir"===r||"auto"===r&&!e.isQuickTime){const e=Yn(i);e&&t.push(e)}else if("mdta"===r){const e=Jn(i);e&&t.push(e)}else("udta"===r||"auto"===r&&e.isQuickTime)&&Qn(t,e.output._metadataTags);return 0===t.length?null:Qs("udta",void 0,t)},Qn=(e,t)=>{for(const{key:r,value:i}of te(t))switch(r){case"title":e.push(Kn("©nam",i));break;case"description":e.push(Kn("©des",i));break;case"artist":e.push(Kn("©ART",i));break;case"album":e.push(Kn("©alb",i));break;case"albumArtist":e.push(Kn("albr",i));break;case"genre":e.push(Kn("©gen",i));break;case"date":e.push(Kn("©day",i.toISOString().slice(0,10)));break;case"comment":e.push(Kn("©cmt",i));break;case"lyrics":e.push(Kn("©lyr",i));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:B(r)}if(t.raw)for(const r in t.raw){const i=t.raw[r];null==i||4!==r.length||e.some((e=>e.type===r))||("string"==typeof i?e.push(Kn(r,i)):i instanceof Uint8Array&&e.push(Qs(r,Array.from(i))))}},Kn=(e,t)=>{const r=h.encode(t);return Qs(e,[Fs(r.length),Fs(no("und")),Array.from(r)])},Gn={"image/jpeg":13,"image/png":14,"image/bmp":27},Xn=(e,t)=>{const r=[];for(const{key:i,value:a}of te(e))switch(i){case"title":r.push({key:t?"title":"©nam",value:Zn(a)});break;case"description":r.push({key:t?"description":"©des",value:Zn(a)});break;case"artist":r.push({key:t?"artist":"©ART",value:Zn(a)});break;case"album":r.push({key:t?"album":"©alb",value:Zn(a)});break;case"albumArtist":r.push({key:t?"album_artist":"aART",value:Zn(a)});break;case"comment":r.push({key:t?"comment":"©cmt",value:Zn(a)});break;case"genre":r.push({key:t?"genre":"©gen",value:Zn(a)});break;case"lyrics":r.push({key:t?"lyrics":"©lyr",value:Zn(a)});break;case"date":r.push({key:t?"date":"©day",value:Zn(a.toISOString().slice(0,10))});break;case"images":for(const e of a)"coverFront"===e.kind&&r.push({key:"covr",value:Qs("data",[zs(Gn[e.mimeType]??0),zs(0),Array.from(e.data)])});break;case"trackNumber":if(t){const t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();r.push({key:"track",value:Zn(t)})}else r.push({key:"trkn",value:Qs("data",[zs(0),zs(0),Fs(0),Fs(a),Fs(e.tracksTotal??0),Fs(0)])});break;case"discNumber":t||r.push({key:"disc",value:Qs("data",[zs(0),zs(0),Fs(0),Fs(a),Fs(e.discsTotal??0),Fs(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:B(i)}if(e.raw)for(const i in e.raw){const a=e.raw[i];null==a||!t&&4!==i.length||r.some((e=>e.key===i))||("string"==typeof a?r.push({key:i,value:Zn(a)}):a instanceof Uint8Array?r.push({key:i,value:Qs("data",[zs(0),zs(0),Array.from(a)])}):a instanceof ce&&r.push({key:i,value:Qs("data",[zs(Gn[a.mimeType]??0),zs(0),Array.from(a.data)])}))}return r},Yn=e=>{const t=Xn(e,!1);return 0===t.length?null:Ks("meta",0,0,void 0,[sn(!1,"mdir","","appl"),Qs("ilst",void 0,t.map((e=>Qs(e.key,void 0,[e.value]))))])},Jn=e=>{const t=Xn(e,!0);return 0===t.length?null:Qs("meta",void 0,[sn(!1,"mdta",""),Ks("keys",0,0,[zs(t.length)],t.map((e=>Qs("mdta",[...h.encode(e.key)])))),Qs("ilst",void 0,t.map(((e,t)=>{const r=String.fromCharCode(...zs(t+1));return Qs(r,void 0,[e.value])})))])},Zn=e=>Qs("data",[zs(1),zs(0),...h.encode(e)]),eo=(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"}},to={avc:e=>e.info.decoderConfig&&Qs("avcC",[...c(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&Qs("hvcC",[...c(e.info.decoderConfig.description)]),vp8:fn,vp9:fn,av1:e=>Qs("av1C",Pe(e.info.decoderConfig.codec))},ro=(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"}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"}},io=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return wn;case"opus":return Tn;case"flac":return Sn}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 kn}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 vn}return null},ao={webvtt:"wvtt"},so={webvtt:e=>Qs("vttC",[...h.encode(e.info.config.description)])},no=e=>{t(3===e.length);let r=0;for(let t=0;t<3;t++)r<<=5,r+=e.charCodeAt(t)-96;return r};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class oo{constructor(){this.ensureMonotonicity=!1,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1}start(){}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 r=t+e.byteLength-this.trackedStart;let i=this.trackedWrites.byteLength;for(;i<r;)i*=2;if(i!==this.trackedWrites.byteLength){const e=new Uint8Array(i);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}}const co=65536,lo=2**32;class ho extends oo{constructor(e){if(super(),this.pos=0,this.maxPos=0,this.target=e,this.supportsResize="resize"in new ArrayBuffer(0),this.supportsResize)try{this.buffer=new ArrayBuffer(co,{maxByteLength:lo})}catch{this.buffer=new ArrayBuffer(co),this.supportsResize=!1}else this.buffer=new ArrayBuffer(co);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>lo)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),r=new Uint8Array(e);r.set(this.bytes,0),this.buffer=e,this.bytes=r}}}write(e){this.maybeTrackWrites(e),this.ensureSize(this.pos+e.byteLength),this.bytes.set(e,this.pos),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.maxPos=Math.max(this.maxPos,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){}async finalize(){this.ensureSize(this.pos),this.target.buffer=this.buffer.slice(0,Math.max(this.maxPos,this.pos))}async close(){}getSlice(e,t){return this.bytes.slice(e,t)}}class uo extends oo{constructor(e){super(),this.pos=0,this.sections=[],this.lastWriteEnd=0,this.lastFlushEnd=0,this.writer=null,this.chunks=[],this.target=e,this.chunked=e._options.chunked??!1,this.chunkSize=e._options.chunkSize??16777216}start(){this.writer=this.target._writable.getWriter()}write(e){if(this.pos>this.lastWriteEnd){const e=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(e))}this.maybeTrackWrites(e),this.sections.push({data:e.slice(),start:this.pos}),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength,this.lastWriteEnd=Math.max(this.lastWriteEnd,this.pos)}seek(e){this.pos=e}getPos(){return this.pos}async flush(){if(this.pos>this.lastWriteEnd){const e=this.pos-this.lastWriteEnd;this.pos=this.lastWriteEnd,this.write(new Uint8Array(e))}if(t(this.writer),0===this.sections.length)return;const e=[],r=[...this.sections].sort(((e,t)=>e.start-t.start));e.push({start:r[0].start,size:r[0].data.byteLength});for(let t=1;t<r.length;t++){const i=e[e.length-1],a=r[t];a.start<=i.start+i.size?i.size=Math.max(i.size,a.start+a.data.byteLength-i.start):e.push({start:a.start,size:a.data.byteLength})}for(const t of e){t.data=new Uint8Array(t.size);for(const e of this.sections)t.start<=e.start&&e.start<t.start+t.size&&t.data.set(e.data,e.start-t.start);if(null!==this.writer.desiredSize&&this.writer.desiredSize<=0&&await this.writer.ready,this.chunked)this.writeDataIntoChunks(t.data,t.start),this.tryToFlushChunks();else{if(this.ensureMonotonicity&&t.start!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:t.data,position:t.start}),this.lastFlushEnd=t.start+t.data.byteLength}}this.sections.length=0}writeDataIntoChunks(e,t){let r=this.chunks.findIndex((e=>e.start<=t&&t<e.start+this.chunkSize));-1===r&&(r=this.createChunk(t));const i=this.chunks[r],a=t-i.start,s=e.subarray(0,Math.min(this.chunkSize-a,e.byteLength));i.data.set(s,a);const n={start:a,end:a+s.byteLength};if(this.insertSectionIntoChunk(i,n),0===i.written[0].start&&i.written[0].end===this.chunkSize&&(i.shouldFlush=!0),this.chunks.length>2){for(let e=0;e<this.chunks.length-1;e++)this.chunks[e].shouldFlush=!0;this.tryToFlushChunks()}s.byteLength<e.byteLength&&this.writeDataIntoChunks(e.subarray(s.byteLength),t+s.byteLength)}insertSectionIntoChunk(e,t){let r=0,i=e.written.length-1,a=-1;for(;r<=i;){const s=Math.floor(r+(i-r+1)/2);e.written[s].start<=t.start?(r=s+1,a=s):i=s-1}for(e.written.splice(a+1,0,t),(-1===a||e.written[a].end<t.start)&&a++;a<e.written.length-1&&e.written[a].end>=e.written[a+1].start;)e.written[a].end=Math.max(e.written[a].end,e.written[a+1].end),e.written.splice(a+1,1)}createChunk(e){const t={start:Math.floor(e/this.chunkSize)*this.chunkSize,data:new Uint8Array(this.chunkSize),written:[],shouldFlush:!1};return this.chunks.push(t),this.chunks.sort(((e,t)=>e.start-t.start)),this.chunks.indexOf(t)}tryToFlushChunks(e=!1){t(this.writer);for(let t=0;t<this.chunks.length;t++){const r=this.chunks[t];if(r.shouldFlush||e){for(const e of r.written){const t=r.start+e.start;if(this.ensureMonotonicity&&t!==this.lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this.writer.write({type:"write",data:r.data.subarray(e.start,e.end),position:t}),this.lastFlushEnd=r.start+e.end}this.chunks.splice(t--,1)}}}finalize(){return this.chunked&&this.tryToFlushChunks(!0),t(this.writer),this.writer.close()}async close(){return this.writer?.close()}}class mo extends oo{constructor(e){super(),this.target=e,this.pos=0}write(e){this.maybeTrackWrites(e),this.target.onwrite?.(this.pos,this.pos+e.byteLength),this.pos+=e.byteLength}getPos(){return this.pos}seek(e){this.pos=e}async flush(){}async finalize(){}async close(){}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const po=void 0!==Ua?Ua:void 0;class fo{constructor(){this._output=null,this.onwrite=null}}class go extends fo{constructor(){super(...arguments),this.buffer=null}_createWriter(){return new ho(this)}}class wo extends fo{constructor(e,t={}){if(super(),!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(null!=t&&"object"!=typeof t)throw new TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==t.chunked&&"boolean"!=typeof t.chunked)throw new TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==t.chunkSize&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t}_createWriter(){return new uo(this)}}class ko extends fo{constructor(e,r={}){if("string"!=typeof e)throw new TypeError("filePath must be a string.");if(!r||"object"!=typeof r)throw new TypeError("options must be an object.");super(),this._fileHandle=null;const i=new WritableStream({start:async()=>{this._fileHandle=await po.fs.open(e,"w")},write:async e=>{t(this._fileHandle),await this._fileHandle.write(e.data,0,e.data.byteLength,e.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new wo(i,{chunked:!0,...r}),this._streamTarget._output=this._output}_createWriter(){return this._streamTarget._createWriter()}}class bo extends fo{_createWriter(){return new mo(this)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const yo=1e3,To=e=>{const t={},r=e.track;return void 0!==r.metadata.name&&(t.name=r.metadata.name),t},So=(e,t,r=!0)=>{const i=e*t;return r?Math.round(i):i};class vo extends $e{constructor(e,t){super(e),this.auxTarget=new go,this.auxWriter=this.auxTarget._createWriter(),this.auxBoxWriter=new Is(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=I(),this.creationTime=Math.floor(Date.now()/1e3)+2082844800,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.format=t,this.writer=e._writer,this.boxWriter=new Is(this.writer),this.isQuickTime=t instanceof zo;const r=this.writer instanceof ho&&"in-memory";this.fastStart=t._options.fastStart??r,this.isFragmented="fragmented"===this.fastStart,("in-memory"===this.fastStart||this.isFragmented)&&(this.writer.ensureMonotonicity=!0),this.minimumFragmentDuration=t._options.minimumFragmentDuration??1}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some((e=>"video"===e.type&&"avc"===e.source._codec));if(this.format._options.onFtyp&&this.writer.startTrackingWrites(),this.boxWriter.writeBox((r={isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented}).isQuickTime?Qs("ftyp",[Ws("qt  "),zs(512),Ws("qt  ")]):r.fragmented?Qs("ftyp",[Ws("iso5"),zs(512),Ws("iso5"),Ws("iso6"),Ws("mp41")]):Qs("ftyp",[Ws("isom"),zs(512),Ws("isom"),r.holdsAvc?Ws("avc1"):[],Ws("mp41")])),this.format._options.onFtyp){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onFtyp(e,t)}var r;if(this.ftypSize=this.writer.getPos(),"in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(const e of this.output._tracks)if(void 0===e.metadata.maximumPacketCount)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Gs(!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=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]}));return vr({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some((e=>"video"===e.type)),hasAudio:this.trackDatas.some((e=>"audio"===e.type)),codecStrings:e})}getVideoTrackData(e,r,i){const a=this.trackDatas.find((t=>t.track===e));if(a)return a;We(i),t(i),t(i.decoderConfig);const s={...i.decoderConfig};t(void 0!==s.codedWidth),t(void 0!==s.codedHeight);let n=!1;if("avc"!==e.source._codec||s.description){if("hevc"===e.source._codec&&!s.description){const e=ct(r.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 r of e.arrays){t.push((1&r.arrayCompleteness)<<7|63&r.nalUnitType),t.push(r.nalUnits.length>>8&255),t.push(255&r.nalUnits.length);for(const e of r.nalUnits){t.push(e.length>>8&255),t.push(255&e.length);for(let r=0;r<e.length;r++)t.push(e[r])}}return new Uint8Array(t)})(e),n=!0}}else{const e=at(r.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 r=[];r.push(e.configurationVersion),r.push(e.avcProfileIndication),r.push(e.profileCompatibility),r.push(e.avcLevelIndication),r.push(252|3&e.lengthSizeMinusOne),r.push(224|31&e.sequenceParameterSets.length);for(const t of e.sequenceParameterSets){const e=t.byteLength;r.push(e>>8),r.push(255&e);for(let i=0;i<e;i++)r.push(t[i])}r.push(e.pictureParameterSets.length);for(const t of e.pictureParameterSets){const e=t.byteLength;r.push(e>>8),r.push(255&e);for(let i=0;i<e;i++)r.push(t[i])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication){t(null!==e.chromaFormat),t(null!==e.bitDepthLumaMinus8),t(null!==e.bitDepthChromaMinus8),t(null!==e.sequenceParameterSetExt),r.push(252|3&e.chromaFormat),r.push(248|7&e.bitDepthLumaMinus8),r.push(248|7&e.bitDepthChromaMinus8),r.push(e.sequenceParameterSetExt.length);for(const t of e.sequenceParameterSetExt){const e=t.byteLength;r.push(e>>8),r.push(255&e);for(let i=0;i<e;i++)r.push(t[i])}}return new Uint8Array(r)})(e),n=!0}const o=((e,t)=>{const r=e<0?-1:1;let i=0,a=1,s=1,n=0,o=e=Math.abs(e);for(;;){const e=Math.floor(o),c=e*s+i,d=e*n+a;if(d>t)return{numerator:r*s,denominator:n};if(i=s,a=n,s=c,n=d,o=1/(o-e),!isFinite(o))break}return{numerator:r*s,denominator:n}})(1/(e.metadata.frameRate??57600),1e6).denominator,c={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,decoderConfig:s,requiresAnnexBTransformation:n},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(c),this.trackDatas.sort(((e,t)=>e.track.id-t.track.id)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,r){const i=this.trackDatas.find((t=>t.track===e));if(i)return i;qe(r),t(r),t(r.decoderConfig);const a={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig,requiresPcmTransformation:!this.isFragmented&&pe.includes(e.source._codec)},timescale:r.decoderConfig.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[]};return this.trackDatas.push(a),this.trackDatas.sort(((e,t)=>e.track.id-t.track.id)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,r){const i=this.trackDatas.find((t=>t.track===e));if(i)return i;je(r),t(r),t(r.config);const a={muxer:this,track:e,type:"subtitle",info:{config:r.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId: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,r){const i=await this.mutex.acquire();try{const i=this.getVideoTrackData(e,t,r);let a=t.data;if(i.info.requiresAnnexBTransformation){const e=Xe(a);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=et(e,4)}const s=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),n=this.createSampleForTrack(i,a,s,t.duration,t.type);await this.registerSample(i,n)}finally{i()}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getAudioTrackData(e,r),a=this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type),s=this.createSampleForTrack(i,t.data,a,t.duration,t.type);i.info.requiresPcmTransformation&&await this.maybePadWithSilence(i,a),await this.registerSample(i,s)}finally{i()}}async maybePadWithSilence(e,t){const r=i(e.samples),a=r?r.timestamp+r.duration:0,s=t-a,n=So(s,e.timescale);if(n>0){const{sampleSize:t,silentValue:r}=ze(e.info.decoderConfig.codec),i=n*e.info.numberOfChannels,o=new Uint8Array(t*i).fill(r),c=this.createSampleForTrack(e,new Uint8Array(o.buffer),a,s,"key");await this.registerSample(e,c)}}async addSubtitleCue(e,t,r){const i=await this.mutex.acquire();try{const i=this.getSubtitleTrackData(e,r);this.validateAndNormalizeTimestamp(i.track,t.timestamp,!0),"webvtt"===e.source._codec&&(i.cueQueue.push(t),await this.processWebVTTCues(i,t.timestamp))}finally{i()}}async processWebVTTCues(e,r){for(;e.cueQueue.length>0;){const i=new Set([]);for(const a of e.cueQueue)t(a.timestamp<=r),t(e.lastCueEndTimestamp<=a.timestamp+a.duration),i.add(Math.max(a.timestamp,e.lastCueEndTimestamp)),i.add(a.timestamp+a.duration);const a=[...i].sort(((e,t)=>e-t)),s=a[0],n=a[1]??s;if(r<n)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);const t=Hn();this.auxBoxWriter.writeBox(t);const r=this.auxWriter.getSlice(0,this.auxWriter.getPos()),i=this.createSampleForTrack(e,r,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,i),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){const r=e.cueQueue[t];if(r.timestamp>=n)break;vs.lastIndex=0;const i=vs.test(r.text),a=r.timestamp+r.duration;let o=e.cueToSourceId.get(r);if(void 0===o&&n<a&&(o=e.nextSourceId++,e.cueToSourceId.set(r,o)),r.notes){const e=jn(r.notes);this.auxBoxWriter.writeBox(e)}const c=qn(r.text,i?s:null,r.identifier??null,r.settings??null,o??null);this.auxBoxWriter.writeBox(c),a===n&&e.cueQueue.splice(t--,1)}const o=this.auxWriter.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,r,i,a){return{timestamp:r,decodeTimestamp:r,duration:i,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:So(i,e.timescale)}}processTimestamps(e,r){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){let t=0;for(let r=0;r<e.timestampProcessingQueue.length;r++){const i=e.timestampProcessingQueue[r];t+=So(i.duration,e.timescale)}if(0===e.timeToSampleTable.length)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{i(e.timeToSampleTable).sampleCount+=t}return void(e.timestampProcessingQueue.length=0)}const a=e.timestampProcessingQueue.map((e=>e.timestamp)).sort(((e,t)=>e-t));for(let r=0;r<e.timestampProcessingQueue.length;r++){const s=e.timestampProcessingQueue[r];s.decodeTimestamp=a[r],this.isFragmented||null!==e.lastTimescaleUnits||(s.decodeTimestamp=0);const n=So(s.timestamp-s.decodeTimestamp,e.timescale),o=So(s.duration,e.timescale);if(null!==e.lastTimescaleUnits){t(e.lastSample);const r=So(s.decodeTimestamp,e.timescale,!1),a=Math.round(r-e.lastTimescaleUnits);if(t(a>=0),e.lastTimescaleUnits+=a,e.lastSample.timescaleUnitsToNextSample=a,!this.isFragmented){let r=i(e.timeToSampleTable);if(t(r),1===r.sampleCount){r.sampleDelta=a;const t=e.timeToSampleTable[e.timeToSampleTable.length-2];t&&t.sampleDelta===a&&(t.sampleCount++,e.timeToSampleTable.pop(),r=t)}else r.sampleDelta!==a&&(r.sampleCount--,e.timeToSampleTable.push(r={sampleCount:1,sampleDelta:a}));r.sampleDelta===o?r.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const s=i(e.compositionTimeOffsetTable);t(s),s.sampleCompositionTimeOffset===n?s.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else e.lastTimescaleUnits=So(s.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));e.lastSample=s}if(e.timestampProcessingQueue.length=0,t(e.lastSample),t(null!==e.lastTimescaleUnits),void 0!==r&&0===e.lastSample.timescaleUnitsToNextSample){t("key"===r.type);const i=So(r.timestamp,e.timescale,!1),a=Math.round(i-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,r){if(!this.isFragmented&&(e.samples.push(r),"reserve"===this.fastStart)){const r=e.track.metadata.maximumPacketCount;if(t(void 0!==r),e.samples.length>r)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${r}). Either add less packets or increase the maximum packet count.`)}let i=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,r.timestamp);const t=r.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const a=this.trackDatas.every((t=>{if(e===t)return"key"===r.type;const i=t.sampleQueue[0];return i?"key"===i.type:t.track.source._closed}));t>=this.minimumFragmentDuration&&a&&r.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=t>=.5}else i=!0;i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:r.timestamp,samples:[],offset:null,moofOffset:null}),t(e.currentChunk),e.currentChunk.samples.push(r),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,r.timestamp))}async finalizeCurrentChunk(e){if(t(!this.isFragmented),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let r=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(r=e.currentChunk.samples.reduce(((t,r)=>t+So(r.duration,e.timescale)),0)),0!==e.compactlyCodedChunkTable.length&&i(e.compactlyCodedChunkTable).samplesPerChunk===r||e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:r}),"in-memory"!==this.fastStart){e.currentChunk.offset=this.writer.getPos();for(const r of e.currentChunk.samples)t(r.data),this.writer.write(r.data),r.data=null;await this.writer.flush()}else e.currentChunk.offset=0}async interleaveSamples(e=!1){if(t(this.isFragmented),e||this.allTracksAreKnown())e:for(;;){let t=null,r=1/0;for(const i of this.trackDatas){if(!e&&0===i.sampleQueue.length&&!i.track.source._closed)break e;i.sampleQueue.length>0&&i.sampleQueue[0].timestamp<r&&(t=i,r=i.sampleQueue[0].timestamp)}if(!t)break;const i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!0){t(this.isFragmented);const r=this.nextFragmentNumber++;if(1===r){this.format._options.onMoov&&this.writer.startTrackingWrites();const e=Xs(this);if(this.boxWriter.writeBox(e),this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}const i=this.trackDatas.filter((e=>e.currentChunk)),a=Dn(r,i),s=this.writer.getPos(),n=s+this.boxWriter.measureBox(a);let o=n+8,c=1/0;for(const e of i){e.currentChunk.offset=o,e.currentChunk.moofOffset=s;for(const t of e.currentChunk.samples)o+=t.size;c=Math.min(c,e.currentChunk.startTimestamp)}const d=o-n,l=d>=2**32;if(l)for(const e of i)e.currentChunk.offset+=8;this.format._options.onMoof&&this.writer.startTrackingWrites();const h=Dn(r,i);if(this.boxWriter.writeBox(h),this.format._options.onMoof){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoof(e,t,c)}t(this.writer.getPos()===n),this.format._options.onMdat&&this.writer.startTrackingWrites();const u=Gs(l);u.size=d,this.boxWriter.writeBox(u),this.writer.seek(n+(l?Cr:8));for(const e of i)for(const t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.format._options.onMdat){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMdat(e,t)}for(const e of i)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,r){if(this.allTracksAreKnown()){if(!this.mdat){const e=Xs(this),r=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;t(null!==this.ftypSize),this.writer.seek(this.ftypSize+r),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Gs(!0),this.boxWriter.writeBox(this.mdat);for(const e of this.trackDatas){for(const t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}await this.addSampleToTrack(e,r)}else e.sampleQueue.push(r)}computeSampleTableSizeUpperBound(){t("reserve"===this.fastStart);let e=0;for(const r of this.trackDatas){const i=r.track.metadata.maximumPacketCount;t(void 0!==i),e+=8*Math.ceil(2/3*i),e+=4*i,e+=8*Math.ceil(2/3*i),e+=12*Math.ceil(2/3*i),e+=4*i,e+=8*i}return e}async onTrackClose(e){const t=await this.mutex.acquire();if("subtitle"===e.type&&"webvtt"===e.source._codec){const t=this.trackDatas.find((t=>t.track===e));t&&await this.processWebVTTCues(t,1/0)}this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const e of this.trackDatas)"subtitle"===e.type&&"webvtt"===e.track.source._codec&&await this.processWebVTTCues(e,1/0);if(this.isFragmented){await this.interleaveSamples(!0);for(const e of this.trackDatas)this.processTimestamps(e);await this.finalizeFragment(!1)}else for(const e of this.trackDatas)this.processTimestamps(e),await this.finalizeCurrentChunk(e);if("in-memory"===this.fastStart){let e;this.mdat=Gs(!1);for(let r=0;r<2;r++){const r=Xs(this),i=this.boxWriter.measureBox(r);e=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+i+e;for(const r of this.finalizedChunks){r.offset=a;for(const{data:i}of r.samples)t(i),a+=i.byteLength,e+=i.byteLength}if(a<2**32)break;e>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const r=Xs(this);if(this.boxWriter.writeBox(r),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 e of this.finalizedChunks)for(const r of e.samples)t(r.data),this.writer.write(r.data),r.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){const e=this.writer.getPos(),t=(r=this.trackDatas,Qs("mfra",void 0,[...r.map(Ln),Wn()]));this.boxWriter.writeBox(t);const i=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{t(this.mdat);const e=this.boxWriter.offsets.get(this.mdat);t(void 0!==e);const r=this.writer.getPos()-e;if(this.mdat.size=r,this.mdat.largeSize=r>=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 i=Xs(this);if("reserve"===this.fastStart){t(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);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(i);if(this.format._options.onMoov){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onMoov(e,t)}}var r;e()}}const Co="Mediabunny",xo={video:1,audio:2,subtitle:17};class Po extends $e{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=I(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.duration=0,this.writer=e._writer,this.format=t,this.ebmlWriter=new Zr(this.writer),this.format._options.appendOnly&&(this.writer.ensureMonotonicity=!0)}async start(){const e=await this.mutex.acquire();this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:$r.EBML,data:[{id:$r.EBMLVersion,data:1},{id:$r.EBMLReadVersion,data:1},{id:$r.EBMLMaxIDLength,data:4},{id:$r.EBMLMaxSizeLength,data:8},{id:$r.DocType,data:this.format instanceof Oo?"webm":"matroska"},{id:$r.DocTypeVersion,data:2},{id:$r.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),i=new Uint8Array([22,84,174,107]),a=new Uint8Array([25,65,164,105]),s=new Uint8Array([18,84,195,103]),n={id:$r.SeekHead,data:[{id:$r.Seek,data:[{id:$r.SeekID,data:t},{id:$r.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:$r.Seek,data:[{id:$r.SeekID,data:r},{id:$r.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:$r.Seek,data:[{id:$r.SeekID,data:i},{id:$r.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:$r.Seek,data:[{id:$r.SeekID,data:a},{id:$r.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:$r.Seek,data:[{id:$r.SeekID,data:s},{id:$r.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=n}createSegmentInfo(){const e={id:$r.Duration,data:new Hr(0)};this.segmentDuration=e;const t={id:$r.Info,data:[{id:$r.TimestampScale,data:1e6},{id:$r.MuxingApp,data:Co},{id:$r.WritingApp,data:Co},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){const e={id:$r.Tracks,data:[]};this.tracksElement=e;for(const r of this.trackDatas){const i=ui[r.track.source._codec];t(i);let a=0;if("audio"===r.type&&"opus"===r.track.source._codec){a=8e7;const e=r.info.decoderConfig.description;if(e){const t=c(e),r=bt(t);a=Math.round(r.preSkip/Me*1e9)}}e.data.push({id:$r.TrackEntry,data:[{id:$r.TrackNumber,data:r.track.id},{id:$r.TrackUID,data:r.track.id},{id:$r.TrackType,data:xo[r.type]},!1===r.track.metadata.disposition?.default?{id:$r.FlagDefault,data:0}:null,r.track.metadata.disposition?.forced?{id:$r.FlagForced,data:1}:null,r.track.metadata.disposition?.hearingImpaired?{id:$r.FlagHearingImpaired,data:1}:null,r.track.metadata.disposition?.visuallyImpaired?{id:$r.FlagVisualImpaired,data:1}:null,r.track.metadata.disposition?.original?{id:$r.FlagOriginal,data:1}:null,r.track.metadata.disposition?.commentary?{id:$r.FlagCommentary,data:1}:null,{id:$r.FlagLacing,data:0},{id:$r.Language,data:r.track.metadata.languageCode??R},{id:$r.CodecID,data:i},{id:$r.CodecDelay,data:0},{id:$r.SeekPreRoll,data:a},void 0!==r.track.metadata.name?{id:$r.Name,data:new jr(r.track.metadata.name)}:null,"video"===r.type?this.videoSpecificTrackInfo(r):null,"audio"===r.type?this.audioSpecificTrackInfo(r):null,"subtitle"===r.type?this.subtitleSpecificTrackInfo(r):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:i}=e.track.metadata,a=[e.info.decoderConfig.description?{id:$r.CodecPrivate,data:c(e.info.decoderConfig.description)}:null,t?{id:$r.DefaultDuration,data:1e9/t}:null],s=i?r(-i):0,n=e.info.decoderConfig.colorSpace,o={id:$r.Video,data:[{id:$r.PixelWidth,data:e.info.width},{id:$r.PixelHeight,data:e.info.height},e.info.alphaMode?{id:$r.AlphaMode,data:1}:null,y(n)?{id:$r.Colour,data:[{id:$r.MatrixCoefficients,data:k[n.matrix]},{id:$r.TransferCharacteristics,data:g[n.transfer]},{id:$r.Primaries,data:p[n.primaries]},{id:$r.Range,data:n.fullRange?2:1}]}:null,s?{id:$r.Projection,data:[{id:$r.ProjectionType,data:0},{id:$r.ProjectionPoseRoll,data:new Wr((s+180)%360-180)}]}:null]};return a.push(o),a}audioSpecificTrackInfo(e){const t=pe.includes(e.track.source._codec)?ze(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:$r.CodecPrivate,data:c(e.info.decoderConfig.description)}:null,{id:$r.Audio,data:[{id:$r.SamplingFrequency,data:new Wr(e.info.sampleRate)},{id:$r.Channels,data:e.info.numberOfChannels},t?{id:$r.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:$r.CodecPrivate,data:h.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(t,r)=>{e.push({id:$r.SimpleTag,data:[{id:$r.TagName,data:new jr(t)},"string"==typeof r?{id:$r.TagString,data:new jr(r)}:{id:$r.TagBinary,data:r}]})},r=this.output._metadataTags,i=new Set;for(const{key:e,value:a}of te(r))switch(e){case"title":t("TITLE",a),i.add("TITLE");break;case"description":t("DESCRIPTION",a),i.add("DESCRIPTION");break;case"artist":t("ARTIST",a),i.add("ARTIST");break;case"album":t("ALBUM",a),i.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),i.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),i.add("GENRE");break;case"comment":t("COMMENT",a),i.add("COMMENT");break;case"lyrics":t("LYRICS",a),i.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),i.add("DATE");break;case"trackNumber":t("PART_NUMBER",void 0!==r.tracksTotal?`${a}/${r.tracksTotal}`:a.toString()),i.add("PART_NUMBER");break;case"discNumber":t("DISC",void 0!==r.discsTotal?`${a}/${r.discsTotal}`:a.toString()),i.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:B(e)}if(r.raw)for(const e in r.raw){const a=r.raw[e];null==a||i.has(e)||("string"==typeof a||a instanceof Uint8Array)&&t(e,a)}0!==e.length&&(this.tagsElement={id:$r.Tags,data:[{id:$r.Tag,data:[{id:$r.Targets,data:[{id:$r.TargetTypeValue,data:50},{id:$r.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],r=new Set,i=e.images??[];for(const e of i){let i,a=e.name;if(void 0===a){a=("coverFront"===e.kind?"cover":"coverBack"===e.kind?"back":"image")+(re(e.mimeType)??"")}for(;;){i=0n;for(let e=0;e<8;e++)i<<=8n,i|=BigInt(Math.floor(256*Math.random()));if(0n!==i&&!r.has(i))break}r.add(i),t.push({id:$r.AttachedFile,data:[void 0!==e.description?{id:$r.FileDescription,data:new jr(e.description)}:null,{id:$r.FileName,data:new jr(a)},{id:$r.FileMediaType,data:e.mimeType},{id:$r.FileData,data:e.data},{id:$r.FileUID,data:i}]})}for(const[r,a]of Object.entries(e.raw??{})){if(!(a instanceof de))continue;/^\d+$/.test(r)&&(i.find((e=>e.mimeType===a.mimeType&&se(e.data,a.data)))||t.push({id:$r.AttachedFile,data:[void 0!==a.description?{id:$r.FileDescription,data:new jr(a.description)}:null,{id:$r.FileName,data:new jr(a.name??"")},{id:$r.FileMediaType,data:a.mimeType??""},{id:$r.FileData,data:a.data},{id:$r.FileUID,data:BigInt(r)}]}))}0!==t.length&&(this.attachmentsElement={id:$r.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:$r.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:$r.Cues,data:[]}}get segmentDataOffset(){return t(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some((t=>t.track===e)))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map((e=>{if("video"===e.type)return e.info.decoderConfig.codec;if("audio"===e.type)return e.info.decoderConfig.codec;return{webvtt:"wvtt"}[e.track.source._codec]}));return pi({isWebM:this.format instanceof Oo,hasVideo:this.trackDatas.some((e=>"video"===e.type)),hasAudio:this.trackDatas.some((e=>"audio"===e.type)),codecStrings:e})}getVideoTrackData(e,r,i){const a=this.trackDatas.find((t=>t.track===e));if(a)return a;We(i),t(i),t(i.decoderConfig),t(void 0!==i.decoderConfig.codedWidth),t(void 0!==i.decoderConfig.codedHeight);const s={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,decoderConfig:i.decoderConfig,alphaMode:!!r.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null};return"vp9"===e.source._codec?s.info.decoderConfig={...s.info.decoderConfig,description:new Uint8Array(xe(s.info.decoderConfig.codec))}:"av1"===e.source._codec&&(s.info.decoderConfig={...s.info.decoderConfig,description:new Uint8Array(Pe(s.info.decoderConfig.codec))}),this.trackDatas.push(s),this.trackDatas.sort(((e,t)=>e.track.id-t.track.id)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getAudioTrackData(e,r){const i=this.trackDatas.find((t=>t.track===e));if(i)return i;qe(r),t(r),t(r.decoderConfig);const a={track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:r.decoderConfig},chunkQueue:[],lastWrittenMsTimestamp:null};return this.trackDatas.push(a),this.trackDatas.sort(((e,t)=>e.track.id-t.track.id)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}getSubtitleTrackData(e,r){const i=this.trackDatas.find((t=>t.track===e));if(i)return i;je(r),t(r),t(r.config);const a={track:e,type:"subtitle",info:{config:r.config},chunkQueue:[],lastWrittenMsTimestamp:null};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,r){const i=await this.mutex.acquire();try{const i=this.getVideoTrackData(e,t,r),a="key"===t.type;let s=this.validateAndNormalizeTimestamp(i.track,t.timestamp,a),n=t.duration;void 0!==e.metadata.frameRate&&(s=U(s,1/e.metadata.frameRate),n=U(n,1/e.metadata.frameRate));const o=i.info.alphaMode?t.sideData.alpha??null:null,c=this.createInternalChunk(t.data,s,n,t.type,o);"vp9"===e.source._codec&&this.fixVP9ColorSpace(i,c),i.chunkQueue.push(c),await this.interleaveChunks()}finally{i()}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getAudioTrackData(e,r),a="key"===t.type,s=this.validateAndNormalizeTimestamp(i.track,t.timestamp,a),n=this.createInternalChunk(t.data,s,t.duration,t.type);i.chunkQueue.push(n),await this.interleaveChunks()}finally{i()}}async addSubtitleCue(e,t,r){const i=await this.mutex.acquire();try{const i=this.getSubtitleTrackData(e,r),a=this.validateAndNormalizeTimestamp(i.track,t.timestamp,!0);let s=t.text;const n=Math.round(1e3*a);vs.lastIndex=0,s=s.replace(vs,(e=>{const t=Ps(e.slice(1,-1));return`<${_s(t-n)}>`}));const o=h.encode(s),c=`${t.settings??""}\n${t.identifier??""}\n${t.notes??""}`,d=this.createInternalChunk(o,a,t.duration,"key",c.trim()?h.encode(c):null);i.chunkQueue.push(d),await this.interleaveChunks()}finally{i()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){e:for(;;){let t=null,r=1/0;for(const i of this.trackDatas){if(!e&&0===i.chunkQueue.length&&!i.track.source._closed)break e;i.chunkQueue.length>0&&i.chunkQueue[0].timestamp<r&&(t=i,r=i.chunkQueue[0].timestamp)}if(!t)break;const i=t.chunkQueue.shift();this.writeBlock(t,i)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if("key"!==t.type)return;if(!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const r=new s(t.data);r.skipBits(2);const i=r.readBits(1),a=(r.readBits(1)<<1)+i;3===a&&r.skipBits(1);if(r.readBits(1))return;if(0!==r.readBits(1))return;r.skipBits(2);if(4817730!==r.readBits(24))return;a>=2&&r.skipBits(1);const n={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];((e,t,r,i)=>{for(let a=t;a<r;a++){const t=Math.floor(a/8);let s=e[t];const n=7-(7&a);s&=~(1<<n),s|=(i&1<<r-a-1)>>r-a-1<<n,e[t]=s}})(t.data,r.pos,r.pos+3,n)}createInternalChunk(e,t,r,i,a=null){return{data:e,type:i,timestamp:t,duration:r,additions:a}}writeBlock(e,r){this.segment||this.createSegment();const i=Math.round(1e3*r.timestamp),a=this.trackDatas.every((t=>{if(e===t)return"key"===r.type;const i=t.chunkQueue[0];return i?"key"===i.type:t.track.source._closed}));let s=!1;if(this.currentCluster){t(null!==this.currentClusterStartMsTimestamp),t(null!==this.currentClusterMaxMsTimestamp);const e=i-this.currentClusterStartMsTimestamp;s=a&&i>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>32767}else s=!0;s&&this.createNewCluster(i);const n=i-this.currentClusterStartMsTimestamp;if(n<-32768)return;const o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,n,!1);const d=Math.round(1e3*r.duration);if(r.additions){const t={id:$r.BlockGroup,data:[{id:$r.Block,data:[o,r.data]},"delta"===r.type?{id:$r.ReferenceBlock,data:new qr(e.lastWrittenMsTimestamp-i)}:null,r.additions?{id:$r.BlockAdditions,data:[{id:$r.BlockMore,data:[{id:$r.BlockAddID,data:1},{id:$r.BlockAdditional,data:r.additions}]}]}:null,d>0?{id:$r.BlockDuration,data:d}:null]};this.ebmlWriter.writeEBML(t)}else{c.setUint8(3,Number("key"===r.type)<<7);const e={id:$r.SimpleBlock,data:[o,r.data]};this.ebmlWriter.writeEBML(e)}this.duration=Math.max(this.duration,i+d),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:$r.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:$r.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(t(this.currentCluster),!this.format._options.appendOnly){const e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){t(null!==this.currentClusterStartMsTimestamp);const{data:e,start:r}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,r,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,r=new Map;for(const[e,{firstMsTimestamp:t}]of this.trackDatasInCurrentCluster)r.has(t)||r.set(t,[]),r.get(t).push(e);const i=[...r.entries()].sort(((e,t)=>e[0]-t[0]));for(const[r,a]of i)t(this.cues),this.cues.data.push({id:$r.CuePoint,data:[{id:$r.CueTime,data:r},...a.map((t=>({id:$r.CueTrackPositions,data:[{id:$r.CueTrack,data:t.track.id},{id:$r.CueClusterPosition,data:e}]})))]})}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),e()}async finalize(){const e=await this.mutex.acquire();if(this.allTracksKnown.resolve(),this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),t(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const e=this.writer.getPos(),r=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(r,6),this.segmentDuration.data=new Hr(this.duration),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),t(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead),this.writer.seek(e)}e()}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class _o{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){const t=this.writer.getPos(),r=224|e.mpegVersionId<<3|e.layer<<1;let i;i=2&e.mpegVersionId&&1&e.mpegVersionId?0:1;let a=-1;const s=16*i*4+16*e.layer;for(let t=0;t<16;t++){const r=xi[s+t];if(Ii(i,e.layer,1e3*r,e.sampleRate,0)>=155){a=t;break}}if(-1===a)throw new Error("No suitable bitrate found.");const n=a<<4|e.frequencyIndex<<2,o=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=255,this.helper[1]=r,this.helper[2]=n,this.helper[3]=o,this.writer.write(this.helper.subarray(0,4));const c=Ei(e.mpegVersionId,e.channel);this.writer.seek(t+c),this.writeU32(Pi);let d=0;null!==e.frameCount&&(d|=1),null!==e.fileSize&&(d|=2),null!==e.toc&&(d|=4),this.writeU32(d),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));const l=xi[s+a],h=Ii(i,e.layer,1e3*l,e.sampleRate,0);this.writer.seek(t+h)}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Io extends $e{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t,this.writer=e._writer,this.mp3Writer=new _o(e._writer)}async start(){if(!he(this.output._metadataTags)){new Vi(this.writer).writeId3V2Tag(this.output._metadataTags)}}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){const r=await this.mutex.acquire();try{const r=!1!==this.format._options.xingHeader;if(!this.xingFrameData&&r){const e=d(t.data);if(e.byteLength<4)throw new Error("Invalid MP3 header in sample.");const r=e.getUint32(0,!1),i=Ai(r,null).header;if(!i)throw new Error("Invalid MP3 header in sample.");const a=Ei(i.mpegVersionId,i.channel);if(e.byteLength>=a+4){const t=e.getUint32(a,!1);if(t===Pi||t===_i)return}this.xingFrameData={mpegVersionId:i.mpegVersionId,layer:i.layer,frequencyIndex:i.frequencyIndex,sampleRate:i.sampleRate,channel:i.channel,modeExtension:i.modeExtension,copyright:i.copyright,original:i.original,emphasis:i.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateAndNormalizeTimestamp(e,t.timestamp,"key"===t.type),this.writer.write(t.data),this.frameCount++,await this.writer.flush(),r&&this.framePositions.push(this.writer.getPos())}finally{r()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||null===this.xingFramePos)return;const e=await this.mutex.acquire(),r=this.writer.getPos();this.writer.seek(this.xingFramePos);const i=new Uint8Array(100);for(let e=0;e<100;e++){const a=Math.floor(this.framePositions.length*(e/100));t(-1!==a&&a<this.framePositions.length);const s=this.framePositions[a];i[e]=s/r*256}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=r,this.xingFrameData.toc=i,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(e,t)}this.writer.seek(r),e()}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Eo extends $e{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=I(),this.pageBytes=new Uint8Array(65307),this.pageView=new DataView(this.pageBytes.buffer),this.format=t,this.writer=e._writer,this.writer.ensureMonotonicity=!0}async start(){}async getMimeType(){return await this.allTracksKnown.promise,Ki({codecStrings:this.trackDatas.map((e=>e.codecInfo.codec))})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,r){const i=this.trackDatas.find((t=>t.track===e));if(i)return i;let a;do{a=Math.floor(2**32*Math.random())}while(this.trackDatas.some((e=>e.serialNumber===a)));t("vorbis"===e.source._codec||"opus"===e.source._codec),qe(r),t(r),t(r.decoderConfig);const s={track:e,serialNumber:a,internalSampleRate:"opus"===e.source._codec?Me:r.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0};return this.queueHeaderPackets(s,r),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,r){if(t(r.decoderConfig),"vorbis"===e.track.source._codec){t(r.decoderConfig.description);const i=c(r.decoderConfig.description);if(2!==i[0])throw new TypeError("First byte of Vorbis decoder description must be 2.");let a=1;const s=()=>{let e=0;for(;;){const t=i[a++];if(void 0===t)throw new TypeError("Vorbis decoder description is too short.");if(e+=t,t<255)return e}},n=s(),o=s();if(i.length-a<=0)throw new TypeError("Vorbis decoder description is too short.");const l=i.subarray(a,a+=n);a+=o;const h=i.subarray(a),u=new Uint8Array(7);u[0]=3,u[1]=118,u[2]=111,u[3]=114,u[4]=98,u[5]=105,u[6]=115;const m=xt(u,this.output._metadataTags,!0);e.packetQueue.push({data:l,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:m,endGranulePosition:0,timestamp:0,forcePageFlush:!1},{data:h,endGranulePosition:0,timestamp:0,forcePageFlush:!0});const p=d(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(15&p),1<<(p>>4)],modeBlockflags:Tt(h).modeBlockflags}}else if("opus"===e.track.source._codec){if(!r.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const t=c(r.decoderConfig.description),i=new Uint8Array(8),a=d(i);a.setUint32(0,1332770163,!1),a.setUint32(4,1415669619,!1);const s=xt(i,this.output._metadataTags,!0);e.packetQueue.push({data:t,endGranulePosition:0,timestamp:0,forcePageFlush:!0},{data:s,endGranulePosition:0,timestamp:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:bt(t).preSkip}}}async addEncodedAudioPacket(e,t,r){const i=await this.mutex.acquire();try{const i=this.getTrackData(e,r);this.validateAndNormalizeTimestamp(i.track,t.timestamp,"key"===t.type);const a=i.currentTimestampInSamples,{durationInSamples:s,vorbisBlockSize:n}=Qi(t.data,i.codecInfo,i.vorbisLastBlocksize);i.currentTimestampInSamples+=s,i.vorbisLastBlocksize=n,i.packetQueue.push({data:t.data,endGranulePosition:i.currentTimestampInSamples,timestamp:a/i.internalSampleRate,forcePageFlush:!1}),await this.interleavePages()}finally{i()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some((t=>t.track===e)))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown())return;for(const e of this.trackDatas)for(;e.packetQueue.length>0;){const t=e.packetQueue.shift();if(this.writePacket(e,t,!1),t.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let t=null,r=1/0;for(const i of this.trackDatas){if(!e&&i.packetQueue.length<=1&&!i.track.source._closed)break e;i.packetQueue.length>0&&i.packetQueue[0].timestamp<r&&(t=i,r=i.packetQueue[0].timestamp)}if(!t)break;const i=t.packetQueue.shift(),a=0===t.packetQueue.length;this.writePacket(t,i,a)}e||await this.writer.flush()}writePacket(e,t,r){let i=t.data.length,a=0,s=0;for(;;){0===e.currentLacingValues.length&&a>0&&(e.currentPageStartsWithFreshPacket=!1);const n=Math.min(255,i);e.currentLacingValues.push(n),e.currentPageSize++,s+=n;const o=i<255;if(255===e.currentLacingValues.length){const i=t.data.subarray(a,s);if(a=s,e.currentPageData.push(i),e.currentPageSize+=i.length,this.writePage(e,r&&o),o)return}if(o)break;i-=255}const n=t.data.subarray(a);e.currentPageData.push(n),e.currentPageSize+=n.length,e.currentGranulePosition=t.endGranulePosition,(e.currentPageSize>=8192||t.forcePageFlush)&&this.writePage(e,r)}writePage(e,t){this.pageView.setUint32(0,qi,!0),this.pageView.setUint8(4,0);let r=0;e.currentPageStartsWithFreshPacket||(r|=1),0===e.pagesWritten&&(r|=2),t&&(r|=4),this.pageView.setUint8(5,r);const i=e.currentLacingValues.every((e=>255===e))?-1:e.currentGranulePosition;((e,t,r,i)=>{i?(e.setUint32(t+0,r,!0),e.setInt32(t+4,Math.floor(r/2**32),!0)):(e.setInt32(t+0,Math.floor(r/2**32),!0),e.setUint32(t+4,r,!0))})(this.pageView,6,i,!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let a=27+e.currentLacingValues.length;for(const t of e.currentPageData)this.pageBytes.set(t,a),a+=t.length;const s=this.pageBytes.subarray(0,a),n=$i(s);if(this.pageView.setUint32(22,n,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(s),this.format._options.onPage){const{data:t,start:r}=this.writer.stopTrackingWrites();this.format._options.onPage(t,r,e.track.source)}}async onTrackClose(){const e=await this.mutex.acquire();this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),e()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve(),await this.interleavePages(!0);for(const e of this.trackDatas)e.currentLacingValues.length>0&&this.writePage(e,!0);e()}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Ao{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/2**32),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write((new TextEncoder).encode(e))}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Bo extends $e{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.writer=e._writer,this.riffWriter=new Ao(e._writer),this.isRf64=!!t._options.large}async start(){}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,r,i){const a=await this.mutex.acquire();try{if(this.headerWritten||(qe(i),t(i),t(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateAndNormalizeTimestamp(e,r.timestamp,"key"===r.type),!this.isRf64&&this.writer.getPos()+r.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(r.data),this.dataSize+=r.data.byteLength,this.sampleCount+=Math.round(r.duration*this.sampleRate),await this.writer.flush()}finally{a()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){let r;this.format._options.onHeader&&this.writer.startTrackingWrites();const i=e.source._codec,a=ze(i);r="ulaw"===a.dataType?ia.MULAW:"alaw"===a.dataType?ia.ALAW:"float"===a.dataType?ia.IEEE_FLOAT:ia.PCM;const s=t.numberOfChannels,n=t.sampleRate,o=a.sampleSize*s;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(r),this.riffWriter.writeU16(s),this.riffWriter.writeU32(n),this.riffWriter.writeU32(n*o),this.riffWriter.writeU16(o),this.riffWriter.writeU16(8*a.sampleSize),!he(this.output._metadataTags)){const e=this.format._options.metadataFormat??"info";"info"===e?this.writeInfoChunk(this.output._metadataTags):"id3"===e?this.writeId3Chunk(this.output._metadataTags):B(e)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){const{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onHeader(e,t)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const r=new Set,i=(e,t)=>{if(!u(t))return void console.warn(`Didn't write tag '${e}' because '${t}' is not ISO 8859-1-compatible.`);const i=t.length+1,a=new Uint8Array(i);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e);this.riffWriter.writeAscii(e),this.riffWriter.writeU32(i),this.writer.write(a),1&i&&this.writer.write(new Uint8Array(1)),r.add(e)};for(const{key:t,value:a}of te(e))switch(t){case"title":i("INAM",a),r.add("INAM");break;case"artist":i("IART",a),r.add("IART");break;case"album":i("IPRD",a),r.add("IPRD");break;case"trackNumber":i("ITRK",void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString()),r.add("ITRK");break;case"genre":i("IGNR",a),r.add("IGNR");break;case"date":i("ICRD",a.toISOString().slice(0,10)),r.add("ICRD");break;case"comment":i("ICMT",a),r.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":case"raw":break;default:B(t)}if(e.raw)for(const t in e.raw){const a=e.raw[t];null==a||4!==t.length||r.has(t)||"string"==typeof a&&i(t,a)}const a=this.writer.getPos(),s=a-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(s),this.writer.seek(a),1&s&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);const r=new Vi(this.writer).writeId3V2Tag(e),i=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(r),this.writer.seek(i),1&r&&this.writer.write(new Uint8Array(1))}async finalize(){const e=await this.mutex.acquire(),r=this.writer.getPos();this.isRf64?(t(null!==this.ds64RiffSizePos),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(r-8),t(null!==this.ds64DataSizePos),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),t(null!==this.ds64SampleCountPos),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(t(null!==this.riffSizePos),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(r-8),t(null!==this.dataSizePos),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),this.writer.seek(r),e()}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */class Fo{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter((e=>me.includes(e)))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter((e=>ge.includes(e)))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter((e=>we.includes(e)))}_codecUnsupportedHint(e){return""}}class Mo extends Fo{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(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:2**32-1}}}get supportsVideoRotationMetadata(){return!0}_createMuxer(e){return new vo(e,this)}}class Do extends Mo{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...me,...fe,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...we]}_codecUnsupportedHint(e){return(new zo).getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class zo extends Mo{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...me,...ge]}_codecUnsupportedHint(e){return(new Do).getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class Ro extends Fo{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.appendOnly&&"boolean"!=typeof e.appendOnly)throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==e.minimumClusterDuration&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==e.onEbmlHeader&&"function"!=typeof e.onEbmlHeader)throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==e.onSegmentHeader&&"function"!=typeof e.onSegmentHeader)throw new TypeError("options.onHeader, when provided, must be a function.");if(void 0!==e.onCluster&&"function"!=typeof e.onCluster)throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Po(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:1/0},audio:{min:0,max:1/0},subtitle:{min:0,max:1/0},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...me,...fe,...pe.filter((e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e))),...we]}get supportsVideoRotationMetadata(){return!1}}class Oo extends Ro{constructor(e){super(e)}getSupportedCodecs(){return[...me.filter((e=>["vp8","vp9","av1"].includes(e))),...ge.filter((e=>["opus","vorbis"].includes(e))),...we]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return(new Ro).getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class Uo extends Fo{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.xingHeader&&"boolean"!=typeof e.xingHeader)throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(void 0!==e.onXingFrame&&"function"!=typeof e.onXingFrame)throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Io(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}}class No extends Fo{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.large&&"boolean"!=typeof e.large)throw new TypeError("options.large, when provided, must be a boolean.");if(void 0!==e.metadataFormat&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(void 0!==e.onHeader&&"function"!=typeof e.onHeader)throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Bo(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...pe.filter((e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-u8","ulaw","alaw"].includes(e)))]}get supportsVideoRotationMetadata(){return!1}}class Vo extends Fo{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.onPage&&"function"!=typeof e.onPage)throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Eo(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:1/0},subtitle:{min:0,max:0},total:{min:1,max:2**32}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...ge.filter((e=>["vorbis","opus"].includes(e)))]}get supportsVideoRotationMetadata(){return!1}}class Lo extends Fo{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(void 0!==e.onFrame&&"function"!=typeof e.onFrame)throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Qe(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoRotationMetadata(){return!1}}class Wo extends Fo{constructor(e={}){if(!e||"object"!=typeof e)throw new TypeError("options must be an object.");super(),this._options=e}_createMuxer(e){return new ys(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoRotationMetadata(){return!1}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const Ho=e=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding config must be an object.");if(!me.includes(e.codec))throw new TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${me.join(", ")}.`);if(!(e.bitrate instanceof Go)&&(!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.onEncodedPacket&&"function"!=typeof e.onEncodedPacket)throw new TypeError("config.onEncodedChunk, 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.");qo(e.codec,e)},qo=(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&&Re(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.")},jo=e=>{const t=e.bitrate instanceof Go?e.bitrate._toVideoBitrate(e.codec,e.width,e.height):e.bitrate;return{codec:e.fullCodecString??Ce(e.codec,e.width,e.height,t),width:e.width,height:e.height,bitrate:t,bitrateMode:e.bitrateMode,alpha:e.alpha??"discard",framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...(r=e.codec,"avc"===r?{avc:{format:"avc"}}:"hevc"===r?{hevc:{format:"hevc"}}:{})};var r},$o=e=>{if(!e||"object"!=typeof e)throw new TypeError("Encoding config must be an object.");if(!ge.includes(e.codec))throw new TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${ge.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 Go)&&(!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.onEncodedPacket&&"function"!=typeof e.onEncodedPacket)throw new TypeError("config.onEncodedChunk, 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.");Qo(e.codec,e)},Qo=(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&&Re(t.fullCodecString)!==e)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},Ko=e=>{const t=e.bitrate instanceof Go?e.bitrate._toAudioBitrate(e.codec):e.bitrate;return{codec:e.fullCodecString??Ie(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:t,bitrateMode:e.bitrateMode,...(r=e.codec,"aac"===r?{aac:{format:"aac"}}:"opus"===r?{opus:{format:"opus"}}:{})};var r};class Go{constructor(e){this._factor=e}_toVideoBitrate(e,t,r){const i=t*r,a=3e6*Math.pow(i/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}[e];if(!t)throw new Error(`Unhandled codec: ${e}`);let r=t*this._factor;if("aac"===e){r=[96e3,128e3,16e4,192e3].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e))}else if("opus"===e||"vorbis"===e)r=Math.max(6e3,r);else if("mp3"===e){r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce(((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e))}return 1e3*Math.round(r/1e3)}}const Xo=new Go(.3),Yo=new Go(.6),Jo=new Go(1),Zo=new Go(2),ec=new Go(4),tc=e=>{if(me.includes(e))return rc(e);if(ge.includes(e))return ic(e);if(we.includes(e))return ac(e);throw new TypeError(`Unknown codec '${e}'.`)},rc=async(e,t={})=>{const{width:r=1280,height:i=720,bitrate:a=1e6,...s}=t;if(!me.includes(e))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("height must be a positive integer.");if(!(a instanceof Go)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer or a quality.");qo(e,s);let n=null;if(Mt.length>0&&(n??=jo({codec:e,width:r,height:i,bitrate:a,framerate:void 0,...s}),Mt.some((t=>t.supports(e,n)))))return!0;if("undefined"==typeof VideoEncoder)return!1;if((r%2==1||i%2==1)&&("avc"===e||"hevc"===e))return!1;n??=jo({codec:e,width:r,height:i,bitrate:a,framerate:void 0,...s,alpha:"discard"});return!!(await VideoEncoder.isConfigSupported(n)).supported&&(!G()||new Promise((async e=>{try{const t=new VideoEncoder({output:()=>{},error:()=>e(!1)});t.configure(n);const a=new Uint8Array(r*i*4),s=new VideoFrame(a,{format:"RGBA",codedWidth:r,codedHeight:i,timestamp:0});t.encode(s),s.close(),await t.flush(),e(!0)}catch{e(!1)}})))},ic=async(e,t={})=>{const{numberOfChannels:r=2,sampleRate:i=48e3,bitrate:a=128e3,...s}=t;if(!ge.includes(e))return!1;if(!Number.isInteger(r)||r<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(a instanceof Go)&&(!Number.isInteger(a)||a<=0))throw new TypeError("bitrate must be a positive integer.");Qo(e,s);let n=null;if(Dt.length>0&&(n??=Ko({codec:e,numberOfChannels:r,sampleRate:i,bitrate:a,...s}),Dt.some((t=>t.supports(e,n)))))return!0;if(pe.includes(e))return!0;if("undefined"==typeof AudioEncoder)return!1;n??=Ko({codec:e,numberOfChannels:r,sampleRate:i,bitrate:a,...s});return!0===(await AudioEncoder.isConfigSupported(n)).supported},ac=async e=>!!we.includes(e),sc=async()=>{const[e,t,r]=await Promise.all([nc(),oc(),cc()]);return[...e,...t,...r]},nc=async(e=me,t)=>{const r=await Promise.all(e.map((e=>rc(e,t))));return e.filter(((e,t)=>r[t]))},oc=async(e=ge,t)=>{const r=await Promise.all(e.map((e=>ic(e,t))));return e.filter(((e,t)=>r[t]))},cc=async(e=we)=>{const t=await Promise.all(e.map(ac));return e.filter(((e,r)=>t[r]))},dc=async(e,t)=>{for(const r of e)if(await rc(r,t))return r;return null},lc=async(e,t)=>{for(const r of e)if(await ic(r,t))return r;return null},hc=async e=>{for(const t of e)if(await ac(t))return t;return null};
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */
class uc{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1,this._timestampOffset=0}_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?this._closingPromise:this._flushAndClose(e)}}class mc extends uc{constructor(e){if(super(),this._connectedTrack=null,!me.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${me.join(", ")}.`);this._codec=e}}class pc extends mc{constructor(e){super(e)}add(e,t){if(!(e instanceof Ut))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.addEncodedVideoPacket(this._connectedTrack,e,t)}}class fc{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.resizeCanvas=null,this.customEncoder=null,this.customEncoderCallSerializer=new j,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorNeedsNewStack=!0}async add(e,r,i){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),null!==this.codedWidth&&null!==this.codedHeight){if(e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight){const i=this.encodingConfig.sizeChangeBehavior??"deny";if("passThrough"===i);else{if("deny"===i)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 'strict' in the encoding options.`);{let a=!1;this.resizeCanvas||("undefined"!=typeof document?(this.resizeCanvas=document.createElement("canvas"),this.resizeCanvas.width=this.codedWidth,this.resizeCanvas.height=this.codedHeight):this.resizeCanvas=new OffscreenCanvas(this.codedWidth,this.codedHeight),a=!0);const s=this.resizeCanvas.getContext("2d",{alpha:G()});t(s),a||(G()?(s.fillStyle="black",s.fillRect(0,0,this.codedWidth,this.codedHeight)):s.clearRect(0,0,this.codedWidth,this.codedHeight)),e.drawWithFit(s,{fit:i}),r&&e.close(),e=new qt(this.resizeCanvas,{timestamp:e.timestamp,duration:e.duration,rotation:e.rotation}),r=!0}}}}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),t(this.encoderInitialized);const a=this.encodingConfig.keyFrameInterval??5,s=Math.floor(e.timestamp/a),n={...i,keyFrame:i?.keyFrame||0===a||s!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=s,this.customEncoder){this.customEncoderQueueSize++;const t=e.clone(),r=this.customEncoderCallSerializer.call((()=>this.customEncoder.encode(t,n))).then((()=>this.customEncoderQueueSize--)).catch((e=>this.error??=e)).finally((()=>{t.close()}));this.customEncoderQueueSize>=4&&await r}else{t(this.encoder);const i=e.toVideoFrame();if(this.alphaEncoder){if(!!i.format&&!i.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(i,n),i.close();else{const e=i.displayWidth,t=i.displayHeight;if(!this.splitter)try{this.splitter=new gc(e,t)}catch(e){console.error("Due to an error, only color data will be encoded.",e),this.splitterCreationFailed=!0,this.alphaFrameQueue.push(null),this.encoder.encode(i,n),i.close()}if(this.splitter){const e=this.splitter.extractColor(i),t=this.splitter.extractAlpha(i);this.alphaFrameQueue.push(t),this.encoder.encode(e,n),e.close(),i.close()}}}else this.encoder.encode(i,n),i.close();r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise((e=>this.encoder.addEventListener("dequeue",e,{once:!0})))}await this.muxer.mutex.currentPromise}finally{r&&e.close()}}ensureEncoder(e){const r=new Error;this.ensureEncoderPromise=(async()=>{const i=jo({width:e.codedWidth,height:e.codedHeight,...this.encodingConfig,framerate:this.source._connectedTrack?.metadata.frameRate});this.encodingConfig.onEncoderConfig?.(i);const a=Mt.find((e=>e.supports(this.encodingConfig.codec,i)));if(a)this.customEncoder=new a,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=i,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof Ut))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.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch((e=>{this.error??=e,this.errorNeedsNewStack=!1}))},await this.customEncoder.init();else{if("undefined"==typeof VideoEncoder)throw new Error("VideoEncoder is not supported by this browser.");i.alpha="discard","keep"===this.encodingConfig.alpha&&(i.latencyMode="quality");if((i.width%2==1||i.height%2==1)&&("avc"===this.encodingConfig.codec||"hevc"===this.encodingConfig.codec))throw new Error(`The dimensions ${i.width}x${i.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(i)).supported)throw new Error(`This specific encoder configuration (${i.codec}, ${i.bitrate} bps, ${i.width}x${i.height}, hardware acceleration: ${i.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const e=[],a=[];let s=0,n=0;const o=(e,t,r)=>{const i={};if(t){const e=new Uint8Array(t.byteLength);t.copyTo(e),i.alpha=e}const a=Ut.fromEncodedChunk(e,i);this.encodingConfig.onEncodedPacket?.(a,r),this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,r).catch((e=>{this.error??=e,this.errorNeedsNewStack=!1}))};this.encoder=new VideoEncoder({output:(r,i)=>{if(!this.alphaEncoder)return void o(r,null,i);const c=this.alphaFrameQueue.shift();t(void 0!==c),c?(this.alphaEncoder.encode(c,{keyFrame:"key"===r.type}),n++,c.close(),e.push({chunk:r,meta:i})):0===n?o(r,null,i):(a.push(s+n),e.push({chunk:r,meta:i}))},error:e=>{e.stack=r.stack,this.error??=e}}),this.encoder.configure(i),"keep"===this.encodingConfig.alpha&&(this.alphaEncoder=new VideoEncoder({output:(r,i)=>{n--;const c=e.shift();for(t(void 0!==c),o(c.chunk,r,c.meta),s++;a.length>0&&a[0]===s;){a.shift();const r=e.shift();t(void 0!==r),o(r.chunk,null,r.meta)}},error:e=>{e.stack=r.stack,this.error??=e}}),this.alphaEncoder.configure(i))}t(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){e||this.checkForEncoderError(),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.errorNeedsNewStack&&(this.error.stack=(new Error).stack),this.error}}class gc{constructor(e,t){this.lastFrame=null,"undefined"!=typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);const r=this.canvas.getContext("webgl2",{alpha:!0});if(!r)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=r,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)}createVertexShader(){return 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(){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(){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){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(){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 i=this.gl.getAttribLocation(this.colorProgram,"a_position"),a=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(i),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(a),this.gl.vertexAttribPointer(a,2,this.gl.FLOAT,!1,16,8),e}createTexture(){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}updateTexture(e){this.lastFrame!==e&&(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),this.lastFrame=e)}extractColor(e){return this.updateTexture(e),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"})}extractAlpha(e){this.updateTexture(e),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:r,height:i}=this.canvas,a=r*i+2*(Math.ceil(r/2)*Math.ceil(i/2)),s=Math.ceil(a/(4*r));let n=new Uint8Array(4*r*s);this.gl.readPixels(0,0,r,s,this.gl.RGBA,this.gl.UNSIGNED_BYTE,n),n=n.subarray(0,a),t(128===n[r*i]),t(128===n[n.length-1]);const o={format:"I420",codedWidth:r,codedHeight:i,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[n.buffer]};return new VideoFrame(n,o)}close(){this.gl.getExtension("WEBGL_lose_context")?.loseContext(),this.gl=null}}class wc extends mc{constructor(e){Ho(e),super(e.codec),this._encoder=new fc(this,e)}add(e,t){if(!(e instanceof qt))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class kc extends mc{constructor(e,t){if(!("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");Ho(t),super(t.codec),this._encoder=new fc(this,t),this._canvas=e}add(e,t=0,r){if(!Number.isFinite(e)||e<0)throw new TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw new TypeError("duration must be a non-negative number.");const i=new qt(this._canvas,{timestamp:e,duration:t});return this._encoder.add(i,!0,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class bc extends mc{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t){if(!(e instanceof MediaStreamTrack)||"video"!==e.kind)throw new TypeError("track must be a video MediaStreamTrack.");Ho(t),super((t={...t,latencyMode:"realtime"}).codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=I(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastSampleTimestamp=null,this._pauseOffset=0,this._encoder=new fc(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1;const r=r=>{if(t)return void r.close();const i=r.timestamp/1e6;if(this._paused){if(null!==e){if(null!==this._lastSampleTimestamp){const e=i-this._lastSampleTimestamp;this._pauseOffset-=e}this._lastSampleTimestamp=i}return void r.close()}if(null===e){e=i;const t=this._connectedTrack.output._muxer;null===t.firstMediaStreamTimestamp?(t.firstMediaStreamTimestamp=performance.now()/1e3,this._timestampOffset=-e):this._timestampOffset=performance.now()/1e3-t.firstMediaStreamTimestamp-e}if(this._lastSampleTimestamp=i,this._encoder.getQueueSize()>=4)return void r.close();const a=new qt(r,{timestamp:i+this._pauseOffset});this._encoder.add(a,!0).catch((e=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),null!==this._workerTrackId&&Bc({type:"stopTrack",trackId:this._workerTrackId})}))};if("undefined"!=typeof MediaStreamTrackProcessor){const e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:r});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch((e=>{e instanceof DOMException&&"AbortError"===e.name||this._promiseWithResolvers.reject(e)}))}else{if(!await Ac())throw new Error("MediaStreamTrackProcessor is required but not supported by this browser.");this._workerTrackId=_c++,Bc({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=e=>{const t=e.data;"videoFrame"===t.type&&t.trackId===this._workerTrackId?r(t.videoFrame):"error"===t.type&&t.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(t.error)},Ic.addEventListener("message",this._workerListener)}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),null!==this._workerTrackId&&(t(this._workerListener),Bc({type:"stopTrack",trackId:this._workerTrackId}),await new Promise((e=>{const r=i=>{const a=i.data;"trackStopped"===a.type&&a.trackId===this._workerTrackId&&(t(this._workerListener),Ic.removeEventListener("message",this._workerListener),Ic.removeEventListener("message",r),e())};Ic.addEventListener("message",r)}))),await this._encoder.flushAndClose(e)}}class yc extends uc{constructor(e){if(super(),this._connectedTrack=null,!ge.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${ge.join(", ")}.`);this._codec=e}}class Tc extends yc{constructor(e){super(e)}add(e,t){if(!(e instanceof Ut))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)}}class Sc{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 j,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.error=null,this.errorNeedsNewStack=!0}async add(e,r){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;this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),t(this.encoderInitialized);{const t=Math.round(e.timestamp*e.sampleRate),r=Math.round((e.timestamp+e.duration)*e.sampleRate);if(null===this.lastEndSampleIndex)this.lastEndSampleIndex=r;else{const r=t-this.lastEndSampleIndex;if(r>=64){const t=new Zt({data:new Float32Array(r*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:r,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.add(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;const t=e.clone(),r=this.customEncoderCallSerializer.call((()=>this.customEncoder.encode(t))).then((()=>this.customEncoderQueueSize--)).catch((e=>this.error??=e)).finally((()=>{t.close()}));this.customEncoderQueueSize>=4&&await r,await this.muxer.mutex.currentPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,r);else{t(this.encoder);const i=e.toAudioData();this.encoder.encode(i),i.close(),r&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise((e=>this.encoder.addEventListener("dequeue",e,{once:!0}))),await this.muxer.mutex.currentPromise}}finally{r&&e.close()}}async doPcmEncoding(e,r){t(this.outputSampleSize),t(this.writeOutputValue);const{numberOfChannels:i,numberOfFrames:a,sampleRate:s,timestamp:n}=e,o=2048,c=[];for(let t=0;t<a;t+=o){const r=Math.min(o,e.numberOfFrames-t),a=r*i*this.outputSampleSize,s=new ArrayBuffer(a),n=new DataView(s);c.push({frameCount:r,view:n})}const d=e.allocationSize({planeIndex:0,format:"f32-planar"}),l=new Float32Array(d/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<i;t++){e.copyTo(l,{planeIndex:t,format:"f32-planar"});for(let e=0;e<c.length;e++){const{frameCount:r,view:a}=c[e];for(let s=0;s<r;s++)this.writeOutputValue(a,(s*i+t)*this.outputSampleSize,l[e*o+s])}}r&&e.close();const h={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let e=0;e<c.length;e++){const{frameCount:t,view:r}=c[e],i=r.buffer,a=e*o,d=new Ut(new Uint8Array(i),"key",n+a/s,t/s);this.encodingConfig.onEncodedPacket?.(d,h),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,d,h)}}ensureEncoder(e){const r=new Error;this.ensureEncoderPromise=(async()=>{const{numberOfChannels:a,sampleRate:n}=e,o=Ko({numberOfChannels:a,sampleRate:n,...this.encodingConfig});this.encodingConfig.onEncoderConfig?.(o);const d=Dt.find((e=>e.supports(this.encodingConfig.codec,o)));if(d)this.customEncoder=new d,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=o,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof Ut))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.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch((e=>{this.error??=e,this.errorNeedsNewStack=!1}))},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(o)).supported)throw new Error(`This specific encoder configuration (${o.codec}, ${o.bitrate} bps, ${o.numberOfChannels} channels, ${o.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);this.encoder=new AudioEncoder({output:(e,t)=>{if("aac"===this.encodingConfig.codec&&t?.decoderConfig){let e=!1;if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<2)e=!0;else{e=0===Fe(c(t.decoderConfig.description)).objectType}if(e){const e=Number(i(o.codec.split(".")));t.decoderConfig.description=(e=>{let t=Ae.indexOf(e.sampleRate),r=null;-1===t&&(t=15,r=e.sampleRate);const i=Be.indexOf(e.numberOfChannels);if(-1===i)throw new TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let a=13;e.objectType>=32&&(a+=6),15===t&&(a+=24);const n=Math.ceil(a/8),o=new Uint8Array(n),c=new s(o);return e.objectType<32?c.writeBits(5,e.objectType):(c.writeBits(5,31),c.writeBits(6,e.objectType-32)),c.writeBits(4,t),15===t&&c.writeBits(24,r),c.writeBits(4,i),o})({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}const r=Ut.fromEncodedChunk(e);this.encodingConfig.onEncodedPacket?.(r,t),this.muxer.addEncodedAudioPacket(this.source._connectedTrack,r,t).catch((e=>{this.error??=e,this.errorNeedsNewStack=!1}))},error:e=>{e.stack=r.stack,this.error??=e}}),this.encoder.configure(o)}t(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:r,sampleSize:i,littleEndian:a}=ze(e);switch(this.outputSampleSize=i,i){case 1:"unsigned"===r?this.writeOutputValue=(e,t,r)=>e.setUint8(t,z(127.5*(r+1),0,255)):"signed"===r?this.writeOutputValue=(e,t,r)=>{e.setInt8(t,z(Math.round(128*r),-128,127))}:"ulaw"===r?this.writeOutputValue=(e,t,r)=>{const i=z(Math.floor(32767*r),-32768,32767);e.setUint8(t,(e=>{let t=e,r=4096,i=0,a=12,s=0;for(t<0&&(t=-t,i=128),t+=33,t>8191&&(t=8191);(t&r)!==r&&a>=5;)r>>=1,a--;return s=t>>a-4&15,255&~(i|a-5<<4|s)})(i))}:"alaw"===r?this.writeOutputValue=(e,t,r)=>{const i=z(Math.floor(32767*r),-32768,32767);e.setUint8(t,(e=>{let t=2048,r=0,i=11,a=0,s=e;for(s<0&&(s=-s,r=128),s>4095&&(s=4095);(s&t)!==t&&i>=5;)t>>=1,i--;return a=s>>(4===i?1:i-4)&15,85^(r|i-4<<4|a)})(i))}:t(!1);break;case 2:"unsigned"===r?this.writeOutputValue=(e,t,r)=>e.setUint16(t,z(32767.5*(r+1),0,65535),a):"signed"===r?this.writeOutputValue=(e,t,r)=>e.setInt16(t,z(Math.round(32767*r),-32768,32767),a):t(!1);break;case 3:"unsigned"===r?this.writeOutputValue=(e,t,r)=>M(e,t,z(8388607.5*(r+1),0,16777215),a):"signed"===r?this.writeOutputValue=(e,t,r)=>((e,t,r,i)=>{(r=z(r,-8388608,8388607))<0&&(r=r+16777216&16777215),M(e,t,r,i)})(e,t,z(Math.round(8388607*r),-8388608,8388607),a):t(!1);break;case 4:"unsigned"===r?this.writeOutputValue=(e,t,r)=>e.setUint32(t,z(2147483647.5*(r+1),0,4294967295),a):"signed"===r?this.writeOutputValue=(e,t,r)=>e.setInt32(t,z(Math.round(2147483647*r),-2147483648,2147483647),a):"float"===r?this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,a):t(!1);break;case 8:"float"===r?this.writeOutputValue=(e,t,r)=>e.setFloat64(t,r,a):t(!1);break;default:B(i),t(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),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.errorNeedsNewStack&&(this.error.stack=(new Error).stack),this.error}}class vc extends yc{constructor(e){$o(e),super(e.codec),this._encoder=new Sc(this,e)}add(e){if(!(e instanceof Zt))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Cc extends yc{constructor(e){$o(e),super(e.codec),this._accumulatedTime=0,this._encoder=new Sc(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=Zt._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const e of t)await this._encoder.add(e,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class xc extends yc{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t){if(!(e instanceof MediaStreamTrack)||"audio"!==e.kind)throw new TypeError("track must be an audio MediaStreamTrack.");$o(t),super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=I(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastSampleTimestamp=null,this._pauseOffset=0,this._encoder=new Sc(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1;const r=r=>{if(t)return void r.close();const i=r.timestamp;if(this._paused){if(null!==e){if(null!==this._lastSampleTimestamp){const e=i-this._lastSampleTimestamp;this._pauseOffset-=e}this._lastSampleTimestamp=i}r.close()}else{if(null===e){e=r.timestamp;const t=this._connectedTrack.output._muxer;null===t.firstMediaStreamTimestamp?(t.firstMediaStreamTimestamp=performance.now()/1e3,this._timestampOffset=-e):this._timestampOffset=performance.now()/1e3-t.firstMediaStreamTimestamp-e}this._lastSampleTimestamp=i,this._encoder.getQueueSize()>=4?r.close():(r.setTimestamp(i+this._pauseOffset),this._encoder.add(r,!0).catch((e=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._audioContext?.suspend()})))}};if("undefined"!=typeof MediaStreamTrackProcessor){const e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:e=>r(new Zt(e))});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch((e=>{e instanceof DOMException&&"AbortError"===e.name||this._promiseWithResolvers.reject(e)}))}else{const e=window.AudioContext||window.webkitAudioContext;this._audioContext=new e({sampleRate:this._track.getSettings().sampleRate});const t=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),"suspended"===this._audioContext.state&&await this._audioContext.resume(),t.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let i=0;this._scriptProcessorNode.onaudioprocess=e=>{const t=Zt._fromAudioBuffer(e.inputBuffer,i);i+=e.inputBuffer.duration;for(const e of t)r(e)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(t(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}}const Pc=()=>{const e=(e,t)=>{t?self.postMessage(e,{transfer:t}):self.postMessage(e)};e({type:"support",supported:"undefined"!=typeof MediaStreamTrackProcessor});const t=new Map,r=new Map;self.addEventListener("message",(i=>{const a=i.data;switch(a.type){case"videoTrack":{r.set(a.trackId,a.track);const i=new MediaStreamTrackProcessor({track:a.track}),s=new WritableStream({write:t=>{r.has(a.trackId)?e({type:"videoFrame",trackId:a.trackId,videoFrame:t},[t]):t.close()}}),n=new AbortController;t.set(a.trackId,n),i.readable.pipeTo(s,{signal:n.signal}).catch((t=>{t instanceof DOMException&&"AbortError"===t.name||e({type:"error",trackId:a.trackId,error:t})}))}break;case"stopTrack":{const i=t.get(a.trackId);i&&(i.abort(),t.delete(a.trackId));const s=r.get(a.trackId);s?.stop(),r.delete(a.trackId),e({type:"trackStopped",trackId:a.trackId})}break;default:B(a)}}))};let _c=0,Ic=null;let Ec=null;const Ac=async()=>null!==Ec?Ec:(Ic||(()=>{const e=new Blob([`(${Pc.toString()})()`],{type:"application/javascript"}),t=URL.createObjectURL(e);Ic=new Worker(t)})(),new Promise((e=>{t(Ic);const r=t=>{const i=t.data;"support"===i.type&&(Ec=i.supported,Ic.removeEventListener("message",r),e(i.supported))};Ic.addEventListener("message",r)}))),Bc=(e,r)=>{t(Ic),r?Ic.postMessage(e,r):Ic.postMessage(e)};class Fc extends uc{constructor(e){if(super(),this._connectedTrack=null,!we.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${we.join(", ")}.`);this._codec=e}}class Mc extends Fc{constructor(e){super(e),this._error=null,this._parser=new Cs({codec:e,output:(e,t)=>{this._connectedTrack?.output._muxer.addSubtitleCue(this._connectedTrack,e,t).catch((e=>{this._error??=e}))}})}add(e){if("string"!=typeof e)throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._connectedTrack.output._muxer.mutex.currentPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose(e){e||this._checkForError()}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const Dc=["video","audio","subtitle"],zc=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.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.")};class Rc{constructor(e){if(this.state="pending",this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new S,this._metadataTags={},!e||"object"!=typeof e)throw new TypeError("options must be an object.");if(!(e.format instanceof Fo))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof fo))throw new TypeError("options.target must be a Target.");if(e.target._output)throw new Error("Target is already used for another output.");e.target._output=this,this.format=e.format,this.target=e.target,this._writer=e.target._createWriter(),this._muxer=e.format._createMuxer(this)}addVideoTrack(e,t={}){if(!(e instanceof mc))throw new TypeError("source must be a VideoSource.");if(zc(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.`);this._addTrack("video",e,t)}addAudioTrack(e,t={}){if(!(e instanceof yc))throw new TypeError("source must be an AudioSource.");zc(t),this._addTrack("audio",e,t)}addSubtitleTrack(e,t={}){if(!(e instanceof Fc))throw new TypeError("source must be a SubtitleSource.");zc(t),this._addTrack("subtitle",e,t)}setMetadataTags(e){if(le(e),"pending"!==this.state)throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e,t,r){if("pending"!==this.state)throw new Error("Cannot add track after output has been started or canceled.");if(t._connectedTrack)throw new Error("Source is already used for a track.");const i=this.format.getSupportedTrackCounts(),a=this._tracks.reduce(((t,r)=>t+(r.type===e?1:0)),0),s=i[e].max;if(a===s)throw new Error(0===s?`${this.format._name} does not support ${e} tracks.`:`${this.format._name} does not support more than ${s} ${e} track`+(1===s?"":"s")+".");const n=i.total.max;if(this._tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} tracks`+(1===n?"":"s")+" in total.");const o={id:this._tracks.length+1,output:this,type:e,source:t,metadata:r};if("video"===o.type){const e=this.format.getSupportedVideoCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${e.map((e=>`'${e}'`)).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("audio"===o.type){const e=this.format.getSupportedAudioCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${e.map((e=>`'${e}'`)).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}else if("subtitle"===o.type){const e=this.format.getSupportedSubtitleCodecs();if(0===e.length)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(o.source._codec));if(!e.includes(o.source._codec))throw new Error(`Codec '${o.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${e.map((e=>`'${e}'`)).join(", ")}.`+this.format._codecUnsupportedHint(o.source._codec))}this._tracks.push(o),t._connectedTrack=o}async start(){const e=this.format.getSupportedTrackCounts();for(const t of Dc){const r=this._tracks.reduce(((e,r)=>e+(r.type===t?1:0)),0),i=e[t].min;if(r<i)throw new Error(i===e[t].max?`${this.format._name} requires exactly ${i} ${t} track${1===i?"":"s"}.`:`${this.format._name} requires at least ${i} ${t} track${1===i?"":"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",this._writer.start();const e=await this._mutex.acquire();await this._muxer.start();const t=this._tracks.map((e=>e.source._start()));await Promise.all(t),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(),t=this._tracks.map((e=>e.source._flushOrWaitForOngoingClose(!0)));await Promise.all(t),await this._writer.close(),e()})():void 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(),t=this._tracks.map((e=>e.source._flushOrWaitForOngoingClose(!1)));await Promise.all(t),await this._muxer.finalize(),await this._writer.flush(),await this._writer.finalize(),this.state="finalized",e()})()}}
/*!
 * Copyright (c) 2025-present, Vanilagy and contributors
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/.
 */const Oc=e=>{if(void 0!==e&&(!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&&!me.includes(e.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${me.join(", ")}.`);if(void 0!==e?.bitrate&&!(e.bitrate instanceof Go)&&(!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&&Kt(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'.")},Uc=e=>{if(void 0!==e&&(!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&&!ge.includes(e.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${ge.join(", ")}.`);if(void 0!==e?.bitrate&&!(e.bitrate instanceof Go)&&(!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?.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.")},Nc=48e3;class Vc{static async init(e){const t=new Vc(e);return await t._init(),t}constructor(e){if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._trackPromises=[],this._executed=!1,this._synchronizer=new Lc,this._totalDuration=null,this._maxTimestamps=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 Ya))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof Rc))throw new TypeError("options.output must be an Output.");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("function"!=typeof e.video&&Oc(e.video),"function"!=typeof e.audio&&Uc(e.audio),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)||e.trim.start<0))throw new TypeError("options.trim.start, when provided, must be a non-negative number.");if(void 0!==e.trim?.end&&(!Number.isFinite(e.trim.end)||e.trim.end<0))throw new TypeError("options.trim.end, when provided, must be a non-negative 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&&le(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,this._startTimestamp=e.trim?.start??0,this._endTimestamp=e.trim?.end??1/0;const{promise:t,resolve:r}=I();this._started=t,this._start=r}async _init(){const e=await this.input.getTracks(),r=this.output.format.getSupportedTrackCounts();let i=1,a=1;for(const s of e){let e;s.isVideoTrack()?this._options.video&&("function"==typeof this._options.video?(e=await this._options.video(s,i),Oc(e),i++):e=this._options.video):s.isAudioTrack()?this._options.audio&&("function"==typeof this._options.audio?(e=await this._options.audio(s,a),Uc(e),a++):e=this._options.audio):t(!1),e?.discard?this.discardedTracks.push({track:s,reason:"discarded_by_user"}):this._totalTrackCount!==r.total.max?this._addedCounts[s.type]!==r[s.type].max?s.isVideoTrack()?await this._processVideoTrack(s,e??{}):s.isAudioTrack()&&await this._processAudioTrack(s,e??{}):this.discardedTracks.push({track:s,reason:"max_track_count_of_type_reached"}):this.discardedTracks.push({track:s,reason:"max_track_count_reached"})}const s=await this.input.getMetadataTags();let n;if(this._options.tags){const e="function"==typeof this._options.tags?await this._options.tags(s):this._options.tags;le(e),n=e}else n=s;const o=(await this.input.getFormat()).mimeType===this.output.format.mimeType,c=s.raw===n.raw;if(s.raw&&c&&!o&&delete n.raw,this.output.setMetadataTags(n),this.isValid=this._totalTrackCount>=r.total.min&&this._addedCounts.video>=r.video.min&&this._addedCounts.audio>=r.audio.min&&this._addedCounts.subtitle>=r.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.push("\n\n"+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));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()));1===t.length?e.push(`\nTracks were discarded because your environment is not able to encode '${t[0]}'.`):e.push(`\nTracks were discarded because your environment is not able to encode any of the following codecs: ${t.map((e=>`'${e}'`)).join(", ")}.`),t.includes("mp3")&&e.push("\nThe @mediabunny/mp3-encoder extension package provides support for encoding MP3.")}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.");if(this._executed=!0,this.onProgress){this._computeProgress=!0,this._totalDuration=Math.min(await this.input.computeDuration()-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const e of this.utilizedTracks)this._maxTimestamps.set(e.id,0);this.onProgress?.(0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(e){throw this._canceled||this.cancel(),e}this._canceled&&await new Promise((()=>{})),await this.output.finalize(),this._computeProgress&&this.onProgress?.(1)}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,i){const a=e.codec;if(!a)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec"});let s;const n=r(e.rotation+(i.rotate??0)),o=this.output.format.supportsVideoRotationMetadata&&(i.allowRotationMetadata??!0),[c,d]=n%180==0?[e.codedWidth,e.codedHeight]:[e.codedHeight,e.codedWidth],l=i.crop;l&&Qt(l,c,d);const[h,u]=l?[l.width,l.height]:[c,d];let m=h,p=u;const f=m/p,g=e=>2*Math.ceil(e/2);void 0!==i.width&&void 0===i.height?(m=g(i.width),p=g(Math.round(m/f))):void 0===i.width&&void 0!==i.height?(p=g(i.height),m=g(Math.round(p*f))):void 0!==i.width&&void 0!==i.height&&(m=g(i.width),p=g(i.height));const w=await e.getFirstTimestamp(),k=!!i.forceTranscode||this._startTimestamp>0||w<0||!!i.frameRate||void 0!==i.keyFrameInterval||void 0!==i.process;let b=m!==h||p!==u||0!==n&&(!o||void 0!==i.process)||!!l;const y=i.alpha??"discard";let T=this.output.format.getSupportedVideoCodecs();if(k||i.bitrate||b||!T.includes(a)||i.codec&&i.codec!==a){if(!await e.canDecode())return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});i.codec&&(T=T.filter((e=>e===i.codec)));const r=i.bitrate??Zo,a=await dc(T,{width:i.process&&i.processedWidth?i.processedWidth:m,height:i.process&&i.processedHeight?i.processedHeight:p,bitrate:r});if(!a)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});const o={codec:a,bitrate:r,keyFrameInterval:i.keyFrameInterval,sizeChangeBehavior:i.fit??"passThrough",alpha:y,hardwareAcceleration:i.hardwareAcceleration},c=new wc(o);if(s=c,!b){const t=new Rc({format:new Do,target:new bo}),r=new wc(o);t.addVideoTrack(r),await t.start();const i=new pr(e),a=await i.getSample(w);if(a)try{await r.add(a),a.close(),await t.finalize()}catch(e){console.info("Error when probing encoder support. Falling back to rerender path.",e),b=!0,t.cancel()}else await t.cancel()}b?this._trackPromises.push((async()=>{await this._started;const r=new fr(e,{width:m,height:p,fit:i.fit??"fill",rotation:n,crop:i.crop,poolSize:1,alpha:"keep"===y}).canvases(this._startTimestamp,this._endTimestamp),a=i.frameRate;let s=null,o=null,d=null;const l=async r=>{t(s),t(void 0!==a);const n=Math.round((r-o)*a);for(let t=1;t<n;t++){const r=new qt(s,{timestamp:o+t/a,duration:1/a});await this._registerVideoSample(e,i,c,r),r.close()}};for await(const{canvas:t,timestamp:n,duration:h}of r){if(this._canceled)return;let r=Math.max(n-this._startTimestamp,0);if(d=r+h,void 0!==a){const e=Math.floor(r*a)/a;if(null!==s){if(e<=o){s=t,o=e;continue}await l(e)}r=e}const u=new qt(t,{timestamp:r,duration:void 0!==a?1/a:h});await this._registerVideoSample(e,i,c,u),u.close(),void 0!==a&&(s=t,o=r)}s&&(t(null!==d),t(void 0!==a),await l(Math.floor(d*a)/a)),c.close(),this._synchronizer.closeTrack(e.id)})()):this._trackPromises.push((async()=>{await this._started;const r=new pr(e),a=i.frameRate;let s=null,n=null,o=null;const d=async r=>{t(s),t(void 0!==a);const o=Math.round((r-n)*a);for(let t=1;t<o;t++)s.setTimestamp(n+t/a),s.setDuration(1/a),await this._registerVideoSample(e,i,c,s);s.close()};for await(const t of r.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled)return void s?.close();let r=Math.max(t.timestamp-this._startTimestamp,0);if(o=r+t.duration,void 0!==a){const e=Math.floor(r*a)/a;if(null!==s){if(e<=n){s.close(),s=t,n=e;continue}await d(e)}r=e,t.setDuration(1/a)}t.setTimestamp(r),await this._registerVideoSample(e,i,c,t),void 0!==a?(s=t,n=r):t.close()}s&&(t(null!==o),t(void 0!==a),await d(Math.floor(o*a)/a)),c.close(),this._synchronizer.closeTrack(e.id)})())}else{const t=new pc(a);s=t,this._trackPromises.push((async()=>{await this._started;const r=new cr(e),i={decoderConfig:await e.getDecoderConfig()??void 0},a=Number.isFinite(this._endTimestamp)?await r.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(const s of r.packets(void 0,a,{verifyKeyPackets:!0})){if(this._canceled)return;"discard"===y&&(delete s.sideData.alpha,delete s.sideData.alphaByteLength),this._reportProgress(e.id,s.timestamp),await t.add(s,i),this._synchronizer.shouldWait(e.id,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addVideoTrack(s,{frameRate:i.frameRate,languageCode:V(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition,rotation:b?0:n}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerVideoSample(e,t,r,i){if(this._canceled)return;let a;if(this._reportProgress(e.id,i.timestamp),t.process){let e=t.process(i);e instanceof Promise&&(e=await e),Array.isArray(e)||(e=null===e?[]:[e]),a=e.map((e=>e instanceof qt?e:"undefined"!=typeof VideoFrame&&e instanceof VideoFrame?new qt(e):new qt(e,{timestamp:i.timestamp,duration:i.duration})))}else a=[i];for(const t of a){if(this._canceled)break;await r.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(const e of a)e!==i&&e.close()}async _processAudioTrack(e,t){const r=e.codec;if(!r)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec"});let i;const a=e.numberOfChannels,s=e.sampleRate,n=await e.getFirstTimestamp();let o=t.numberOfChannels??a,c=t.sampleRate??s,d=o!==a||c!==s||this._startTimestamp>0||n<0,l=this.output.format.getSupportedAudioCodecs();if(t.forceTranscode||t.bitrate||d||!l.includes(r)||t.codec&&t.codec!==r||t.process){if(!await e.canDecode())return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec"});let r=null;t.codec&&(l=l.filter((e=>e===t.codec)));const a=t.bitrate??Zo,s=await oc(l,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:o,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:c,bitrate:a});if(s.some((e=>fe.includes(e)))||!l.some((e=>fe.includes(e)))||2===o&&c===Nc)r=s[0]??null;else{const e=(await oc(l,{numberOfChannels:2,sampleRate:Nc,bitrate:a})).find((e=>fe.includes(e)));e&&(d=!0,r=e,o=2,c=Nc)}if(null===r)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec"});if(d)i=this._resampleAudio(e,t,r,o,c,a);else{const s=new vc({codec:r,bitrate:a});i=s,this._trackPromises.push((async()=>{await this._started;const r=new kr(e);for await(const i of r.samples(void 0,this._endTimestamp)){if(this._canceled)return;await this._registerAudioSample(e,t,s,i),i.close()}s.close(),this._synchronizer.closeTrack(e.id)})())}}else{const t=new Tc(r);i=t,this._trackPromises.push((async()=>{await this._started;const r=new cr(e),i={decoderConfig:await e.getDecoderConfig()??void 0},a=Number.isFinite(this._endTimestamp)?await r.getPacket(this._endTimestamp,{metadataOnly:!0})??void 0:void 0;for await(const s of r.packets(void 0,a)){if(this._canceled)return;this._reportProgress(e.id,s.timestamp),await t.add(s,i),this._synchronizer.shouldWait(e.id,s.timestamp)&&await this._synchronizer.wait(s.timestamp)}t.close(),this._synchronizer.closeTrack(e.id)})())}this.output.addAudioTrack(i,{languageCode:V(e.languageCode)?e.languageCode:void 0,name:e.name??void 0,disposition:e.disposition}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e)}async _registerAudioSample(e,t,r,i){if(this._canceled)return;let a;if(this._reportProgress(e.id,i.timestamp),t.process){let e=t.process(i);if(e instanceof Promise&&(e=await e),Array.isArray(e)||(e=null===e?[]:[e]),!e.every((e=>e instanceof Zt)))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");a=e}else a=[i];for(const t of a){if(this._canceled)break;await r.add(t),this._synchronizer.shouldWait(e.id,t.timestamp)&&await this._synchronizer.wait(t.timestamp)}for(const e of a)e!==i&&e.close()}_resampleAudio(e,t,r,i,a,s){const n=new vc({codec:r,bitrate:s});return this._trackPromises.push((async()=>{await this._started;const r=new Wc({targetNumberOfChannels:i,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async r=>{await this._registerAudioSample(e,t,n,r),r.close()}}),s=new kr(e).samples(this._startTimestamp,this._endTimestamp);for await(const e of s){if(this._canceled)return;await r.add(e),e.close()}await r.finalize(),n.close(),this._synchronizer.closeTrack(e.id)})()),n}_reportProgress(e,r){if(!this._computeProgress)return;t(null!==this._totalDuration),this._maxTimestamps.set(e,Math.max(r,this._maxTimestamps.get(e)));const i=Math.min(...this._maxTimestamps.values()),a=z(i/this._totalDuration,0,1);a!==this._lastProgress&&(this._lastProgress=a,this.onProgress?.(a))}}class Lc{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}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 r=this.resolvers[t];r.timestamp-e<5&&(r.resolve(),this.resolvers.splice(t,1),t--)}return e}shouldWait(e,t){this.maxTimestamps.set(e,Math.max(t,this.maxTimestamps.get(e)??-1/0));return t-this.computeMinAndMaybeResolve()>=5}wait(e){const{promise:t,resolve:r}=I();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}}class Wc{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.startTime=e.startTime,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=0,this.maxWrittenFrame=-1}doChannelMixerSetup(){t(null!==this.sourceNumberOfChannels);const e=this.sourceNumberOfChannels,r=this.targetNumberOfChannels;this.channelMixer=1===e&&2===r?(t,r)=>t[r*e]:1===e&&4===r?(t,r,i)=>t[r*e]*+(i<2):1===e&&6===r?(t,r,i)=>t[r*e]*+(2===i):2===e&&1===r?(t,r)=>{const i=r*e;return.5*(t[i]+t[i+1])}:2===e&&4===r||2===e&&6===r?(t,r,i)=>t[r*e+i]*+(i<2):4===e&&1===r?(t,r)=>{const i=r*e;return.25*(t[i]+t[i+1]+t[i+2]+t[i+3])}:4===e&&2===r?(t,r,i)=>{const a=r*e;return.5*(t[a+i]+t[a+i+2])}:4===e&&6===r?(t,r,i)=>{const a=r*e;return i<2?t[a+i]:2===i||3===i?0:t[a+i-2]}:6===e&&1===r?(t,r)=>{const i=r*e;return Math.SQRT1_2*(t[i]+t[i+1])+t[i+2]+.5*(t[i+4]+t[i+5])}:6===e&&2===r?(t,r,i)=>{const a=r*e;return t[a+i]+Math.SQRT1_2*(t[a+2]+t[a+i+4])}:6===e&&4===r?(t,r,i)=>{const a=r*e;return i<2?t[a+i]+Math.SQRT1_2*t[a+2]:t[a+i+2]}:(t,r,i)=>i<e?t[r*e+i]: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 r=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(r);const i=e.allocationSize({planeIndex:0,format:"f32"}),a=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(a,{planeIndex:0,format:"f32"});const s=e.timestamp-this.startTime,n=e.numberOfFrames/this.sourceSampleRate,o=Math.min(s+n,this.endTime-this.startTime),c=Math.floor(s*this.targetSampleRate),d=Math.ceil(o*this.targetSampleRate);for(let r=c;r<d;r++){if(r<this.bufferStartFrame)continue;for(;r>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const i=r-this.bufferStartFrame;t(i<this.bufferSizeInFrames);const n=(r/this.targetSampleRate-s)*this.sourceSampleRate,o=Math.floor(n),c=Math.ceil(n),d=n-o;for(let t=0;t<this.targetNumberOfChannels;t++){let r=0,s=0;o>=0&&o<e.numberOfFrames&&(r=this.channelMixer(a,o,t)),c>=0&&c<e.numberOfFrames&&(s=this.channelMixer(a,c,t));const n=r+d*(s-r),l=i*this.targetNumberOfChannels+t;this.outputBuffer[l]+=n}this.maxWrittenFrame=Math.max(this.maxWrittenFrame,i)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame<0)return;const e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));const r=this.bufferStartFrame/this.targetSampleRate,i=new Zt({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=-1}finalize(){return this.finalizeCurrentBuffer()}}export{Da as ADTS,Ra as ALL_FORMATS,Dc as ALL_TRACK_TYPES,ge as AUDIO_CODECS,Pa as AdtsInputFormat,Lo as AdtsOutputFormat,de as AttachedFile,br as AudioBufferSink,Cc as AudioBufferSource,Zt as AudioSample,kr as AudioSampleSink,vc as AudioSampleSource,yc as AudioSource,lr as BaseMediaSampleSink,Wa as BlobSource,La as BufferSource,go as BufferTarget,fr as CanvasSink,kc as CanvasSource,Vc as Conversion,It as CustomAudioDecoder,At as CustomAudioEncoder,_t as CustomVideoDecoder,Et as CustomVideoEncoder,Tc as EncodedAudioPacketSource,Ut as EncodedPacket,cr as EncodedPacketSink,pc as EncodedVideoPacketSource,za as FLAC,$a as FilePathSource,ko as FilePathTarget,xa as FlacInputFormat,Wo as FlacOutputFormat,Ya as Input,Sr as InputAudioTrack,Ja as InputDisposedError,ga as InputFormat,yr as InputTrack,Tr as InputVideoTrack,wa as IsobmffInputFormat,Mo as IsobmffOutputFormat,Ea as MATROSKA,Ba as MP3,_a as MP4,ya as MatroskaInputFormat,uc as MediaSource,xc as MediaStreamAudioTrackSource,bc as MediaStreamVideoTrackSource,Ro as MkvOutputFormat,zo as MovOutputFormat,Sa as Mp3InputFormat,Uo as Mp3OutputFormat,ka as Mp4InputFormat,Do as Mp4OutputFormat,fe as NON_PCM_AUDIO_CODECS,bo as NullTarget,Ma as OGG,Ca as OggInputFormat,Vo as OggOutputFormat,Rc as Output,Fo as OutputFormat,pe as PCM_AUDIO_CODECS,Ia as QTFF,Zo as QUALITY_HIGH,Yo as QUALITY_LOW,Jo as QUALITY_MEDIUM,ec as QUALITY_VERY_HIGH,Xo as QUALITY_VERY_LOW,Go as Quality,ba as QuickTimeInputFormat,Ka as ReadableStreamSource,ce as RichImageData,we as SUBTITLE_CODECS,Va as Source,Qa as StreamSource,wo as StreamTarget,Fc as SubtitleSource,fo as Target,Mc as TextSubtitleSource,ja as UrlSource,me as VIDEO_CODECS,Wt as VIDEO_SAMPLE_PIXEL_FORMATS,qt as VideoSample,jt as VideoSampleColorSpace,pr as VideoSampleSink,wc as VideoSampleSource,mc as VideoSource,Fa as WAVE,Aa as WEBM,No as WavOutputFormat,va as WaveInputFormat,Ta as WebMInputFormat,Oo as WebMOutputFormat,tc as canEncode,ic as canEncodeAudio,ac as canEncodeSubtitles,rc as canEncodeVideo,oc as getEncodableAudioCodecs,sc as getEncodableCodecs,cc as getEncodableSubtitleCodecs,nc as getEncodableVideoCodecs,lc as getFirstEncodableAudioCodec,hc as getFirstEncodableSubtitleCodec,dc as getFirstEncodableVideoCodec,zt as registerDecoder,Rt as registerEncoder};export default null;
//# sourceMappingURL=/sm/40b70f301e48890bd07360d5021596d01f07d32cbbdc0dd5d2b6a215b349483f.map