hyperframes 0.6.29 → 0.6.31
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +371 -32
- package/dist/hyperframe-runtime.js +17 -17
- package/dist/hyperframe.manifest.json +1 -1
- package/dist/hyperframe.runtime.iife.js +17 -17
- package/dist/studio/assets/index-BWBj8I6Q.css +1 -0
- package/dist/studio/assets/index-DSLrl2tB.js +531 -0
- package/dist/studio/assets/index-Do0kAMcy.js +115 -0
- package/dist/studio/index.html +2 -2
- package/package.json +1 -1
- package/dist/studio/assets/index-C-kAqQVb.js +0 -362
- package/dist/studio/assets/index-DVpLGNHi.css +0 -1
|
@@ -0,0 +1,531 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
3
|
+
*
|
|
4
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
5
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
6
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
7
|
+
*/function m(i){if(!i)throw new Error("Assertion failed.")}const Er=i=>{const e=(i%360+360)%360;if(e===0||e===90||e===180||e===270)return e;throw new Error(`Invalid rotation ${i}.`)},we=i=>i&&i[i.length-1],Wt=i=>i>=0&&i<2**32,V=i=>{let e=0;for(;i.readBits(1)===0&&e<32;)e++;if(e>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<e)-1+i.readBits(e)},At=i=>{const e=V(i);return(e&1)===0?-(e>>1):e+1>>1},Wl=(i,e,t,r)=>{for(let s=e;s<t;s++){const n=Math.floor(s/8);let a=i[n];const o=7-(s&7);a&=~(1<<o),a|=(r&1<<t-s-1)>>t-s-1<<o,i[n]=a}},he=i=>i.constructor===Uint8Array?i:ArrayBuffer.isView(i)?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i),Z=i=>i.constructor===DataView?i:ArrayBuffer.isView(i)?new DataView(i.buffer,i.byteOffset,i.byteLength):new DataView(i),qe=new TextDecoder,le=new TextEncoder,pt=i=>{for(let e=0;e<i.length;e++)if(i.charCodeAt(e)>255)return!1;return!0},Dn=i=>Object.fromEntries(Object.entries(i).map(([e,t])=>[t,e])),ar={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},Qi=Dn(ar),or={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Xi=Dn(or),cr={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},$i=Dn(cr),Oo=i=>!!i&&!!i.primaries&&!!i.transfer&&!!i.matrix&&i.fullRange!==void 0,Fr=i=>i instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&i instanceof SharedArrayBuffer||ArrayBuffer.isView(i);class lr{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(s=>{let n=!1;e=()=>{n||(s(),this.pending--,n=!0)}}),r=this.currentPromise;return this.currentPromise=t,this.pending++,await r,e}}const Ll=/^[0-9a-fA-F]+$/,wi=i=>[...i].map(e=>e.toString(16).padStart(2,"0")).join(""),Hl=i=>{m(i.length%2===0);const e=new Uint8Array(i.length/2);for(let t=0;t<i.length;t+=2)e[t/2]=parseInt(i.slice(t,t+2),16);return e},wa=i=>(i=i>>1&1431655765|(i&1431655765)<<1,i=i>>2&858993459|(i&858993459)<<2,i=i>>4&252645135|(i&252645135)<<4,i=i>>8&16711935|(i&16711935)<<8,i=i>>16&65535|(i&65535)<<16,i>>>0),vi=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){const a=r+s>>1,o=t(i[a]);o===e?(n=a,s=a-1):o<e?r=a+1:s=a-1}return n},ne=(i,e,t)=>{let r=0,s=i.length-1,n=-1;for(;r<=s;){const a=r+(s-r+1)/2|0;t(i[a])<=e?(n=a,r=a+1):s=a-1}return n},ya=(i,e,t)=>{const r=ne(i,t(e),t);i.splice(r+1,0,e)},ge=()=>{let i,e;return{promise:new Promise((r,s)=>{i=r,e=s}),resolve:i,reject:e}},Wo=(i,e)=>{const t=i.indexOf(e);t!==-1&&i.splice(t,1)},Lo=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return i[t]},us=(i,e)=>{for(let t=i.length-1;t>=0;t--)if(e(i[t]))return t;return-1},ql=async function*(i){Symbol.iterator in i?yield*i[Symbol.iterator]():yield*i[Symbol.asyncIterator]()},jl=i=>{if(!(Symbol.iterator in i)&&!(Symbol.asyncIterator in i))throw new TypeError("Argument must be an iterable or async iterable.")},De=i=>{throw new Error(`Unexpected value: ${i}`)},ds=(i,e,t)=>{const r=i.getUint8(e),s=i.getUint8(e+1),n=i.getUint8(e+2);return t?r|s<<8|n<<16:r<<16|s<<8|n},Kl=(i,e,t)=>ds(i,e,t)<<8>>8,hs=(i,e,t,r)=>{t=t>>>0,t=t&16777215,r?(i.setUint8(e,t&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t>>>16&255)):(i.setUint8(e,t>>>16&255),i.setUint8(e+1,t>>>8&255),i.setUint8(e+2,t&255))},Gl=(i,e,t,r)=>{t=Ie(t,-8388608,8388607),t<0&&(t=t+16777216&16777215),hs(i,e,t,r)},Ql=(i,e,t,r)=>{i.setUint32(e+0,t,!0),i.setInt32(e+4,Math.floor(t/2**32),!0)},Yi=(i,e)=>({async next(){const t=await i.next();return t.done?{value:void 0,done:!0}:{value:e(t.value),done:!1}},return(){return i.return()},throw(t){return i.throw(t)},[Symbol.asyncIterator](){return this}}),Ie=(i,e,t)=>Math.max(e,Math.min(t,i)),ve="und",yi=i=>{const e=Math.round(i);return Math.abs(i/e-1)<10*Number.EPSILON?e:i},nn=(i,e)=>Math.round(i/e)*e,vr=(i,e)=>Math.round(i*e)/e,Bs=(i,e)=>Math.floor(i/e)*e,ba=(i,e)=>Math.floor(i*e)/e,Xl=i=>{let e=0;for(;i;)e++,i>>=1;return e},$l=/^[a-z]{3}$/,bi=i=>$l.test(i),Ut=1e6*(1+Number.EPSILON),Yl=(i,e)=>{const t={...i,...e};if(i.headers||e.headers){const r=i.headers?ka(i.headers):{},s=e.headers?ka(e.headers):{},n={...r};Object.entries(s).forEach(([a,o])=>{const c=Object.keys(n).find(u=>u.toLowerCase()===a.toLowerCase());c&&delete n[c],n[a]=o}),t.headers=n}return t},ka=i=>{if(i instanceof Headers){const e={};return i.forEach((t,r)=>{e[r]=t}),e}if(Array.isArray(i)){const e={};return i.forEach(([t,r])=>{e[t]=r}),e}return i},Zl=async(i,e,t,r,s)=>{let n=0;for(;;)try{return await i(e,t)}catch(a){if(s())throw a;n++;const o=r(n,a,e);if(o===null)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(o)||o<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(o>0&&await Vn(1e3*o),s())throw a}},Jl=(i,e)=>{const t=i<0?-1:1;i=Math.abs(i);let r=0,s=1,n=1,a=0,o=i;for(;;){const c=Math.floor(o),u=c*n+r,l=c*a+s;if(l>e)return{num:t*n,den:a};if(r=n,s=a,n=u,a=l,o=1/(o-c),!isFinite(o))break}return{num:t*n,den:a}};class ki{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Fs=null;const fi=()=>{var i;return Fs!==null?Fs:Fs=!!(typeof navigator<"u"&&((i=navigator.vendor)!=null&&i.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let Rs=null;const Zi=()=>{var i;return Rs!==null?Rs:Rs=typeof navigator<"u"&&((i=navigator.userAgent)==null?void 0:i.includes("Firefox"))};let Ms=null;const an=()=>{var i;return Ms!==null?Ms:Ms=!!(typeof navigator<"u"&&((i=navigator.vendor)!=null&&i.includes("Google Inc")||/Chrome/.test(navigator.userAgent)))};let Ds=null;const eu=()=>{if(Ds!==null)return Ds;if(typeof navigator>"u")return null;const i=/\bChrome\/(\d+)/.exec(navigator.userAgent);return i?Ds=Number(i[1]):null},mr=(i,e)=>i!==-1?i:e,on=(i,e,t,r)=>i<=r&&t<=e,Rr=function*(i){for(const e in i){const t=i[e];t!==void 0&&(yield{key:e,value:t})}},tu=i=>{switch(i.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}},Ji=i=>{const e=atob(i),t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);return t},ru=i=>{let e="";for(let t=0;t<i.length;t++)e+=String.fromCharCode(i[t]);return btoa(e)},Ho=(i,e)=>{if(i.length!==e.length)return!1;for(let t=0;t<i.length;t++)if(i[t]!==e[t])return!1;return!0},zn=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Mr=i=>typeof i=="number"&&!Number.isNaN(i),Fe=(i,e)=>{if(e.includes("://"))return e;if(i.includes("://")){const o=i.indexOf("?");o!==-1&&(i=i.slice(0,o))}let t;if(e.startsWith("/")){const o=i.indexOf("://");if(o===-1)t=e;else{const c=i.indexOf("/",o+3);c===-1?t=i+e:t=i.slice(0,c)+e}}else{const o=i.lastIndexOf("/");o===-1?t=e:t=i.slice(0,o+1)+e}let r="";const s=t.indexOf("://");if(s!==-1){const o=t.indexOf("/",s+3);o!==-1&&(r=t.slice(0,o),t=t.slice(o))}const n=t.split("/"),a=[];for(const o of n)o===".."?a.pop():o!=="."&&a.push(o);return r+a.join("/")},ui=(i,e)=>{let t=0;for(let r=0;r<i.length;r++)e(i[r])&&t++;return t},Un=(i,e)=>{let t=-1,r=1/0;for(let s=0;s<i.length;s++){const n=e(i[s]);n<r&&(r=n,t=s)}return t},iu=(i,e)=>{let t=-1,r=-1/0;for(let s=0;s<i.length;s++){const n=e(i[s]);n>r&&(r=n,t=s)}return t},Ti=i=>{m(Number.isInteger(i.num)),m(Number.isInteger(i.den)),m(i.den!==0);let e=Math.abs(i.num),t=Math.abs(i.den);for(;t!==0;){const s=e%t;e=t,t=s}const r=e||1;return{num:i.num/r,den:i.den/r}},Ta=(i,e)=>{if(typeof i!="object"||!i)throw new TypeError(`${e} must be an object.`);if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(`${e}.left must be a non-negative integer.`);if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(`${e}.top must be a non-negative integer.`);if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(`${e}.width must be a non-negative integer.`);if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(`${e}.height must be a non-negative integer.`)};let Jr,su=1;const Sa=new Map,Nn=new Map,qo=()=>typeof window>"u",nu=()=>{const i=new Map,e=new Map;self.onmessage=t=>{const r=t.data;switch(r.type){case"set-timeout":{const s=setTimeout(()=>{i.delete(r.timerId),self.postMessage({type:"fire",timerId:r.timerId})},r.delay);i.set(r.timerId,s)}break;case"set-interval":{const s=setInterval(()=>{self.postMessage({type:"fire",timerId:r.timerId})},r.delay);e.set(r.timerId,s)}break;case"clear-timeout":{const s=i.get(r.timerId);s!==void 0&&(clearTimeout(s),i.delete(r.timerId))}break;case"clear-interval":{const s=e.get(r.timerId);s!==void 0&&(clearInterval(s),e.delete(r.timerId))}break}}},jo=()=>{if(Jr)return Jr;const i=`(${nu.toString()})();`,e=URL.createObjectURL(new Blob([i],{type:"text/javascript"}));return Jr=new Worker(e),URL.revokeObjectURL(e),Jr.onmessage=t=>{const r=t.data,s=Sa.get(r.timerId);if(s){Sa.delete(r.timerId),s();return}const n=Nn.get(r.timerId);n&&n()},Jr},au=(i,e)=>{if(qo())return{id:setInterval(i,e)};const t=su++;return Nn.set(t,()=>{i()}),jo().postMessage({type:"set-interval",timerId:t,delay:e}),{id:t}},ou=i=>{if(qo()){clearInterval(i.id);return}m(typeof i.id=="number"),Nn.delete(i.id),jo().postMessage({type:"clear-interval",timerId:i.id})},Vn=i=>new Promise(e=>setTimeout(e,i)),Pr=i=>Array.isArray(i)?i:[i];class fs{constructor(){this._listeners=new Map}on(e,t,r){this._listeners.has(e)||this._listeners.set(e,new Set);const s={fn:t,once:(r==null?void 0:r.once)??!1};return this._listeners.get(e).add(s),()=>{var n;(n=this._listeners.get(e))==null||n.delete(s)}}_emit(...e){const[t,r]=e,s=this._listeners.get(t);if(s)for(const n of s){try{n.fn(r)}catch(a){console.error(a)}n.once&&s.delete(n)}}}const dr=i=>Math.ceil(i/2)*2;class vm{constructor(e){this._queue=[],this._errored=!1,this.parallelism=e}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(e){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);const t=e();this._queue.push(t),t.then(()=>Wo(this._queue,t)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}}const Ko=i=>i!==null&&typeof i=="object"&&Object.getPrototypeOf(i)===Object.prototype&&Object.values(i).every(e=>typeof e=="string");/*!
|
|
8
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
9
|
+
*
|
|
10
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
11
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
12
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
13
|
+
*/class Cr{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(typeof t!="string")throw new TypeError("mimeType must be a string.")}}class On{constructor(e,t,r,s){if(this.data=e,this.mimeType=t,this.name=r,this.description=s,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!==void 0&&typeof t!="string")throw new TypeError("mimeType, when provided, must be a string.");if(r!==void 0&&typeof r!="string")throw new TypeError("name, when provided, must be a string.");if(s!==void 0&&typeof s!="string")throw new TypeError("description, when provided, must be a string.")}}const cn=i=>{if(!i||typeof i!="object")throw new TypeError("tags must be an object.");if(i.title!==void 0&&typeof i.title!="string")throw new TypeError("tags.title, when provided, must be a string.");if(i.description!==void 0&&typeof i.description!="string")throw new TypeError("tags.description, when provided, must be a string.");if(i.artist!==void 0&&typeof i.artist!="string")throw new TypeError("tags.artist, when provided, must be a string.");if(i.album!==void 0&&typeof i.album!="string")throw new TypeError("tags.album, when provided, must be a string.");if(i.albumArtist!==void 0&&typeof i.albumArtist!="string")throw new TypeError("tags.albumArtist, when provided, must be a string.");if(i.trackNumber!==void 0&&(!Number.isInteger(i.trackNumber)||i.trackNumber<=0))throw new TypeError("tags.trackNumber, when provided, must be a positive integer.");if(i.tracksTotal!==void 0&&(!Number.isInteger(i.tracksTotal)||i.tracksTotal<=0))throw new TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(i.discNumber!==void 0&&(!Number.isInteger(i.discNumber)||i.discNumber<=0))throw new TypeError("tags.discNumber, when provided, must be a positive integer.");if(i.discsTotal!==void 0&&(!Number.isInteger(i.discsTotal)||i.discsTotal<=0))throw new TypeError("tags.discsTotal, when provided, must be a positive integer.");if(i.genre!==void 0&&typeof i.genre!="string")throw new TypeError("tags.genre, when provided, must be a string.");if(i.date!==void 0&&(!(i.date instanceof Date)||Number.isNaN(i.date.getTime())))throw new TypeError("tags.date, when provided, must be a valid Date.");if(i.lyrics!==void 0&&typeof i.lyrics!="string")throw new TypeError("tags.lyrics, when provided, must be a string.");if(i.images!==void 0){if(!Array.isArray(i.images))throw new TypeError("tags.images, when provided, must be an array.");for(const e of i.images){if(!e||typeof e!="object")throw new TypeError("Each image in tags.images must be an object.");if(!(e.data instanceof Uint8Array))throw new TypeError("Each image.data must be a Uint8Array.");if(typeof e.mimeType!="string")throw new TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(e.kind))throw new TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(i.comment!==void 0&&typeof i.comment!="string")throw new TypeError("tags.comment, when provided, must be a string.");if(i.raw!==void 0){if(!i.raw||typeof i.raw!="object")throw new TypeError("tags.raw, when provided, must be an object.");for(const e of Object.values(i.raw))if(e!==null&&typeof e!="string"&&!(e instanceof Uint8Array)&&!(e instanceof Cr)&&!(e instanceof On)&&!Ko(e))throw new TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},Si=i=>i.title===void 0&&i.description===void 0&&i.artist===void 0&&i.album===void 0&&i.albumArtist===void 0&&i.trackNumber===void 0&&i.tracksTotal===void 0&&i.discNumber===void 0&&i.discsTotal===void 0&&i.genre===void 0&&i.date===void 0&&i.lyrics===void 0&&(!i.images||i.images.length===0)&&i.comment===void 0&&(i.raw===void 0||Object.keys(i.raw).length===0),Et={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},cu=i=>{if(!i||typeof i!="object")throw new TypeError("disposition must be an object.");if(i.default!==void 0&&typeof i.default!="boolean")throw new TypeError("disposition.default must be a boolean.");if(i.primary!==void 0&&typeof i.primary!="boolean")throw new TypeError("disposition.primary must be a boolean.");if(i.forced!==void 0&&typeof i.forced!="boolean")throw new TypeError("disposition.forced must be a boolean.");if(i.original!==void 0&&typeof i.original!="boolean")throw new TypeError("disposition.original must be a boolean.");if(i.commentary!==void 0&&typeof i.commentary!="boolean")throw new TypeError("disposition.commentary must be a boolean.");if(i.hearingImpaired!==void 0&&typeof i.hearingImpaired!="boolean")throw new TypeError("disposition.hearingImpaired must be a boolean.");if(i.visuallyImpaired!==void 0&&typeof i.visuallyImpaired!="boolean")throw new TypeError("disposition.visuallyImpaired must be a boolean.")};/*!
|
|
14
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
15
|
+
*
|
|
16
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
17
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
18
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
19
|
+
*/class re{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-(this.pos&7),s=(t&1<<r)>>r;return this.pos++,s}readBits(e){if(e===1)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 s=this.pos;s<r;s++){const n=Math.floor(s/8);let a=this.bytes[n];const o=7-(s&7);a&=~(1<<o),a|=(t&1<<r-s-1)>>r-s-1<<o,this.bytes[n]=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 this.bytes.length*8-this.pos}clone(){const e=new re(this.bytes);return e.pos=this.pos,e}}/*!
|
|
20
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
21
|
+
*
|
|
22
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
23
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
24
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
25
|
+
*/const Lt=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Dr=[-1,1,2,3,4,5,6,8],Bi=i=>{if(!i||i.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const e=new re(i);let t=e.readBits(5);t===31&&(t=32+e.readBits(6));const r=e.readBits(4);let s=null;r===15?s=e.readBits(24):r<Lt.length&&(s=Lt[r]);const n=e.readBits(4);let a=null;return n>=1&&n<=7&&(a=Dr[n]),{objectType:t,frequencyIndex:r,sampleRate:s,channelConfiguration:n,numberOfChannels:a}},Wn=i=>{let e=Lt.indexOf(i.sampleRate),t=null;e===-1&&(e=15,t=i.sampleRate);const r=Dr.indexOf(i.numberOfChannels);if(r===-1)throw new TypeError(`Unsupported number of channels: ${i.numberOfChannels}`);let s=13;i.objectType>=32&&(s+=6),e===15&&(s+=24);const n=Math.ceil(s/8),a=new Uint8Array(n),o=new re(a);return i.objectType<32?o.writeBits(5,i.objectType):(o.writeBits(5,31),o.writeBits(6,i.objectType-32)),o.writeBits(4,e),e===15&&o.writeBits(24,t),o.writeBits(4,r),a},Go=i=>{const e=new Uint8Array(7),t=new re(e),{objectType:r,frequencyIndex:s,channelConfiguration:n}=i,a=r-1;return t.writeBits(12,4095),t.writeBits(1,0),t.writeBits(2,0),t.writeBits(1,1),t.writeBits(2,a),t.writeBits(4,s),t.writeBits(1,0),t.writeBits(3,n),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.writeBits(1,0),t.skipBits(13),t.writeBits(11,2047),t.writeBits(2,0),{header:e,bitstream:t}},Qo=(i,e)=>{i.pos=30,i.writeBits(13,e)};/*!
|
|
26
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
27
|
+
*
|
|
28
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
29
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
30
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
31
|
+
*/const Se=["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"],rr=["aac","opus","mp3","vorbis","flac","ac3","eac3"],Ce=[...rr,...Pe],dt=["webvtt"],es=[{maxMacroblocks:99,maxBitrate:64e3,maxDpbMbs:396,level:10},{maxMacroblocks:396,maxBitrate:192e3,maxDpbMbs:900,level:11},{maxMacroblocks:396,maxBitrate:384e3,maxDpbMbs:2376,level:12},{maxMacroblocks:396,maxBitrate:768e3,maxDpbMbs:2376,level:13},{maxMacroblocks:396,maxBitrate:2e6,maxDpbMbs:2376,level:20},{maxMacroblocks:792,maxBitrate:4e6,maxDpbMbs:4752,level:21},{maxMacroblocks:1620,maxBitrate:4e6,maxDpbMbs:8100,level:22},{maxMacroblocks:1620,maxBitrate:1e7,maxDpbMbs:8100,level:30},{maxMacroblocks:3600,maxBitrate:14e6,maxDpbMbs:18e3,level:31},{maxMacroblocks:5120,maxBitrate:2e7,maxDpbMbs:20480,level:32},{maxMacroblocks:8192,maxBitrate:2e7,maxDpbMbs:32768,level:40},{maxMacroblocks:8192,maxBitrate:5e7,maxDpbMbs:32768,level:41},{maxMacroblocks:8704,maxBitrate:5e7,maxDpbMbs:34816,level:42},{maxMacroblocks:22080,maxBitrate:135e6,maxDpbMbs:110400,level:50},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:51},{maxMacroblocks:36864,maxBitrate:24e7,maxDpbMbs:184320,level:52},{maxMacroblocks:139264,maxBitrate:24e7,maxDpbMbs:696320,level:60},{maxMacroblocks:139264,maxBitrate:48e7,maxDpbMbs:696320,level:61},{maxMacroblocks:139264,maxBitrate:8e8,maxDpbMbs:696320,level:62}],Aa=[{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}],Nt=[{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}],xa=[{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}],Pa=".01.01.01.01.00",Ca=".0.110.01.01.01.0",Xo=(i,e,t,r)=>{if(i==="avc"){const n=Math.ceil(e/16)*Math.ceil(t/16),a=es.find(d=>n<=d.maxMacroblocks&&r<=d.maxBitrate)??we(es),o=a?a.level:0,c="64".padStart(2,"0"),u="00",l=o.toString(16).padStart(2,"0");return`avc1.${c}${u}${l}`}else if(i==="hevc"){const o=e*t,c=Aa.find(l=>o<=l.maxPictureSize&&r<=l.maxBitrate)??we(Aa);return`hev1.1.6.${c.tier}${c.level}.B0`}else{if(i==="vp8")return"vp8";if(i==="vp9"){const n=e*t;return`vp09.00.${(Nt.find(c=>n<=c.maxPictureSize&&r<=c.maxBitrate)??we(Nt)).level.toString().padStart(2,"0")}.08`}else if(i==="av1"){const n=e*t,a=xa.find(u=>n<=u.maxPictureSize&&r<=u.maxBitrate)??we(xa);return`av01.0.${a.level.toString().padStart(2,"0")}${a.tier}.08`}}throw new TypeError(`Unhandled codec '${i}'.`)},lu=i=>{const e=i.split("."),t=Number(e[1]),r=Number(e[2]),s=Number(e[3]),n=e[4]?Number(e[4]):1;return[1,1,t,2,1,r,3,1,s,4,1,n]},$o=i=>{const e=i.split("."),s=(1<<7)+1,n=Number(e[1]),a=e[2],o=Number(a.slice(0,-1)),c=(n<<5)+o,u=a.slice(-1)==="H"?1:0,d=Number(e[3])===8?0:1,h=0,p=e[4]?Number(e[4]):0,y=e[5]?Number(e[5][0]):1,f=e[5]?Number(e[5][1]):1,w=e[5]?Number(e[5][2]):0,g=(u<<7)+(d<<6)+(h<<5)+(p<<4)+(y<<3)+(f<<2)+w;return[s,c,g,0]},Ln=i=>{const{codec:e,codecDescription:t,colorSpace:r,avcCodecInfo:s,hevcCodecInfo:n,vp9CodecInfo:a,av1CodecInfo:o}=i;if(e==="avc"){if(m(i.avcType!==null),s){const c=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${i.avcType}.${wi(c)}`}if(!t||t.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${i.avcType}.${wi(t.subarray(1,4))}`}else if(e==="hevc"){let c,u,l,d,h,p;if(n)c=n.generalProfileSpace,u=n.generalProfileIdc,l=wa(n.generalProfileCompatibilityFlags),d=n.generalTierFlag,h=n.generalLevelIdc,p=[...n.generalConstraintIndicatorFlags];else{if(!t||t.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const f=Z(t),w=f.getUint8(1);c=w>>6&3,u=w&31,l=wa(f.getUint32(2)),d=w>>5&1,h=f.getUint8(12),p=[];for(let g=0;g<6;g++)p.push(f.getUint8(6+g))}let y="hev1.";for(y+=["","A","B","C"][c]+u,y+=".",y+=l.toString(16).toUpperCase(),y+=".",y+=d===0?"L":"H",y+=h;p.length>0&&p[p.length-1]===0;)p.pop();return p.length>0&&(y+=".",y+=p.map(f=>f.toString(16).toUpperCase()).join(".")),y}else{if(e==="vp8")return"vp8";if(e==="vp9"){if(!a){const g=i.width*i.height;let b=we(Nt).level;for(const k of Nt)if(g<=k.maxPictureSize){b=k.level;break}return`vp09.00.${b.toString().padStart(2,"0")}.08`}const c=a.profile.toString().padStart(2,"0"),u=a.level.toString().padStart(2,"0"),l=a.bitDepth.toString().padStart(2,"0"),d=a.chromaSubsampling.toString().padStart(2,"0"),h=a.colourPrimaries.toString().padStart(2,"0"),p=a.transferCharacteristics.toString().padStart(2,"0"),y=a.matrixCoefficients.toString().padStart(2,"0"),f=a.videoFullRangeFlag.toString().padStart(2,"0");let w=`vp09.${c}.${u}.${l}.${d}`;return w+=`.${h}.${p}.${y}.${f}`,w.endsWith(Pa)&&(w=w.slice(0,-Pa.length)),w}else if(e==="av1"){if(!o){const k=i.width*i.height;let S=we(Nt).level;for(const A of Nt)if(k<=A.maxPictureSize){S=A.level;break}return`av01.0.${S.toString().padStart(2,"0")}M.08`}const c=o.profile,u=o.level.toString().padStart(2,"0"),l=o.tier?"H":"M",d=o.bitDepth.toString().padStart(2,"0"),h=o.monochrome?"1":"0",p=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),y=r!=null&&r.primaries?ar[r.primaries]:1,f=r!=null&&r.transfer?or[r.transfer]:1,w=r!=null&&r.matrix?cr[r.matrix]:1,g=r!=null&&r.fullRange?1:0;let b=`av01.${c}.${u}${l}.${d}`;return b+=`.${h}.${p.toString().padStart(3,"0")}`,b+=`.${y.toString().padStart(2,"0")}`,b+=`.${f.toString().padStart(2,"0")}`,b+=`.${w.toString().padStart(2,"0")}`,b+=`.${g}`,b.endsWith(Ca)&&(b=b.slice(0,-Ca.length)),b}}throw new TypeError(`Unhandled codec '${e}'.`)},Yo=(i,e,t)=>{if(i==="aac")return e>=2&&t<=24e3?"mp4a.40.29":t<=24e3?"mp4a.40.5":"mp4a.40.2";if(i==="mp3")return"mp3";if(i==="opus")return"opus";if(i==="vorbis")return"vorbis";if(i==="flac")return"flac";if(i==="ac3")return"ac-3";if(i==="eac3")return"ec-3";if(Pe.includes(i))return i;throw new TypeError(`Unhandled codec '${i}'.`)},Hn=i=>{const{codec:e,codecDescription:t,aacCodecInfo:r}=i;if(e==="aac"){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let s;return r.objectType!==null?s=r.objectType:s=Bi(t).objectType,`mp4a.40.${s}`}}else{if(e==="mp3")return"mp3";if(e==="opus")return"opus";if(e==="vorbis")return"vorbis";if(e==="flac")return"flac";if(e==="ac3")return"ac-3";if(e==="eac3")return"ec-3";if(e&&Pe.includes(e))return e}throw new TypeError(`Unhandled codec '${e}'.`)},uu=i=>{},du=i=>{switch(i.codec){case"flac":{const e=Ji("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");return i.sampleRate>=1<<20||i.numberOfChannels>8?!1:(e[18]=i.sampleRate>>>12,e[19]=i.sampleRate>>>4,e[20]=(i.sampleRate&15)<<4|i.numberOfChannels-1<<1,e)}case"vorbis":{const e=Ji("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),t=Z(e);return t.setUint8(15,i.numberOfChannels),t.setUint32(16,i.sampleRate,!0),e}default:return}},zr=48e3,Zo=/^pcm-([usf])(\d+)(be)?$/,st=i=>{if(m(Pe.includes(i)),i==="ulaw")return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if(i==="alaw")return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const e=Zo.exec(i);m(e);let t;e[1]==="u"?t="unsigned":e[1]==="s"?t="signed":t="float";const r=Number(e[2])/8,s=e[3]!=="be",n=i==="pcm-u8"?2**7:0;return{dataType:t,sampleSize:r,littleEndian:s,silentValue:n}},xt=i=>i.startsWith("avc1")||i.startsWith("avc3")?"avc":i.startsWith("hev1")||i.startsWith("hvc1")?"hevc":i==="vp8"?"vp8":i.startsWith("vp09")?"vp9":i.startsWith("av01")?"av1":i==="mp3"||i==="mp4a.69"||i==="mp4a.6B"||i==="mp4a.6b"||i==="mp4a.40.34"?"mp3":i.startsWith("mp4a.40.")||i==="mp4a.67"?"aac":i==="opus"?"opus":i==="vorbis"?"vorbis":i==="flac"?"flac":i==="ac-3"||i==="ac3"?"ac3":i==="ec-3"||i==="eac3"?"eac3":i==="ulaw"?"ulaw":i==="alaw"?"alaw":Zo.test(i)?i:i==="webvtt"?"webvtt":null,hu=i=>i==="avc"?{avc:{format:"avc"}}:i==="hevc"?{hevc:{format:"hevc"}}:{},fu=i=>i==="aac"?{aac:{format:"aac"}}:i==="opus"?{opus:{format:"opus"}}:{},mu=["avc1","avc3","hev1","hvc1","vp8","vp09","av01"],pu=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,gu=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,wu=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,yu=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,ms=i=>{if(!i)throw new TypeError("Video chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Video chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Video chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Video chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!mu.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.codedWidth)||i.decoderConfig.codedWidth<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(i.decoderConfig.codedHeight)||i.decoderConfig.codedHeight<=0)throw new TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(i.decoderConfig.displayAspectWidth!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectWidth)||i.decoderConfig.displayAspectWidth<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectHeight!==void 0&&(!Number.isInteger(i.decoderConfig.displayAspectHeight)||i.decoderConfig.displayAspectHeight<=0))throw new TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(i.decoderConfig.displayAspectWidth!==void 0!=(i.decoderConfig.displayAspectHeight!==void 0))throw new TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(i.decoderConfig.description!==void 0&&!Fr(i.decoderConfig.description))throw new TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.colorSpace!==void 0){const{colorSpace:e}=i.decoderConfig;if(typeof e!="object")throw new TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");const t=Object.keys(ar);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${t.join(", ")}.`);const r=Object.keys(or);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.join(", ")}.`);const s=Object.keys(cr);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(i.decoderConfig.codec.startsWith("avc1")||i.decoderConfig.codec.startsWith("avc3")){if(!pu.test(i.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(i.decoderConfig.codec.startsWith("hev1")||i.decoderConfig.codec.startsWith("hvc1")){if(!gu.test(i.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(i.decoderConfig.codec.startsWith("vp8")){if(i.decoderConfig.codec!=="vp8")throw new TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(i.decoderConfig.codec.startsWith("vp09")){if(!wu.test(i.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(i.decoderConfig.codec.startsWith("av01")&&!yu.test(i.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/.')},bu=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],qt=i=>{if(!i)throw new TypeError("Audio chunk metadata must be provided.");if(typeof i!="object")throw new TypeError("Audio chunk metadata must be an object.");if(!i.decoderConfig)throw new TypeError("Audio chunk metadata must include a decoder configuration.");if(typeof i.decoderConfig!="object")throw new TypeError("Audio chunk metadata decoder configuration must be an object.");if(typeof i.decoderConfig.codec!="string")throw new TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!bu.some(e=>i.decoderConfig.codec.startsWith(e)))throw new TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(i.decoderConfig.sampleRate)||i.decoderConfig.sampleRate<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(i.decoderConfig.numberOfChannels)||i.decoderConfig.numberOfChannels<=0)throw new TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(i.decoderConfig.description!==void 0&&!Fr(i.decoderConfig.description))throw new TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(i.decoderConfig.codec.startsWith("mp4a")&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b"){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(i.decoderConfig.codec))throw new TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("mp3")||i.decoderConfig.codec.startsWith("mp4a")){if(i.decoderConfig.codec!=="mp3"&&i.decoderConfig.codec!=="mp4a.69"&&i.decoderConfig.codec!=="mp4a.6B"&&i.decoderConfig.codec!=="mp4a.6b")throw new TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(i.decoderConfig.codec.startsWith("opus")){if(i.decoderConfig.codec!=="opus")throw new TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(i.decoderConfig.description&&i.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(i.decoderConfig.codec.startsWith("vorbis")){if(i.decoderConfig.codec!=="vorbis")throw new TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!i.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(i.decoderConfig.codec.startsWith("flac")){if(i.decoderConfig.codec!=="flac")throw new TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!i.decoderConfig.description||i.decoderConfig.description.byteLength<42)throw new TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(i.decoderConfig.codec.startsWith("ac-3")||i.decoderConfig.codec.startsWith("ac3")){if(i.decoderConfig.codec!=="ac-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(i.decoderConfig.codec.startsWith("ec-3")||i.decoderConfig.codec.startsWith("eac3")){if(i.decoderConfig.codec!=="ec-3")throw new TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((i.decoderConfig.codec.startsWith("pcm")||i.decoderConfig.codec.startsWith("ulaw")||i.decoderConfig.codec.startsWith("alaw"))&&!Pe.includes(i.decoderConfig.codec))throw new TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${Pe.join(", ")}).`)},Jo=i=>{if(!i)throw new TypeError("Subtitle metadata must be provided.");if(typeof i!="object")throw new TypeError("Subtitle metadata must be an object.");if(!i.config)throw new TypeError("Subtitle metadata must include a config object.");if(typeof i.config!="object")throw new TypeError("Subtitle metadata config must be an object.");if(typeof i.config.description!="string")throw new TypeError("Subtitle metadata config description must be a string.")};/*!
|
|
32
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
33
|
+
*
|
|
34
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
35
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
36
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
37
|
+
*/const ir=4,ku=[44100,48e3,32e3],ln=[-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],ps=1483304551,qn=1231971951,un=(i,e,t,r,s)=>e===0?0:e===1?Math.floor(144*t/(r<<i))+s:e===2?Math.floor(144*t/r)+s:(Math.floor(12*t/r)+s)*4,Tu=(i,e,t,r)=>e===0?0:e===1?144*t/(r<<i):e===2?144*t/r:12*t/r*4,gs=(i,e)=>i===3?e===3?21:36:e===3?13:21,ws=(i,e)=>{const t=i>>>24,r=i>>>16&255,s=i>>>8&255,n=i&255;if(t!==255&&r!==255&&s!==255&&n!==255)return{header:null,bytesAdvanced:4};if(t!==255)return{header:null,bytesAdvanced:1};if((r&224)!==224)return{header:null,bytesAdvanced:1};let a=0,o=0;r&16?a=r&8?0:1:(a=1,o=1);const c=r>>3&3,u=r>>1&3,l=s>>4&15,d=(s>>2&3)%3,h=s>>1&1,p=n>>6&3,y=n>>4&3,f=n>>3&1,w=n>>2&1,g=n&3,b=ln[a*16*4+u*16+l];if(b===-1)return{header:null,bytesAdvanced:1};const k=b*1e3,S=ku[d]>>a+o,A=un(a,u,k,S,h);if(e!==null&&e<A)return{header:null,bytesAdvanced:1};let _;return c===3?_=u===3?384:1152:u===3?_=384:u===2?_=1152:_=576,{header:{totalSize:A,mpegVersionId:c,lowSamplingFrequency:a,layer:u,bitrate:k,frequencyIndex:d,sampleRate:S,channel:p,modeExtension:y,copyright:f,original:w,emphasis:g,audioSamplesInFrame:_},bytesAdvanced:1}},Su=i=>{let e=127,t=0,r=i;for(;(e^2147483647)!==0;)t=r&~e,t<<=1,t|=r&e,e=(e+1<<8)-1,r=t;return t},dn=i=>{let e=2130706432,t=0;for(;e!==0;)t>>=1,t|=i&e,e>>=8;return t};var sr;(function(i){i[i.FrameCount=1]="FrameCount",i[i.FileSize=2]="FileSize",i[i.Toc=4]="Toc"})(sr||(sr={}));/*!
|
|
38
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
39
|
+
*
|
|
40
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
41
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
42
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
43
|
+
*/const ys=[48e3,44100,32e3],ec=[24e3,22050,16e3];/*!
|
|
44
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
45
|
+
*
|
|
46
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
47
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
48
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
49
|
+
*/var Xe;(function(i){i[i.NON_IDR_SLICE=1]="NON_IDR_SLICE",i[i.SLICE_DPA=2]="SLICE_DPA",i[i.SLICE_DPB=3]="SLICE_DPB",i[i.SLICE_DPC=4]="SLICE_DPC",i[i.IDR=5]="IDR",i[i.SEI=6]="SEI",i[i.SPS=7]="SPS",i[i.PPS=8]="PPS",i[i.AUD=9]="AUD",i[i.SPS_EXT=13]="SPS_EXT"})(Xe||(Xe={}));var Te;(function(i){i[i.RASL_N=8]="RASL_N",i[i.RASL_R=9]="RASL_R",i[i.BLA_W_LP=16]="BLA_W_LP",i[i.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",i[i.VPS_NUT=32]="VPS_NUT",i[i.SPS_NUT=33]="SPS_NUT",i[i.PPS_NUT=34]="PPS_NUT",i[i.AUD_NUT=35]="AUD_NUT",i[i.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",i[i.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"})(Te||(Te={}));const Ur=function*(i){let e=0,t=-1;for(;e<i.length-2;){const r=i.indexOf(0,e);if(r===-1||r>=i.length-2)break;e=r;let s=0;if(e+3<i.length&&i[e+1]===0&&i[e+2]===0&&i[e+3]===1?s=4:i[e+1]===0&&i[e+2]===1&&(s=3),s===0){e++;continue}t!==-1&&e>t&&(yield{offset:t,length:e-t}),t=e+s,e=t}t!==-1&&t<i.length&&(yield{offset:t,length:i.length-t})},jn=function*(i,e){let t=0;const r=new DataView(i.buffer,i.byteOffset,i.byteLength);for(;t+e<=i.length;){let s;e===1?s=r.getUint8(t):e===2?s=r.getUint16(t,!1):e===3?s=ds(r,t,!1):(m(e===4),s=r.getUint32(t,!1)),t+=e,yield{offset:t,length:s},t+=s}},tc=(i,e)=>{if(e.description){const s=(he(e.description)[4]&3)+1;return jn(i,s)}else return Ur(i)},Br=i=>i&31,bs=i=>{const e=[],t=i.length;for(let r=0;r<t;r++)r+2<t&&i[r]===0&&i[r+1]===0&&i[r+2]===3?(e.push(0,0),r+=2):e.push(i[r]);return new Uint8Array(e)},zs=new Uint8Array([0,0,0,1]),ts=i=>{const e=i.reduce((s,n)=>s+zs.byteLength+n.byteLength,0),t=new Uint8Array(e);let r=0;for(const s of i)t.set(zs,r),r+=zs.byteLength,t.set(s,r),r+=s.byteLength;return t},Kn=(i,e)=>{const t=i.reduce((n,a)=>n+e+a.byteLength,0),r=new Uint8Array(t);let s=0;for(const n of i){const a=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(e){case 1:a.setUint8(s,n.byteLength);break;case 2:a.setUint16(s,n.byteLength,!1);break;case 3:hs(a,s,n.byteLength,!1);break;case 4:a.setUint32(s,n.byteLength,!1);break}s+=e,r.set(n,s),s+=n.byteLength}return r},Au=(i,e)=>{if(e.description){const s=(he(e.description)[4]&3)+1;return Kn(i,s)}else return ts(i)},Gn=i=>{try{const e=[],t=[],r=[];for(const o of Ur(i)){const c=i.subarray(o.offset,o.offset+o.length),u=Br(c[0]);u===Xe.SPS?e.push(c):u===Xe.PPS?t.push(c):u===Xe.SPS_EXT&&r.push(c)}if(e.length===0||t.length===0)return null;const s=e[0],n=Qn(s);m(n!==null);const a=n.profileIdc===100||n.profileIdc===110||n.profileIdc===122||n.profileIdc===144;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:e,pictureParameterSets:t,chromaFormat:a?n.chromaFormatIdc:null,bitDepthLumaMinus8:a?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(e){return console.error("Error building AVC Decoder Configuration Record:",e),null}},xu=i=>{const e=[];e.push(i.configurationVersion),e.push(i.avcProfileIndication),e.push(i.profileCompatibility),e.push(i.avcLevelIndication),e.push(252|i.lengthSizeMinusOne&3),e.push(224|i.sequenceParameterSets.length&31);for(const t of i.sequenceParameterSets){const r=t.byteLength;e.push(r>>8),e.push(r&255);for(let s=0;s<r;s++)e.push(t[s])}e.push(i.pictureParameterSets.length);for(const t of i.pictureParameterSets){const r=t.byteLength;e.push(r>>8),e.push(r&255);for(let s=0;s<r;s++)e.push(t[s])}if(i.avcProfileIndication===100||i.avcProfileIndication===110||i.avcProfileIndication===122||i.avcProfileIndication===144){m(i.chromaFormat!==null),m(i.bitDepthLumaMinus8!==null),m(i.bitDepthChromaMinus8!==null),m(i.sequenceParameterSetExt!==null),e.push(252|i.chromaFormat&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.sequenceParameterSetExt.length);for(const t of i.sequenceParameterSetExt){const r=t.byteLength;e.push(r>>8),e.push(r&255);for(let s=0;s<r;s++)e.push(t[s])}}return new Uint8Array(e)},rc=i=>{try{const e=Z(i);let t=0;const r=e.getUint8(t++),s=e.getUint8(t++),n=e.getUint8(t++),a=e.getUint8(t++),o=e.getUint8(t++)&3,c=e.getUint8(t++)&31,u=[];for(let p=0;p<c;p++){const y=e.getUint16(t,!1);t+=2,u.push(i.subarray(t,t+y)),t+=y}const l=e.getUint8(t++),d=[];for(let p=0;p<l;p++){const y=e.getUint16(t,!1);t+=2,d.push(i.subarray(t,t+y)),t+=y}const h={configurationVersion:r,avcProfileIndication:s,profileCompatibility:n,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:u,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((s===100||s===110||s===122||s===144)&&t+4<=i.length){const p=e.getUint8(t++)&3,y=e.getUint8(t++)&7,f=e.getUint8(t++)&7,w=e.getUint8(t++);h.chromaFormat=p,h.bitDepthLumaMinus8=y,h.bitDepthChromaMinus8=f;const g=[];for(let b=0;b<w;b++){const k=e.getUint16(t,!1);t+=2,g.push(i.subarray(t,t+k)),t+=k}h.sequenceParameterSetExt=g}return h}catch(e){return console.error("Error deserializing AVC Decoder Configuration Record:",e),null}},ic={1:{num:1,den:1},2:{num:12,den:11},3:{num:10,den:11},4:{num:16,den:11},5:{num:40,den:33},6:{num:24,den:11},7:{num:20,den:11},8:{num:32,den:11},9:{num:80,den:33},10:{num:18,den:11},11:{num:15,den:11},12:{num:64,den:33},13:{num:160,den:99},14:{num:4,den:3},15:{num:3,den:2},16:{num:2,den:1}},Qn=i=>{try{const e=new re(bs(i));if(e.skipBits(1),e.skipBits(2),e.readBits(5)!==7)return null;const r=e.readAlignedByte(),s=e.readAlignedByte(),n=e.readAlignedByte();V(e);let a=1,o=0,c=0,u=0;if((r===100||r===110||r===122||r===244||r===44||r===83||r===86||r===118||r===128)&&(a=V(e),a===3&&(u=e.readBits(1)),o=V(e),c=V(e),e.skipBits(1),e.readBits(1))){for(let R=0;R<(a!==3?8:12);R++)if(e.readBits(1)){const H=R<6?16:64;let q=8,O=8;for(let ee=0;ee<H;ee++){if(O!==0){const ue=At(e);O=(q+ue+256)%256}q=O===0?q:O}}}V(e);const l=V(e);if(l===0)V(e);else if(l===1){e.skipBits(1),At(e),At(e);const M=V(e);for(let R=0;R<M;R++)At(e)}V(e),e.skipBits(1);const d=V(e),h=V(e),p=16*(d+1),y=16*(h+1);let f=p,w=y;const g=e.readBits(1);if(g||e.skipBits(1),e.skipBits(1),e.readBits(1)){const M=V(e),R=V(e),L=V(e),H=V(e);let q,O;if((u===0?a:0)===0)q=1,O=2-g;else{const ue=a===3?1:2,xe=a===1?2:1;q=ue,O=xe*(2-g)}f-=q*(M+R),w-=O*(L+H)}let k=2,S=2,A=2,_=0,I={num:1,den:1},C=null,P=null;if(e.readBits(1)){if(e.readBits(1)){const xe=e.readBits(8);if(xe===255)I={num:e.readBits(16),den:e.readBits(16)};else{const Ue=ic[xe];Ue&&(I=Ue)}}e.readBits(1)&&e.skipBits(1),e.readBits(1)&&(e.skipBits(3),_=e.readBits(1),e.readBits(1)&&(k=e.readBits(8),S=e.readBits(8),A=e.readBits(8))),e.readBits(1)&&(V(e),V(e)),e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.skipBits(1));const O=e.readBits(1);O&&_a(e);const ee=e.readBits(1);ee&&_a(e),(O||ee)&&e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(1),V(e),V(e),V(e),V(e),C=V(e),P=V(e))}if(C===null){m(P===null);const M=s&16;if((r===44||r===86||r===100||r===110||r===122||r===244)&&M)C=0,P=0;else{const R=d+1,L=h+1,H=(2-g)*L,q=es.find(ee=>ee.level>=n)??we(es),O=Math.min(Math.floor(q.maxDpbMbs/(R*H)),16);C=O,P=O}}return m(P!==null),{profileIdc:r,constraintFlags:s,levelIdc:n,frameMbsOnlyFlag:g,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:p,codedHeight:y,displayWidth:f,displayHeight:w,pixelAspectRatio:I,colourPrimaries:k,matrixCoefficients:A,transferCharacteristics:S,fullRangeFlag:_,numReorderFrames:C,maxDecFrameBuffering:P}}catch(e){return console.error("Error parsing AVC SPS:",e),null}},_a=i=>{const e=V(i);i.skipBits(4),i.skipBits(4);for(let t=0;t<=e;t++)V(i),V(i),i.skipBits(1);i.skipBits(5),i.skipBits(5),i.skipBits(5),i.skipBits(5)},Pu=(i,e)=>{if(e.description){const s=(he(e.description)[21]&3)+1;return Kn(i,s)}else return ts(i)},rs=(i,e)=>{if(e.description){const s=(he(e.description)[21]&3)+1;return jn(i,s)}else return Ur(i)},Ht=i=>i>>1&63,sc=i=>{try{const e=new re(bs(i));e.skipBits(16),e.readBits(4);const t=e.readBits(3),r=e.readBits(1),{general_profile_space:s,general_tier_flag:n,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:u}=Cu(e,t);V(e);const l=V(e);let d=0;l===3&&(d=e.readBits(1));const h=V(e),p=V(e);let y=h,f=p;if(e.readBits(1)){const R=V(e),L=V(e),H=V(e),q=V(e);let O=1,ee=1;const ue=d===0?l:0;ue===1?(O=2,ee=2):ue===2&&(O=2,ee=1),y-=(R+L)*O,f-=(H+q)*ee}const w=V(e),g=V(e);V(e);const k=e.readBits(1)?0:t;let S=0;for(let R=k;R<=t;R++)V(e),S=V(e),V(e);V(e),V(e),V(e),V(e),V(e),V(e),e.readBits(1)&&e.readBits(1)&&_u(e),e.skipBits(1),e.skipBits(1),e.readBits(1)&&(e.skipBits(4),e.skipBits(4),V(e),V(e),e.skipBits(1));const A=V(e);if(Iu(e,A),e.readBits(1)){const R=V(e);for(let L=0;L<R;L++)V(e),e.skipBits(1)}e.skipBits(1),e.skipBits(1);let _=2,I=2,C=2,P=0,v=0,M={num:1,den:1};if(e.readBits(1)){const R=vu(e,t);M=R.pixelAspectRatio,_=R.colourPrimaries,I=R.transferCharacteristics,C=R.matrixCoefficients,P=R.fullRangeFlag,v=R.minSpatialSegmentationIdc}return{displayWidth:y,displayHeight:f,pixelAspectRatio:M,colourPrimaries:_,transferCharacteristics:I,matrixCoefficients:C,fullRangeFlag:P,maxDecFrameBuffering:S+1,spsMaxSubLayersMinus1:t,spsTemporalIdNestingFlag:r,generalProfileSpace:s,generalTierFlag:n,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:l,bitDepthLumaMinus8:w,bitDepthChromaMinus8:g,minSpatialSegmentationIdc:v}}catch(e){return console.error("Error parsing HEVC SPS:",e),null}},Xn=i=>{try{const e=[],t=[],r=[],s=[];for(const u of Ur(i)){const l=i.subarray(u.offset,u.offset+u.length),d=Ht(l[0]);d===Te.VPS_NUT?e.push(l):d===Te.SPS_NUT?t.push(l):d===Te.PPS_NUT?r.push(l):(d===Te.PREFIX_SEI_NUT||d===Te.SUFFIX_SEI_NUT)&&s.push(l)}if(t.length===0||r.length===0)return null;const n=sc(t[0]);if(!n)return null;let a=0;if(r.length>0){const u=r[0],l=new re(bs(u));l.skipBits(16),V(l),V(l),l.skipBits(1),l.skipBits(1),l.skipBits(3),l.skipBits(1),l.skipBits(1),V(l),V(l),At(l),l.skipBits(1),l.skipBits(1),l.readBits(1)&&V(l),At(l),At(l),l.skipBits(1),l.skipBits(1),l.skipBits(1),l.skipBits(1);const d=l.readBits(1),h=l.readBits(1);!d&&!h?a=0:d&&!h?a=2:!d&&h?a=3:a=0}const o=[...e.length?[{arrayCompleteness:1,nalUnitType:Te.VPS_NUT,nalUnits:e}]:[],...t.length?[{arrayCompleteness:1,nalUnitType:Te.SPS_NUT,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Te.PPS_NUT,nalUnits:r}]:[],...s.length?[{arrayCompleteness:1,nalUnitType:Ht(s[0][0]),nalUnits:s}]:[]];return{configurationVersion:1,generalProfileSpace:n.generalProfileSpace,generalTierFlag:n.generalTierFlag,generalProfileIdc:n.generalProfileIdc,generalProfileCompatibilityFlags:n.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:n.generalConstraintIndicatorFlags,generalLevelIdc:n.generalLevelIdc,minSpatialSegmentationIdc:n.minSpatialSegmentationIdc,parallelismType:a,chromaFormatIdc:n.chromaFormatIdc,bitDepthLumaMinus8:n.bitDepthLumaMinus8,bitDepthChromaMinus8:n.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:n.spsMaxSubLayersMinus1+1,temporalIdNested:n.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(e){return console.error("Error building HEVC Decoder Configuration Record:",e),null}},Cu=(i,e)=>{const t=i.readBits(2),r=i.readBits(1),s=i.readBits(5);let n=0;for(let l=0;l<32;l++)n=n<<1|i.readBits(1);const a=new Uint8Array(6);for(let l=0;l<6;l++)a[l]=i.readBits(8);const o=i.readBits(8),c=[],u=[];for(let l=0;l<e;l++)c.push(i.readBits(1)),u.push(i.readBits(1));if(e>0)for(let l=e;l<8;l++)i.skipBits(2);for(let l=0;l<e;l++)c[l]&&i.skipBits(88),u[l]&&i.skipBits(8);return{general_profile_space:t,general_tier_flag:r,general_profile_idc:s,general_profile_compatibility_flags:n,general_constraint_indicator_flags:a,general_level_idc:o}},_u=i=>{for(let e=0;e<4;e++)for(let t=0;t<(e===3?2:6);t++)if(!i.readBits(1))V(i);else{const s=Math.min(64,1<<4+(e<<1));e>1&&At(i);for(let n=0;n<s;n++)At(i)}},Iu=(i,e)=>{const t=[];for(let r=0;r<e;r++)t[r]=Eu(i,r,e,t)},Eu=(i,e,t,r)=>{let s=0,n=0,a=0;if(e!==0&&(n=i.readBits(1)),n){if(e===t){const c=V(i);a=e-(c+1)}else a=e-1;i.readBits(1),V(i);const o=r[a]??0;for(let c=0;c<=o;c++)i.readBits(1)||i.readBits(1);s=r[a]}else{const o=V(i),c=V(i);for(let u=0;u<o;u++)V(i),i.readBits(1);for(let u=0;u<c;u++)V(i),i.readBits(1);s=o+c}return s},vu=(i,e)=>{let t=2,r=2,s=2,n=0,a=0,o={num:1,den:1};if(i.readBits(1)){const c=i.readBits(8);if(c===255)o={num:i.readBits(16),den:i.readBits(16)};else{const u=ic[c];u&&(o=u)}}return i.readBits(1)&&i.readBits(1),i.readBits(1)&&(i.readBits(3),n=i.readBits(1),i.readBits(1)&&(t=i.readBits(8),r=i.readBits(8),s=i.readBits(8))),i.readBits(1)&&(V(i),V(i)),i.readBits(1),i.readBits(1),i.readBits(1),i.readBits(1)&&(V(i),V(i),V(i),V(i)),i.readBits(1)&&(i.readBits(32),i.readBits(32),i.readBits(1)&&V(i),i.readBits(1)&&Bu(i,!0,e)),i.readBits(1)&&(i.readBits(1),i.readBits(1),i.readBits(1),a=V(i),V(i),V(i),V(i),V(i)),{pixelAspectRatio:o,colourPrimaries:t,transferCharacteristics:r,matrixCoefficients:s,fullRangeFlag:n,minSpatialSegmentationIdc:a}},Bu=(i,e,t)=>{let r=!1,s=!1,n=!1;r=i.readBits(1)===1,s=i.readBits(1)===1,(r||s)&&(n=i.readBits(1)===1,n&&(i.readBits(8),i.readBits(5),i.readBits(1),i.readBits(5)),i.readBits(4),i.readBits(4),n&&i.readBits(4),i.readBits(5),i.readBits(5),i.readBits(5));for(let a=0;a<=t;a++){const o=i.readBits(1)===1;let c=!0;o||(c=i.readBits(1)===1);let u=!1;c?V(i):u=i.readBits(1)===1;let l=1;u||(l=V(i)+1),r&&Ia(i,l,n),s&&Ia(i,l,n)}},Ia=(i,e,t)=>{for(let r=0;r<e;r++)V(i),V(i),t&&(V(i),V(i)),i.readBits(1)},Fu=i=>{const e=[];e.push(i.configurationVersion),e.push((i.generalProfileSpace&3)<<6|(i.generalTierFlag&1)<<5|i.generalProfileIdc&31),e.push(i.generalProfileCompatibilityFlags>>>24&255),e.push(i.generalProfileCompatibilityFlags>>>16&255),e.push(i.generalProfileCompatibilityFlags>>>8&255),e.push(i.generalProfileCompatibilityFlags&255),e.push(...i.generalConstraintIndicatorFlags),e.push(i.generalLevelIdc&255),e.push(240|i.minSpatialSegmentationIdc>>8&15),e.push(i.minSpatialSegmentationIdc&255),e.push(252|i.parallelismType&3),e.push(252|i.chromaFormatIdc&3),e.push(248|i.bitDepthLumaMinus8&7),e.push(248|i.bitDepthChromaMinus8&7),e.push(i.avgFrameRate>>8&255),e.push(i.avgFrameRate&255),e.push((i.constantFrameRate&3)<<6|(i.numTemporalLayers&7)<<3|(i.temporalIdNested&1)<<2|i.lengthSizeMinusOne&3),e.push(i.arrays.length&255);for(const t of i.arrays){e.push((t.arrayCompleteness&1)<<7|0|t.nalUnitType&63),e.push(t.nalUnits.length>>8&255),e.push(t.nalUnits.length&255);for(const r of t.nalUnits){e.push(r.length>>8&255),e.push(r.length&255);for(let s=0;s<r.length;s++)e.push(r[s])}}return new Uint8Array(e)},Ru=i=>{try{const e=Z(i);let t=0;const r=e.getUint8(t++),s=e.getUint8(t++),n=s>>6&3,a=s>>5&1,o=s&31,c=e.getUint32(t,!1);t+=4;const u=i.subarray(t,t+6);t+=6;const l=e.getUint8(t++),d=(e.getUint8(t++)&15)<<8|e.getUint8(t++),h=e.getUint8(t++)&3,p=e.getUint8(t++)&3,y=e.getUint8(t++)&7,f=e.getUint8(t++)&7,w=e.getUint16(t,!1);t+=2;const g=e.getUint8(t++),b=g>>6&3,k=g>>3&7,S=g>>2&1,A=g&3,_=e.getUint8(t++),I=[];for(let C=0;C<_;C++){const P=e.getUint8(t++),v=P>>7&1,M=P&63,R=e.getUint16(t,!1);t+=2;const L=[];for(let H=0;H<R;H++){const q=e.getUint16(t,!1);t+=2,L.push(i.subarray(t,t+q)),t+=q}I.push({arrayCompleteness:v,nalUnitType:M,nalUnits:L})}return{configurationVersion:r,generalProfileSpace:n,generalTierFlag:a,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:u,generalLevelIdc:l,minSpatialSegmentationIdc:d,parallelismType:h,chromaFormatIdc:p,bitDepthLumaMinus8:y,bitDepthChromaMinus8:f,avgFrameRate:w,constantFrameRate:b,numTemporalLayers:k,temporalIdNested:S,lengthSizeMinusOne:A,arrays:I}}catch(e){return console.error("Error deserializing HEVC Decoder Configuration Record:",e),null}};var Re;(function(i){i[i.audAllowed=0]="audAllowed",i[i.beforeFirstVcl=1]="beforeFirstVcl",i[i.afterFirstVcl=2]="afterFirstVcl",i[i.eoBitstreamAllowed=3]="eoBitstreamAllowed",i[i.noMoreDataAllowed=4]="noMoreDataAllowed"})(Re||(Re={}));const Mu=(i,e)=>{const t=new Set;let r=Re.audAllowed;for(const n of rs(i,e)){if(r===Re.noMoreDataAllowed){t.add(n.offset);continue}const a=Ht(i[n.offset]);if(r===Re.eoBitstreamAllowed&&a!==37){t.add(n.offset);continue}let o=!1;a===35?r>Re.audAllowed?o=!0:r=Re.beforeFirstVcl:a<=31?r>Re.afterFirstVcl?o=!0:r=Re.afterFirstVcl:a===36?r!==Re.afterFirstVcl?o=!0:r=Re.eoBitstreamAllowed:a===37?r<Re.afterFirstVcl?o=!0:r=Re.noMoreDataAllowed:a===32||a===33||a===34||a===39||a>=41&&a<=44||a>=48&&a<=55?r>Re.beforeFirstVcl?o=!0:r=Re.beforeFirstVcl:(a===38||a===40||a>=45&&a<=47||a>=56&&a<=63)&&r<Re.afterFirstVcl&&(o=!0),o&&t.add(n.offset)}if(t.size===0)return null;const s=[];for(const n of rs(i,e))t.has(n.offset)||s.push(i.subarray(n.offset,n.offset+n.length));return Pu(s,e)},nc=i=>{const e=new re(i);if(e.readBits(2)!==2)return null;const r=e.readBits(1),n=(e.readBits(1)<<1)+r;if(n===3&&e.skipBits(1),e.readBits(1)===1||e.readBits(1)!==0||(e.skipBits(2),e.readBits(24)!==4817730))return null;let u=8;n>=2&&(u=e.readBits(1)?12:10);const l=e.readBits(3);let d=0,h=0;if(l!==7)if(h=e.readBits(1),n===1||n===3){const I=e.readBits(1),C=e.readBits(1);d=!I&&!C?3:I&&!C?2:1,e.skipBits(1)}else d=1;else d=3,h=1;const p=e.readBits(16),y=e.readBits(16),f=p+1,w=y+1,g=f*w;let b=we(Nt).level;for(const _ of Nt)if(g<=_.maxPictureSize){b=_.level;break}return{profile:n,level:b,bitDepth:u,chromaSubsampling:d,videoFullRangeFlag:h,colourPrimaries:l===2?1:l===1?6:2,transferCharacteristics:l===2?1:l===1?6:2,matrixCoefficients:l===7?0:l===2?1:l===1?6:2}},ac=function*(i){const e=new re(i),t=()=>{let r=0;for(let s=0;s<8;s++){const n=e.readAlignedByte();if(r|=(n&127)<<s*7,!(n&128))break;if(s===7&&n&128)return null}return r>=2**32-1?null:r};for(;e.getBitsLeft()>=8;){e.skipBits(1);const r=e.readBits(4),s=e.readBits(1),n=e.readBits(1);e.skipBits(1),s&&e.skipBits(8);let a;if(n){const o=t();if(o===null)return;a=o}else a=Math.floor(e.getBitsLeft()/8);m(e.pos%8===0),yield{type:r,data:i.subarray(e.pos/8,e.pos/8+a)},e.skipBits(a*8)}},oc=i=>{for(const{type:e,data:t}of ac(i)){if(e!==1)continue;const r=new re(t),s=r.readBits(3);r.readBits(1);const n=r.readBits(1);let a=0,o=0,c=0;if(n)a=r.readBits(5);else{if(r.readBits(1)&&(r.skipBits(32),r.skipBits(32),r.readBits(1)))return null;const A=r.readBits(1);A&&(c=r.readBits(5),r.skipBits(32),r.skipBits(5),r.skipBits(5));const _=r.readBits(5);for(let I=0;I<=_;I++){r.skipBits(12);const C=r.readBits(5);if(I===0&&(a=C),C>7){const v=r.readBits(1);I===0&&(o=v)}if(A&&r.readBits(1)){const M=c+1;r.skipBits(M),r.skipBits(M),r.skipBits(1)}r.readBits(1)&&r.skipBits(4)}}const u=r.readBits(4),l=r.readBits(4),d=u+1;r.skipBits(d);const h=l+1;r.skipBits(h);let p=0;if(n?p=0:p=r.readBits(1),p&&(r.skipBits(4),r.skipBits(3)),r.skipBits(1),r.skipBits(1),r.skipBits(1),!n){r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const S=r.readBits(1);S&&(r.skipBits(1),r.skipBits(1));const A=r.readBits(1);let _=0;A?_=2:_=r.readBits(1),_>0&&(r.readBits(1)||r.skipBits(1)),S&&r.skipBits(3)}r.skipBits(1),r.skipBits(1),r.skipBits(1);const y=r.readBits(1);let f=8;s===2&&y?f=r.readBits(1)?12:10:s<=2&&(f=y?10:8);let w=0;s!==1&&(w=r.readBits(1));let g=1,b=1,k=0;return w||(s===0?(g=1,b=1):s===1?(g=0,b=0):f===12&&(g=r.readBits(1),g&&(b=r.readBits(1))),g&&b&&(k=r.readBits(2))),{profile:s,level:a,tier:o,bitDepth:f,monochrome:w,chromaSubsamplingX:g,chromaSubsamplingY:b,chromaSamplePosition:k}}return null},ks=i=>{const e=Z(i),t=e.getUint8(9),r=e.getUint16(10,!0),s=e.getUint32(12,!0),n=e.getInt16(16,!0),a=e.getUint8(18);let o=null;return a&&(o=i.subarray(19,21+t)),{outputChannelCount:t,preSkip:r,inputSampleRate:s,outputGain:n,channelMappingFamily:a,channelMappingTable:o}},Du=[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],zu=i=>{const e=i[0]>>3;return{durationInSamples:Du[e]}},cc=i=>{if(i.length<7)throw new Error("Setup header is too short.");if(i[0]!==5)throw new Error("Wrong packet type in Setup header.");if(String.fromCharCode(...i.slice(1,7))!=="vorbis")throw new Error("Invalid packet signature in Setup header.");const t=i.length,r=new Uint8Array(t);for(let d=0;d<t;d++)r[d]=i[t-1-d];const s=new re(r);let n=0;for(;s.getBitsLeft()>97;)if(s.readBits(1)===1){n=s.pos;break}if(n===0)throw new Error("Invalid Setup header: framing bit not found.");let a=0,o=!1,c=0;for(;s.getBitsLeft()>=97;){const d=s.pos,h=s.readBits(8),p=s.readBits(16),y=s.readBits(16);if(h>63||p!==0||y!==0){s.pos=d;break}if(s.skipBits(1),a++,a>64)break;s.clone().readBits(6)+1===a&&(o=!0,c=a)}if(!o)throw new Error("Invalid Setup header: mode header not found.");if(c>63)throw new Error(`Unsupported mode count: ${c}.`);const u=c;s.pos=0,s.skipBits(n);const l=Array(u).fill(0);for(let d=u-1;d>=0;d--)s.skipBits(40),l[d]=s.readBits(1);return{modeBlockflags:l}},Ts=(i,e,t)=>{switch(i){case"avc":{for(const r of tc(t,e)){const s=t[r.offset],n=Br(s);if(n>=Xe.NON_IDR_SLICE&&n<=Xe.SLICE_DPC)return"delta";if(n===Xe.IDR)return"key";if(n===Xe.SEI&&(!an()||eu()>=144)){const a=t.subarray(r.offset,r.offset+r.length),o=bs(a);let c=1;do{let u=0;for(;;){const h=o[c++];if(h===void 0||(u+=h,h<255))break}let l=0;for(;;){const h=o[c++];if(h===void 0||(l+=h,h<255))break}if(u===6){const h=new re(o);h.pos=8*c;const p=V(h),y=h.readBits(1);if(p===0&&y===1)return"key"}c+=l}while(c<o.length-1)}}return"delta"}case"hevc":{for(const r of rs(t,e)){const s=Ht(t[r.offset]);if(s<Te.BLA_W_LP)return"delta";if(s<=Te.RSV_IRAP_VCL23)return"key"}return"delta"}case"vp8":return(t[0]&1)===0?"key":"delta";case"vp9":{const r=new re(t);if(r.readBits(2)!==2)return null;const s=r.readBits(1);return(r.readBits(1)<<1)+s===3&&r.skipBits(1),r.readBits(1)?null:r.readBits(1)===0?"key":"delta"}case"av1":{let r=!1;for(const{type:s,data:n}of ac(t))if(s===1){const a=new re(n);a.skipBits(4),r=!!a.readBits(1)}else if(s===3||s===6||s===7){if(r)return"key";const a=new re(n);return a.readBits(1)?null:a.readBits(2)===0?"key":"delta"}return null}default:De(i),m(!1)}};var Pt;(function(i){i[i.STREAMINFO=0]="STREAMINFO",i[i.VORBIS_COMMENT=4]="VORBIS_COMMENT",i[i.PICTURE=6]="PICTURE"})(Pt||(Pt={}));const hn=(i,e)=>{var o,c;const t=Z(i);let r=0;const s=t.getUint32(r,!0);r+=4;const n=qe.decode(i.subarray(r,r+s));r+=s,s>0&&(e.raw??(e.raw={}),(o=e.raw).vendor??(o.vendor=n));const a=t.getUint32(r,!0);r+=4;for(let u=0;u<a;u++){const l=t.getUint32(r,!0);r+=4;const d=qe.decode(i.subarray(r,r+l));r+=l;const h=d.indexOf("=");if(h===-1)continue;const p=d.slice(0,h).toUpperCase(),y=d.slice(h+1);switch(e.raw??(e.raw={}),(c=e.raw)[p]??(c[p]=y),p){case"TITLE":e.title??(e.title=y);break;case"DESCRIPTION":e.description??(e.description=y);break;case"ARTIST":e.artist??(e.artist=y);break;case"ALBUM":e.album??(e.album=y);break;case"ALBUMARTIST":e.albumArtist??(e.albumArtist=y);break;case"COMMENT":e.comment??(e.comment=y);break;case"LYRICS":e.lyrics??(e.lyrics=y);break;case"TRACKNUMBER":{const f=y.split("/"),w=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(w)&&w>0&&(e.trackNumber??(e.trackNumber=w)),g&&Number.isInteger(g)&&g>0&&(e.tracksTotal??(e.tracksTotal=g))}break;case"TRACKTOTAL":{const f=Number.parseInt(y,10);Number.isInteger(f)&&f>0&&(e.tracksTotal??(e.tracksTotal=f))}break;case"DISCNUMBER":{const f=y.split("/"),w=Number.parseInt(f[0],10),g=f[1]&&Number.parseInt(f[1],10);Number.isInteger(w)&&w>0&&(e.discNumber??(e.discNumber=w)),g&&Number.isInteger(g)&&g>0&&(e.discsTotal??(e.discsTotal=g))}break;case"DISCTOTAL":{const f=Number.parseInt(y,10);Number.isInteger(f)&&f>0&&(e.discsTotal??(e.discsTotal=f))}break;case"DATE":{const f=new Date(y);Number.isNaN(f.getTime())||(e.date??(e.date=f))}break;case"GENRE":e.genre??(e.genre=y);break;case"METADATA_BLOCK_PICTURE":{const f=Ji(y),w=Z(f),g=w.getUint32(0,!1),b=w.getUint32(4,!1),k=String.fromCharCode(...f.subarray(8,8+b)),S=w.getUint32(8+b,!1),A=qe.decode(f.subarray(12+b,12+b+S)),_=w.getUint32(b+S+28),I=f.subarray(b+S+32,b+S+32+_);e.images??(e.images=[]),e.images.push({data:I,mimeType:k,kind:g===3?"coverFront":g===4?"coverBack":"unknown",name:void 0,description:A||void 0})}break}}},fn=(i,e,t)=>{var y,f;const r=[i],n=le.encode("Mediabunny");let a=new Uint8Array(4+n.length),o=new DataView(a.buffer);o.setUint32(0,n.length,!0),a.set(n,4),r.push(a);const c=new Set,u=(w,g)=>{const b=`${w}=${g}`,k=le.encode(b);a=new Uint8Array(4+k.length),o=new DataView(a.buffer),o.setUint32(0,k.length,!0),a.set(k,4),r.push(a),c.add(w)};for(const{key:w,value:g}of Rr(e))switch(w){case"title":u("TITLE",g);break;case"description":u("DESCRIPTION",g);break;case"artist":u("ARTIST",g);break;case"album":u("ALBUM",g);break;case"albumArtist":u("ALBUMARTIST",g);break;case"genre":u("GENRE",g);break;case"date":{const b=((y=e.raw)==null?void 0:y.DATE)??((f=e.raw)==null?void 0:f.date);b&&typeof b=="string"?u("DATE",b):u("DATE",g.toISOString().slice(0,10))}break;case"comment":u("COMMENT",g);break;case"lyrics":u("LYRICS",g);break;case"trackNumber":u("TRACKNUMBER",g.toString());break;case"tracksTotal":u("TRACKTOTAL",g.toString());break;case"discNumber":u("DISCNUMBER",g.toString());break;case"discsTotal":u("DISCTOTAL",g.toString());break;case"images":{if(!t)break;for(const b of g){const k=b.kind==="coverFront"?3:b.kind==="coverBack"?4:0,S=new Uint8Array(b.mimeType.length);for(let P=0;P<b.mimeType.length;P++)S[P]=b.mimeType.charCodeAt(P);const A=le.encode(b.description??""),_=new Uint8Array(8+S.length+4+A.length+16+4+b.data.length),I=Z(_);I.setUint32(0,k,!1),I.setUint32(4,S.length,!1),_.set(S,8),I.setUint32(8+S.length,A.length,!1),_.set(A,12+S.length),I.setUint32(28+S.length+A.length,b.data.length,!1),_.set(b.data,32+S.length+A.length);const C=ru(_);u("METADATA_BLOCK_PICTURE",C)}}break;case"raw":break;default:De(w)}if(e.raw)for(const w in e.raw){const g=e.raw[w]??e.raw[w.toLowerCase()];w==="vendor"||g==null||c.has(w)||typeof g=="string"&&u(w,g)}const l=new Uint8Array(4);Z(l).setUint32(0,c.size,!0),r.splice(2,0,l);const d=r.reduce((w,g)=>w+g.length,0),h=new Uint8Array(d);let p=0;for(const w of r)h.set(w,p),p+=w.length;return h},$n=[2,1,2,3,3,4,4,5],lc=i=>{if(i.length<7||i[0]!==11||i[1]!==119)return null;const e=new re(i);e.skipBits(16),e.skipBits(16);const t=e.readBits(2);if(t===3)return null;const r=e.readBits(6),s=e.readBits(5);if(s>8)return null;const n=e.readBits(3),a=e.readBits(3);(a&1)!==0&&a!==1&&e.skipBits(2),(a&4)!==0&&e.skipBits(2),a===2&&e.skipBits(2);const o=e.readBits(1),c=Math.floor(r/2);return{fscod:t,bsid:s,bsmod:n,acmod:a,lfeon:o,bitRateCode:c}},Uu=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,288*2,384,418,288*2,448,486,336*2,448,488,336*2,256*2,278*2,384*2,256*2,279*2,384*2,320*2,348*2,480*2,320*2,349*2,480*2,384*2,417*2,576*2,384*2,418*2,576*2,448*2,487*2,672*2,448*2,488*2,672*2,512*2,557*2,768*2,512*2,558*2,768*2,640*2,696*2,960*2,640*2,697*2,960*2,768*2,835*2,1152*2,768*2,836*2,1152*2,896*2,975*2,1344*2,896*2,976*2,1344*2,1024*2,1114*2,1536*2,1024*2,1115*2,1536*2,1152*2,1253*2,1728*2,1152*2,1254*2,1728*2,1280*2,1393*2,1920*2,1280*2,1394*2,1920*2],Nu=1536,zi=new Uint8Array([5,4,65,67,45,51]),Ui=new Uint8Array([5,4,69,65,67,51]),uc=[1,2,3,6],dc=i=>{if(i.length<6||i[0]!==11||i[1]!==119)return null;const e=new re(i);e.skipBits(16);const t=e.readBits(2);if(e.skipBits(3),t!==0&&t!==2)return null;const r=e.readBits(11),s=e.readBits(2);let n=0,a;s===3?(n=e.readBits(2),a=3):a=e.readBits(2);const o=e.readBits(3),c=e.readBits(1),u=e.readBits(5);if(u<11||u>16)return null;const l=uc[a];let d;return s<3?d=ys[s]/1e3:d=ec[n]/1e3,{dataRate:Math.round((r+1)*d/(l*16)),substreams:[{fscod:s,fscod2:n,bsid:u,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},Vu=i=>{if(i.length<2)return null;const e=new re(i),t=e.readBits(13),r=e.readBits(3),s=[];for(let n=0;n<=r&&!(Math.ceil(e.pos/8)+3>i.length);n++){const a=e.readBits(2),o=e.readBits(5);e.skipBits(1),e.skipBits(1);const c=e.readBits(3),u=e.readBits(3),l=e.readBits(1);e.skipBits(3);const d=e.readBits(4);let h=0;d>0?h=e.readBits(9):e.skipBits(1),s.push({fscod:a,fscod2:null,bsid:o,bsmod:c,acmod:u,lfeon:l,numDepSub:d,chanLoc:h})}return s.length===0?null:{dataRate:t,substreams:s}},hc=i=>{const e=i.substreams[0];return m(e),e.fscod<3?ys[e.fscod]:e.fscod2!==null&&e.fscod2<3?ec[e.fscod2]:null},fc=i=>{const e=i.substreams[0];m(e);let t=$n[e.acmod]+e.lfeon;if(e.numDepSub>0){const r=[2,2,1,1,2,2,2,1,1];for(let s=0;s<9;s++)e.chanLoc&1<<8-s&&(t+=r[s])}return t};/*!
|
|
50
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
51
|
+
*
|
|
52
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
53
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
54
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
55
|
+
*/class vt{constructor(e){this.input=e}dispose(){}}/*!
|
|
56
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
57
|
+
*
|
|
58
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
59
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
60
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
61
|
+
*/const je=new Uint8Array(0);class de{constructor(e,t,r,s,n=-1,a,o){if(this.data=e,this.type=t,this.timestamp=r,this.duration=s,this.sequenceNumber=n,e===je&&a===void 0)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(a===void 0&&(a=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(t!=="key"&&t!=="delta")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(s)||s<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(n))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(a)||a<0)throw new TypeError("byteLength must be a non-negative integer.");if(o!==void 0&&(typeof o!="object"||!o))throw new TypeError("sideData, when provided, must be an object.");if((o==null?void 0:o.alpha)!==void 0&&!(o.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if((o==null?void 0:o.alphaByteLength)!==void 0&&(!Number.isInteger(o.alphaByteLength)||o.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=a,this.sideData=o??{},this.sideData.alpha&&this.sideData.alphaByteLength===void 0&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===je}get microsecondTimestamp(){return Math.trunc(Ut*this.timestamp)}get microsecondDuration(){return Math.trunc(Ut*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if(typeof EncodedVideoChunk>"u")throw new Error("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(typeof EncodedVideoChunk>"u")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(typeof EncodedAudioChunk>"u")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 de(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(e!==void 0&&(typeof e!="object"||e===null))throw new TypeError("options, when provided, must be an object.");if((e==null?void 0:e.data)!==void 0&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if((e==null?void 0:e.type)!==void 0&&e.type!=="key"&&e.type!=="delta")throw new TypeError('options.type, when provided, must be either "key" or "delta".');if((e==null?void 0:e.timestamp)!==void 0&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if((e==null?void 0:e.duration)!==void 0&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if((e==null?void 0:e.sequenceNumber)!==void 0&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if((e==null?void 0:e.sideData)!==void 0&&(typeof e.sideData!="object"||e.sideData===null))throw new TypeError("options.sideData, when provided, must be an object.");return new de((e==null?void 0:e.data)??this.data,(e==null?void 0:e.type)??this.type,(e==null?void 0:e.timestamp)??this.timestamp,(e==null?void 0:e.duration)??this.duration,(e==null?void 0:e.sequenceNumber)??this.sequenceNumber,this.byteLength,(e==null?void 0:e.sideData)??this.sideData)}}/*!
|
|
62
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
63
|
+
*
|
|
64
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
65
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
66
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
67
|
+
*/const mc=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isQuickTime?"quicktime":"mp4");if(i.codecStrings.length>0){const r=[...new Set(i.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t},pc=i=>{const e=Z(i);let t=0;const r=e.getUint8(t);t+=1,t+=3;const s=wi(i.subarray(t,t+16));t+=16;let n=null;if(r>0){const o=e.getUint32(t);if(t+=4,o>0){n=[];for(let c=0;c<o;c++)n.push(wi(i.subarray(t,t+16))),t+=16}}const a=e.getUint32(t);return t+=4,{systemId:s,keyIds:n,data:i.slice(t,t+a)}},gc=(i,e)=>i.systemId===e.systemId&&Ho(i.data,e.data);/*!
|
|
68
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
69
|
+
*
|
|
70
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
71
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
72
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
73
|
+
*/const kt=8,Jt=16,Dt=i=>{let e=U(i);const t=ye(i,4);let r=8;e===1&&(e=Ge(i),r=16);const n=e-r;return n<0?null:{name:t,totalSize:e,headerSize:r,contentSize:n}},jt=i=>tr(i)/65536,Us=i=>tr(i)/1073741824,Ns=i=>{let e=0;for(let t=0;t<4;t++){e<<=7;const r=j(i);if(e|=r&127,(r&128)===0)break}return e},ot=i=>{let e=ke(i);return i.skip(2),e=Math.min(e,i.remainingLength),qe.decode(K(i,e))},Ou=i=>{const e=Dt(i);if(!e||e.name!=="data"||i.remainingLength<8)return null;const t=U(i);i.skip(4);const r=K(i,e.contentSize-8);switch(t){case 1:return qe.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Cr(r,"image/jpeg");case 14:return new Cr(r,"image/png");case 27:return new Cr(r,"image/bmp");default:return r}};/*!
|
|
74
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
75
|
+
*
|
|
76
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
77
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
78
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
79
|
+
*/const ut=16,gt=new Uint32Array(256),pr=new Uint32Array(256),gr=new Uint32Array(256),wr=new Uint32Array(256),yr=new Uint32Array(256),Be=new Uint32Array(256),wc=new Uint32Array(10);let yc=!1;const Wu=()=>{const i=new Uint8Array(256),e=new Uint8Array(256),t=new Uint8Array(256);for(let n=0,a=1;n<256;n++)t[n]=a,e[a]=n,a=a^a<<1^(a&128?283:0);const r=(n,a)=>n&&a?t[(e[n]+e[a])%255]:0;i[0]=99;for(let n=1;n<256;n++){const a=t[255-e[n]];let o=a^a<<1^a<<2^a<<3^a<<4;o=o>>>8^o&255^99,i[n]=o}for(let n=0;n<256;n++){const a=i[n],o=i.indexOf(n);gt[n]=a<<24|a<<16|a<<8|a,Be[n]=o<<24|o<<16|o<<8|o;const c=r(o,14),u=r(o,9),l=r(o,13),d=r(o,11),h=c<<24|u<<16|l<<8|d;pr[n]=h,gr[n]=h>>>8|h<<24,wr[n]=h>>>16|h<<16,yr[n]=h>>>24|h<<8}let s=1;for(let n=0;n<10;n++)wc[n]=s<<24,s=s<<1^(s&128?283:0);yc=!0};class bc{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(ut/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(ut),this.out=new Uint8Array(ut),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){m(e.byteLength===16),m(t.byteLength===16),yc||Wu();const r=new DataView(e.buffer,e.byteOffset,e.byteLength),s=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=s.getUint32(0,!1),this.iv[1]=s.getUint32(4,!1),this.iv[2]=s.getUint32(8,!1),this.iv[3]=s.getUint32(12,!1);for(let n=4;n<44;n+=4){const a=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^gt[a>>>16&255]&4278190080^gt[a>>>8&255]&16711680^gt[a>>>0&255]&65280^gt[a>>>24&255]&255^wc[n/4-1],this.roundkey[n+1]=this.roundkey[n-3]^this.roundkey[n],this.roundkey[n+2]=this.roundkey[n-2]^this.roundkey[n+1],this.roundkey[n+3]=this.roundkey[n-1]^this.roundkey[n+2]}for(let n=0,a=40;n<a;n+=4,a-=4)for(let o=0;o<4;o++){const c=this.roundkey[n+o];this.roundkey[n+o]=this.roundkey[a+o],this.roundkey[a+o]=c}for(let n=4;n<40;n+=4)for(let a=0;a<4;a++){const o=this.roundkey[n+a];this.roundkey[n+a]=pr[gt[o>>>24&255]&255]^gr[gt[o>>>16&255]&255]^wr[gt[o>>>8&255]&255]^yr[gt[o>>>0&255]&255]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],r=this.inView.getUint32(8,!1)^this.roundkey[2],s=this.inView.getUint32(12,!1)^this.roundkey[3];const n=this.inView.getUint32(0,!1),a=this.inView.getUint32(4,!1),o=this.inView.getUint32(8,!1),c=this.inView.getUint32(12,!1);let u,l,d,h;for(let g=1;g<10;g++){const b=g*4;u=pr[e>>>24]^gr[s>>>16&255]^wr[r>>>8&255]^yr[t&255]^this.roundkey[b],l=pr[t>>>24]^gr[e>>>16&255]^wr[s>>>8&255]^yr[r&255]^this.roundkey[b+1],d=pr[r>>>24]^gr[t>>>16&255]^wr[e>>>8&255]^yr[s&255]^this.roundkey[b+2],h=pr[s>>>24]^gr[r>>>16&255]^wr[t>>>8&255]^yr[e&255]^this.roundkey[b+3],e=u,t=l,r=d,s=h}const p=Be[e>>>24&255]&4278190080^Be[s>>>16&255]&16711680^Be[r>>>8&255]&65280^Be[t>>>0&255]&255^this.roundkey[40],y=Be[t>>>24&255]&4278190080^Be[e>>>16&255]&16711680^Be[s>>>8&255]&65280^Be[r>>>0&255]&255^this.roundkey[41],f=Be[r>>>24&255]&4278190080^Be[t>>>16&255]&16711680^Be[e>>>8&255]&65280^Be[s>>>0&255]&255^this.roundkey[42],w=Be[s>>>24&255]&4278190080^Be[r>>>16&255]&16711680^Be[t>>>8&255]&65280^Be[e>>>0&255]&255^this.roundkey[43];this.outView.setUint32(0,p^this.iv[0],!1),this.outView.setUint32(4,y^this.iv[1],!1),this.outView.setUint32(8,f^this.iv[2],!1),this.outView.setUint32(12,w^this.iv[3],!1),this.iv[0]=n,this.iv[1]=a,this.iv[2]=o,this.iv[3]=c}}const Lu=(i,e,t)=>{let r=!1,s=0;const n=2**16,a=16,o=new bc;return new ReadableStream({pull:async c=>{r||(o.init(await e()),r=!0);const u=n+a;let l=i.requestSliceRange(s,0,u);if(l instanceof Promise&&(l=await l),!l||l.length===0)throw new Error("Invalid ciphertext.");const d=l.length;if(d%16!==0)throw new Error("Invalid ciphertext.");const h=d===u?d-a:d,p=K(l,h),y=new Uint8Array(h);for(let f=0;f<h;f+=16)o.in.set(p.subarray(f,f+16)),o.decrypt(),y.set(o.out,f);if(h<d)c.enqueue(y),s+=h;else{const f=y[h-1];if(f===0||f>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const w=y.subarray(0,h-f);c.enqueue(w),c.close(),t()}},cancel:()=>{t()}})};/*!
|
|
80
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
81
|
+
*
|
|
82
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
83
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
84
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
85
|
+
*/class Yn extends vt{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(r=>r.getDecoderConfig().then(s=>(s==null?void 0:s.codec)??null)));return mc({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(r=>{var s;return((s=r.info)==null?void 0:s.type)==="video"}),hasAudio:this.tracks.some(r=>{var s;return((s=r.info)==null?void 0:s.type)==="audio"}),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1;for(;;){let r=this.reader.requestSliceRange(e,kt,Jt);if(r instanceof Promise&&(r=await r),!r)break;const s=e,n=Dt(r);if(!n)break;if(n.name==="ftyp"||n.name==="styp"){const a=ye(r,4);this.isQuickTime=a==="qt "}else if(n.name==="moov"){let a=this.reader.requestSlice(r.filePos,n.contentSize);if(a instanceof Promise&&(a=await a),!a)break;this.moovSlice=a,this.readContiguousBoxes(this.moovSlice);for(const o of this.tracks){const c=o.editListPreviousSegmentDurations/this.movieTimescale;o.editListOffset-=Math.round(c*o.timescale)}t=this.isFragmented&&this.reader.fileSize!==null&&this.reader.fileSize>s+n.totalSize;break}else if(n.name==="moof"){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');const a=await this.input._initInput._getDemuxer();if(a.constructor!==Yn)throw new Error("Init input must match the input's format.");await a.readMetadata(),this.movieTimescale=a.movieTimescale,this.movieDurationInTimescale=a.movieDurationInTimescale,this.metadataTags=a.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=a.fragmentTrackDefaults,this.psshBoxes=a.psshBoxes;for(const o of a.tracks){const c={id:o.id,demuxer:this,trackBacking:null,disposition:o.disposition,timescale:o.timescale,durationInMediaTimescale:o.durationInMediaTimescale,durationInMovieTimescale:o.durationInMovieTimescale,rotation:o.rotation,internalCodecId:o.internalCodecId,name:o.name,languageCode:o.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:o.editListPreviousSegmentDurations,editListOffset:o.editListOffset,encryptionInfo:o.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:o.info};if(o.trackBacking){if(m(c.info),c.info.type==="video"&&c.info.width!==-1){const u=c;c.trackBacking=new Ea(u),this.tracks.push(c)}else if(c.info.type==="audio"&&c.info.numberOfChannels!==-1){const u=c;c.trackBacking=new va(u),this.tracks.push(c)}}}t=!1;break}e=s+n.totalSize}if(t){m(this.reader.fileSize!==null);let r=this.reader.requestSlice(this.reader.fileSize-4,4);r instanceof Promise&&(r=await r),m(r);const s=U(r),n=this.reader.fileSize-s;if(n>=0&&n<=this.reader.fileSize-Jt){let a=this.reader.requestSliceRange(n,kt,Jt);if(a instanceof Promise&&(a=await a),a){const o=Dt(a);if(o&&o.name==="mfra"){let c=this.reader.requestSlice(a.filePos,o.contentSize);c instanceof Promise&&(c=await c),c&&this.readContiguousBoxes(c)}}}}})())}getSampleTableForTrack(e){var n,a;if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,e.sampleTableByteOffset===null)return t;m(this.moovSlice);const r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,((n=e.info)==null?void 0:n.type)==="audio"&&e.info.codec&&Pe.includes(e.info.codec)&&t.sampleCompositionTimeOffsets.length===0){m(((a=e.info)==null?void 0:a.type)==="audio");const o=st(e.info.codec),c=[],u=[];for(let l=0;l<t.sampleToChunk.length;l++){const d=t.sampleToChunk[l],h=t.sampleToChunk[l+1],p=(h?h.startChunkIndex:t.chunkOffsets.length)-d.startChunkIndex;for(let y=0;y<p;y++){const f=d.startSampleIndex+y*d.samplesPerChunk,w=f+d.samplesPerChunk,g=ne(t.sampleTimingEntries,f,v=>v.startIndex),b=t.sampleTimingEntries[g],k=ne(t.sampleTimingEntries,w,v=>v.startIndex),S=t.sampleTimingEntries[k],A=b.startDecodeTimestamp+(f-b.startIndex)*b.delta,I=S.startDecodeTimestamp+(w-S.startIndex)*S.delta-A,C=we(c);C&&C.delta===I?C.count++:c.push({startIndex:d.startChunkIndex+y,startDecodeTimestamp:A,count:1,delta:I});const P=d.samplesPerChunk*o.sampleSize*e.info.numberOfChannels;u.push(P)}d.startSampleIndex=d.startChunkIndex,d.samplesPerChunk=1}t.sampleTimingEntries=c,t.sampleSizes=u}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const o of t.sampleTimingEntries)for(let c=0;c<o.count;c++)t.presentationTimestamps.push({presentationTimestamp:o.startDecodeTimestamp+c*o.delta,sampleIndex:o.startIndex+c});for(const o of t.sampleCompositionTimeOffsets)for(let c=0;c<o.count;c++){const u=o.startIndex+c,l=t.presentationTimestamps[u];l&&(l.presentationTimestamp+=o.offset)}t.presentationTimestamps.sort((o,c)=>o.presentationTimestamp-c.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let o=0;o<t.presentationTimestamps.length;o++)t.presentationTimestampIndexMap[t.presentationTimestamps[o].sampleIndex]=o}return t}async readFragment(e){var a;if(((a=this.lastReadFragment)==null?void 0:a.moofOffset)===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,kt,Jt);t instanceof Promise&&(t=await t),m(t);const r=Dt(t);m((r==null?void 0:r.name)==="moof");let s=this.reader.requestSlice(e,r.totalSize);s instanceof Promise&&(s=await s),m(s),this.traverseBox(s);const n=this.lastReadFragment;m(n&&n.moofOffset===e);for(const[,o]of n.trackData){const c=o.track,{fragmentPositionCache:u}=c;if(!o.startTimestampIsFinal){const d=c.fragmentLookupTable.find(h=>h.moofOffset===n.moofOffset);if(d)Vs(o,d.timestamp);else{const h=ne(u,n.moofOffset-1,p=>p.moofOffset);if(h!==-1){const p=u[h];Vs(o,p.endTimestamp)}}o.startTimestampIsFinal=!0}const l=ne(u,o.startTimestamp,d=>d.startTimestamp);if((l===-1||u[l].moofOffset!==n.moofOffset)&&u.splice(l+1,0,{moofOffset:n.moofOffset,startTimestamp:o.startTimestamp,endTimestamp:o.endTimestamp}),o.encryptionAuxInfo&&c.encryptionInfo){const d=await Tc(this.reader,c.encryptionInfo,o.encryptionAuxInfo);for(let h=0;h<Math.min(o.samples.length,d.length);h++){const p=d[h];o.samples[h].encryption=p}}}return n}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-kt&&this.traverseBox(e););}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-kt;){const r=e.filePos,s=Dt(e);if(!s)break;yield{boxInfo:s,slice:e},e.filePos=r+s.totalSize}}traverseBox(e){var a,o,c,u,l,d,h,p,y,f,w,g,b,k,S,A,_,I,C,P,v,M,R,L,H,q,O,ee,ue,xe,Ue,Vr,Or,Wr,Lr,Hr,qr,jr,Kr,Gr,Qr,Xr,$r,Yr,Zr;const t=e.filePos,r=Dt(e);if(!r)return!1;const s=e.filePos,n=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mvhd":{const T=j(e);e.skip(3),T===1?(e.skip(16),this.movieTimescale=U(e),this.movieDurationInTimescale=Ge(e)):(e.skip(8),this.movieTimescale=U(e),this.movieDurationInTimescale=U(e))}break;case"trak":{const T={id:-1,demuxer:this,trackBacking:null,disposition:{...Et,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:ve,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=T,this.readContiguousBoxes(e.slice(s,r.contentSize)),T.id!==-1&&T.timescale!==-1&&T.info!==null){if(T.info.type==="video"&&T.info.width!==-1){const D=T;T.trackBacking=new Ea(D),this.tracks.push(T)}else if(T.info.type==="audio"&&T.info.numberOfChannels!==-1){const D=T;T.trackBacking=new va(D),this.tracks.push(T)}}this.currentTrack=null}break;case"tkhd":{const T=this.currentTrack;if(!T)break;const D=j(e),B=!!(wt(e)&1);if(T.disposition.default=B,D===0)e.skip(8),T.id=U(e),e.skip(4),T.durationInMovieTimescale=U(e);else if(D===1)e.skip(16),T.id=U(e),e.skip(4),T.durationInMovieTimescale=Ge(e);else throw new Error(`Incorrect track header version ${D}.`);e.skip(16);const N=[jt(e),jt(e),Us(e),jt(e),jt(e),Us(e),jt(e),jt(e),Us(e)],F=Er(nn(Ku(N),90));m(F===0||F===90||F===180||F===270),T.rotation=F}break;case"elst":{const T=this.currentTrack;if(!T)break;const D=j(e);e.skip(3);let E=!1,B=0;const N=U(e);for(let F=0;F<N;F++){const W=D===1?Ge(e):U(e),G=D===1?Ph(e):tr(e),Y=jt(e);if(W!==0){if(E){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(G===-1){B+=W;continue}if(Y!==1){console.warn("Unsupported edit list entry: media rate must be 1.");break}T.editListPreviousSegmentDurations=B,T.editListOffset=G,E=!0}}}break;case"mdhd":{const T=this.currentTrack;if(!T)break;const D=j(e);e.skip(3),D===0?(e.skip(8),T.timescale=U(e),T.durationInMediaTimescale=U(e)):D===1&&(e.skip(16),T.timescale=U(e),T.durationInMediaTimescale=Ge(e));let E=ke(e);if(E>0){T.languageCode="";for(let B=0;B<3;B++)T.languageCode=String.fromCharCode(96+(E&31))+T.languageCode,E>>=5;bi(T.languageCode)||(T.languageCode=ve)}}break;case"hdlr":{const T=this.currentTrack;if(!T)break;e.skip(8);const D=ye(e,4);D==="vide"?T.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:D==="soun"&&(T.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const T=this.currentTrack;if(!T)break;T.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(s,r.contentSize))}break;case"stsd":{const T=this.currentTrack;if(!T||T.info===null||T.sampleTable)break;const D=j(e);e.skip(3);const E=U(e);for(let B=0;B<E;B++){const N=e.filePos,F=Dt(e);if(!F)break;T.internalCodecId=F.name;const W=F.name.toLowerCase();if(T.info.type==="video"){e.skip(24),T.info.width=ke(e),T.info.height=ke(e),T.info.squarePixelWidth=T.info.width,T.info.squarePixelHeight=T.info.height,e.skip(50),T.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,N+F.totalSize-e.filePos));const G=W==="encv"?T.frmaCodecString:W;T.frmaCodecString=null,G==="avc1"||G==="avc3"?(T.info.codec="avc",T.info.avcType=G==="avc1"?1:3):G==="hvc1"||G==="hev1"?T.info.codec="hevc":G==="vp08"?T.info.codec="vp8":G==="vp09"?T.info.codec="vp9":G==="av01"?T.info.codec="av1":console.warn(G===null?"Unknown encrypted video codec due to missing frma box.":`Unsupported video codec (sample entry type '${F.name}').`)}else{e.skip(8);const G=ke(e);e.skip(6);let Y=ke(e),J=ke(e);e.skip(4);let oe=U(e)/65536,fe=null;D===0&&G>0&&(G===1?(e.skip(4),J=8*U(e),e.skip(8)):G===2&&(e.skip(4),oe=pl(e),Y=U(e),e.skip(4),J=U(e),fe=U(e),e.skip(8))),T.info.numberOfChannels=Y,T.info.sampleRate=oe,T.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,N+F.totalSize-e.filePos));const $=W==="enca"?T.frmaCodecString:W;if(T.frmaCodecString=null,$!=="mp4a")if($==="opus")T.info.codec="opus",T.info.sampleRate=zr;else if($==="flac")T.info.codec="flac";else if($==="ulaw")T.info.codec="ulaw";else if($==="alaw")T.info.codec="alaw";else if($==="ac-3")T.info.codec="ac3";else if($==="ec-3")T.info.codec="eac3";else if($==="twos")J===8?T.info.codec="pcm-s8":J===16?T.info.codec=T.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.warn(`Unsupported sample size ${J} for codec 'twos'.`),T.info.codec=null);else if($==="sowt")J===8?T.info.codec="pcm-s8":J===16?T.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${J} for codec 'sowt'.`),T.info.codec=null);else if($==="raw ")T.info.codec="pcm-u8";else if($==="in24")T.info.codec=T.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if($==="in32")T.info.codec=T.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if($==="fl32")T.info.codec=T.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if($==="fl64")T.info.codec=T.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if($==="ipcm"){const se=T.info.pcmSampleSize;T.info.pcmLittleEndian?se===16?T.info.codec="pcm-s16":se===24?T.info.codec="pcm-s24":se===32?T.info.codec="pcm-s32":(console.warn(`Invalid ipcm sample size ${se}.`),T.info.codec=null):se===16?T.info.codec="pcm-s16be":se===24?T.info.codec="pcm-s24be":se===32?T.info.codec="pcm-s32be":(console.warn(`Invalid ipcm sample size ${se}.`),T.info.codec=null)}else if($==="fpcm"){const se=T.info.pcmSampleSize;T.info.pcmLittleEndian?se===32?T.info.codec="pcm-f32":se===64?T.info.codec="pcm-f64":(console.warn(`Invalid fpcm sample size ${se}.`),T.info.codec=null):se===32?T.info.codec="pcm-f32be":se===64?T.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${se}.`),T.info.codec=null)}else if($==="lpcm"&&fe!==null){const se=J+7>>3,at=!!(fe&1),mt=!!(fe&2),ur=fe&4?-1:0;J>0&&J<=64&&(at?J===32&&(T.info.codec=mt?"pcm-f32be":"pcm-f32"):ur&1<<se-1?se===1?T.info.codec="pcm-s8":se===2?T.info.codec=mt?"pcm-s16be":"pcm-s16":se===3?T.info.codec=mt?"pcm-s24be":"pcm-s24":se===4&&(T.info.codec=mt?"pcm-s32be":"pcm-s32"):se===1&&(T.info.codec="pcm-u8")),T.info.codec===null&&console.warn("Unsupported PCM format.")}else console.warn($===null?"Unknown encrypted audio codec due to missing frma box.":`Unsupported audio codec (sample entry type '${F.name}').`)}e.filePos=N+F.totalSize}}break;case"frma":{const T=this.currentTrack;if(!T)break;const E=ye(e,4).toLowerCase();T.frmaCodecString=E}break;case"schm":{const T=this.currentTrack;if(!T)break;e.skip(4);const D=ye(e,4);D==="cenc"||D==="cens"||D==="cbcs"?T.encryptionInfo={scheme:D,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:console.warn(`Unsupported encryption scheme '${D}'.`)}break;case"tenc":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;const D=j(e);e.skip(3),e.skip(1);const E=j(e);if(D>0?(T.encryptionInfo.defaultCryptByteBlock=E>>4,T.encryptionInfo.defaultSkipByteBlock=E&15):(T.encryptionInfo.defaultCryptByteBlock=0,T.encryptionInfo.defaultSkipByteBlock=0),T.encryptionInfo.defaultIsProtected=j(e)!==0,T.encryptionInfo.defaultPerSampleIvSize=j(e),T.encryptionInfo.defaultKid=wi(K(e,16)),T.encryptionInfo.defaultIsProtected&&T.encryptionInfo.defaultPerSampleIvSize===0){const B=j(e),N=new Uint8Array(16);N.set(K(e,B),0),T.encryptionInfo.defaultConstantIv=N}}break;case"avcC":{const T=this.currentTrack;if(!T)break;m(T.info),T.info.codecDescription=K(e,r.contentSize)}break;case"hvcC":{const T=this.currentTrack;if(!T)break;m(T.info),T.info.codecDescription=K(e,r.contentSize)}break;case"vpcC":{const T=this.currentTrack;if(!T)break;m(((a=T.info)==null?void 0:a.type)==="video"),e.skip(4);const D=j(e),E=j(e),B=j(e),N=B>>4,F=B>>1&7,W=B&1,G=j(e),Y=j(e),J=j(e);T.info.vp9CodecInfo={profile:D,level:E,bitDepth:N,chromaSubsampling:F,videoFullRangeFlag:W,colourPrimaries:G,transferCharacteristics:Y,matrixCoefficients:J}}break;case"av1C":{const T=this.currentTrack;if(!T)break;m(((o=T.info)==null?void 0:o.type)==="video"),e.skip(1);const D=j(e),E=D>>5,B=D&31,N=j(e),F=N>>7,W=N>>6&1,G=N>>5&1,Y=N>>4&1,J=N>>3&1,oe=N>>2&1,fe=N&3,$=E===2&&W?G?12:10:W?10:8;T.info.av1CodecInfo={profile:E,level:B,tier:F,bitDepth:$,monochrome:Y,chromaSubsamplingX:J,chromaSubsamplingY:oe,chromaSamplePosition:fe}}break;case"colr":{const T=this.currentTrack;if(!T||(m(((c=T.info)==null?void 0:c.type)==="video"),ye(e,4)!=="nclx"))break;const E=ke(e),B=ke(e),N=ke(e),F=!!(j(e)&128);T.info.colorSpace={primaries:Qi[E],transfer:Xi[B],matrix:$i[N],fullRange:F}}break;case"pasp":{const T=this.currentTrack;if(!T)break;m(((u=T.info)==null?void 0:u.type)==="video");const D=U(e),E=U(e);D>0&&E>0&&(D>E?T.info.squarePixelWidth=Math.round(T.info.width*D/E):T.info.squarePixelHeight=Math.round(T.info.height*E/D))}break;case"wave":this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"esds":{const T=this.currentTrack;if(!T)break;m(((l=T.info)==null?void 0:l.type)==="audio"),e.skip(4);const D=j(e);m(D===3),Ns(e),e.skip(2);const E=j(e),B=(E&128)!==0,N=(E&64)!==0,F=(E&32)!==0;if(B&&e.skip(2),N){const oe=j(e);e.skip(oe)}F&&e.skip(2);const W=j(e);m(W===4);const G=Ns(e),Y=e.filePos,J=j(e);if(J===64||J===103?(T.info.codec="aac",T.info.aacCodecInfo={isMpeg2:J===103,objectType:null}):J===105||J===107?T.info.codec="mp3":J===221?T.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${J}) - discarding track.`),e.skip(12),G>e.filePos-Y){const oe=j(e);m(oe===5);const fe=Ns(e);if(T.info.codecDescription=K(e,fe),T.info.codec==="aac"){const $=Bi(T.info.codecDescription);$.numberOfChannels!==null&&(T.info.numberOfChannels=$.numberOfChannels),$.sampleRate!==null&&(T.info.sampleRate=$.sampleRate)}}}break;case"enda":{const T=this.currentTrack;if(!T)break;m(((d=T.info)==null?void 0:d.type)==="audio"),T.info.pcmLittleEndian=!!(ke(e)&255)}break;case"pcmC":{const T=this.currentTrack;if(!T)break;m(((h=T.info)==null?void 0:h.type)==="audio"),e.skip(4);const D=j(e);T.info.pcmLittleEndian=!!(D&1),T.info.pcmSampleSize=j(e)}break;case"dOps":{const T=this.currentTrack;if(!T)break;m(((p=T.info)==null?void 0:p.type)==="audio"),e.skip(1);const D=j(e),E=ke(e),B=U(e),N=Bn(e),F=j(e);let W;F!==0?W=K(e,2+D):W=new Uint8Array(0);const G=new Uint8Array(19+W.byteLength),Y=new DataView(G.buffer);Y.setUint32(0,1332770163,!1),Y.setUint32(4,1214603620,!1),Y.setUint8(8,1),Y.setUint8(9,D),Y.setUint16(10,E,!0),Y.setUint32(12,B,!0),Y.setInt16(16,N,!0),Y.setUint8(18,F),G.set(W,19),T.info.codecDescription=G,T.info.numberOfChannels=D}break;case"dfLa":{const T=this.currentTrack;if(!T)break;m(((y=T.info)==null?void 0:y.type)==="audio"),e.skip(4);const D=127,E=128,B=e.filePos;for(;e.filePos<n;){const Y=j(e),J=wt(e);if((Y&D)===Pt.STREAMINFO){e.skip(10);const fe=U(e),$=fe>>>12,se=(fe>>9&7)+1;T.info.sampleRate=$,T.info.numberOfChannels=se,e.skip(20)}else e.skip(J);if(Y&E)break}const N=e.filePos;e.filePos=B;const F=K(e,N-B),W=new Uint8Array(4+F.byteLength);new DataView(W.buffer).setUint32(0,1716281667,!1),W.set(F,4),T.info.codecDescription=W}break;case"dac3":{const T=this.currentTrack;if(!T)break;m(((f=T.info)==null?void 0:f.type)==="audio");const D=K(e,3),E=new re(D),B=E.readBits(2);E.skipBits(8);const N=E.readBits(3),F=E.readBits(1);B<3&&(T.info.sampleRate=ys[B]),T.info.numberOfChannels=$n[N]+F}break;case"dec3":{const T=this.currentTrack;if(!T)break;m(((w=T.info)==null?void 0:w.type)==="audio");const D=K(e,r.contentSize),E=Vu(D);if(!E){console.warn("Invalid dec3 box contents, ignoring.");break}const B=hc(E);B!==null&&(T.info.sampleRate=B),T.info.numberOfChannels=fc(E)}break;case"stts":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const D=U(e);let E=0,B=0;for(let N=0;N<D;N++){const F=U(e),W=U(e);T.sampleTable.sampleTimingEntries.push({startIndex:E,startDecodeTimestamp:B,count:F,delta:W}),E+=F,B+=F*W}}break;case"ctts":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const D=U(e);let E=0;for(let B=0;B<D;B++){const N=U(e),F=tr(e);T.sampleTable.sampleCompositionTimeOffsets.push({startIndex:E,count:N,offset:F}),E+=N}}break;case"stsz":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const D=U(e),E=U(e);if(D===0)for(let B=0;B<E;B++){const N=U(e);T.sampleTable.sampleSizes.push(N)}else T.sampleTable.sampleSizes.push(D)}break;case"stz2":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4),e.skip(3);const D=j(e),E=U(e),B=K(e,Math.ceil(E*D/8)),N=new re(B);for(let F=0;F<E;F++){const W=N.readBits(D);T.sampleTable.sampleSizes.push(W)}}break;case"stss":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4),T.sampleTable.keySampleIndices=[];const D=U(e);for(let E=0;E<D;E++){const B=U(e)-1;T.sampleTable.keySampleIndices.push(B)}T.sampleTable.keySampleIndices[0]!==0&&T.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const D=U(e);for(let B=0;B<D;B++){const N=U(e)-1,F=U(e),W=U(e);T.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:N,samplesPerChunk:F,sampleDescriptionIndex:W})}let E=0;for(let B=0;B<T.sampleTable.sampleToChunk.length;B++)if(T.sampleTable.sampleToChunk[B].startSampleIndex=E,B<T.sampleTable.sampleToChunk.length-1){const F=T.sampleTable.sampleToChunk[B+1].startChunkIndex-T.sampleTable.sampleToChunk[B].startChunkIndex;E+=F*T.sampleTable.sampleToChunk[B].samplesPerChunk}}break;case"stco":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const D=U(e);for(let E=0;E<D;E++){const B=U(e);T.sampleTable.chunkOffsets.push(B)}}break;case"co64":{const T=this.currentTrack;if(!T||!T.sampleTable)break;e.skip(4);const D=U(e);for(let E=0;E<D;E++){const B=Ge(e);T.sampleTable.chunkOffsets.push(B)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(s,r.contentSize));break;case"mehd":{const T=j(e);e.skip(3);const D=T===1?Ge(e):U(e);this.movieDurationInTimescale=D}break;case"trex":{e.skip(4);const T=U(e),D=U(e),E=U(e),B=U(e),N=U(e);this.fragmentTrackDefaults.push({trackId:T,defaultSampleDescriptionIndex:D,defaultSampleDuration:E,defaultSampleSize:B,defaultSampleFlags:N})}break;case"tfra":{const T=j(e);e.skip(3);const D=U(e),E=this.tracks.find($=>$.id===D);if(!E)break;const B=U(e),N=(B&48)>>4,F=(B&12)>>2,W=B&3,G=[j,ke,wt,U],Y=G[N],J=G[F],oe=G[W],fe=U(e);for(let $=0;$<fe;$++){const se=T===1?Ge(e):U(e),at=T===1?Ge(e):U(e);Y(e),J(e),oe(e),E.fragmentLookupTable.push({timestamp:se,moofOffset:at})}E.fragmentLookupTable.sort(($,se)=>$.timestamp-se.timestamp);for(let $=0;$<E.fragmentLookupTable.length-1;$++){const se=E.fragmentLookupTable[$],at=E.fragmentLookupTable[$+1];se.timestamp===at.timestamp&&(E.fragmentLookupTable.splice($+1,1),$--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(s,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(m(this.currentFragment),this.readContiguousBoxes(e.slice(s,r.contentSize)),this.currentTrack){const T=this.currentFragment.trackData.get(this.currentTrack.id);if(T){this.currentFragment.implicitBaseDataOffset=T.currentOffset,T.presentationTimestamps=T.samples.map((N,F)=>({presentationTimestamp:N.presentationTimestamp,sampleIndex:F})).sort((N,F)=>N.presentationTimestamp-F.presentationTimestamp);for(let N=0;N<T.presentationTimestamps.length;N++){const F=T.presentationTimestamps[N],W=T.samples[F.sampleIndex];if(T.firstKeyFrameTimestamp===null&&W.isKeyFrame&&(T.firstKeyFrameTimestamp=W.presentationTimestamp),N<T.presentationTimestamps.length-1){const Y=T.presentationTimestamps[N+1].presentationTimestamp-F.presentationTimestamp;W.duration=Y}}const D=T.samples[T.presentationTimestamps[0].sampleIndex],E=T.samples[we(T.presentationTimestamps).sampleIndex];T.startTimestamp=D.presentationTimestamp,T.endTimestamp=E.presentationTimestamp+E.duration;const{currentFragmentState:B}=this.currentTrack;m(B),B.startTimestamp!==null&&(Vs(T,B.startTimestamp),T.startTimestampIsFinal=!0),B.encryptionAuxInfo&&!T.samples[0].encryption&&(T.encryptionAuxInfo=B.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if((g=this.input._formatOptions.isobmff)!=null&&g._suppressPsshParsing)break;const T=pc(K(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(T):this.currentTrack||this.psshBoxes.push(T)}break;case"tfhd":{m(this.currentFragment),e.skip(1);const T=wt(e),D=!!(T&1),E=!!(T&2),B=!!(T&8),N=!!(T&16),F=!!(T&32),W=!!(T&65536),G=!!(T&131072),Y=U(e),J=this.tracks.find(fe=>fe.id===Y);if(!J)break;const oe=this.fragmentTrackDefaults.find(fe=>fe.trackId===Y);this.currentTrack=J,J.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:(oe==null?void 0:oe.defaultSampleDescriptionIndex)??null,defaultSampleDuration:(oe==null?void 0:oe.defaultSampleDuration)??null,defaultSampleSize:(oe==null?void 0:oe.defaultSampleSize)??null,defaultSampleFlags:(oe==null?void 0:oe.defaultSampleFlags)??null,startTimestamp:null,encryptionAuxInfo:null},D?J.currentFragmentState.baseDataOffset=Ge(e):G&&(J.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),E&&(J.currentFragmentState.sampleDescriptionIndex=U(e)),B&&(J.currentFragmentState.defaultSampleDuration=U(e)),N&&(J.currentFragmentState.defaultSampleSize=U(e)),F&&(J.currentFragmentState.defaultSampleFlags=U(e)),W&&(J.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const T=this.currentTrack;if(!T)break;m(T.currentFragmentState);const D=j(e);e.skip(3);const E=D===0?U(e):Ge(e);T.currentFragmentState.startTimestamp=E}break;case"trun":{const T=this.currentTrack;if(!T)break;m(this.currentFragment),m(T.currentFragmentState);const D=j(e),E=wt(e),B=!!(E&1),N=!!(E&4),F=!!(E&256),W=!!(E&512),G=!!(E&1024),Y=!!(E&2048),J=U(e);let oe=null;B&&(oe=tr(e));let fe=null;N&&(fe=U(e));let $;if(this.currentFragment.trackData.has(T.id)?($=this.currentFragment.trackData.get(T.id),oe!==null&&($.currentOffset=T.currentFragmentState.baseDataOffset+oe)):($={track:T,currentTimestamp:0,currentOffset:T.currentFragmentState.baseDataOffset+(oe??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(T.id,$)),J===0){this.currentFragment.implicitBaseDataOffset=$.currentOffset;break}for(let se=0;se<J;se++){let at;F?at=U(e):(m(T.currentFragmentState.defaultSampleDuration!==null),at=T.currentFragmentState.defaultSampleDuration);let mt;W?mt=U(e):(m(T.currentFragmentState.defaultSampleSize!==null),mt=T.currentFragmentState.defaultSampleSize);let ur;G?ur=U(e):(m(T.currentFragmentState.defaultSampleFlags!==null),ur=T.currentFragmentState.defaultSampleFlags),se===0&&fe!==null&&(ur=fe);let vs=0;Y&&(D===0?vs=U(e):vs=tr(e));const Ol=!(ur&65536);$.samples.push({presentationTimestamp:$.currentTimestamp+vs,duration:at,byteOffset:$.currentOffset,byteSize:mt,isKeyFrame:Ol,encryption:null}),$.currentOffset+=mt,$.currentTimestamp+=at}}break;case"saiz":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;if(e.skip(1),wt(e)&1){const W=ye(e,4),G=U(e);if(W!==T.encryptionInfo.scheme||G!==0)break}const E=j(e),B=U(e);let N=null;E===0&&B>0&&(N=K(e,B));const F=Fa(T);F.defaultSampleInfoSize=E,F.sampleSizes=N,F.sampleCount=B}break;case"saio":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;const D=j(e);if(wt(e)&1){const W=ye(e,4),G=U(e);if(W!==T.encryptionInfo.scheme||G!==0)break}const B=U(e);if(B===0)break;B>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let N=D===0?U(e):Number(Ge(e));this.currentFragment&&(N+=this.currentFragment.moofOffset);const F=Fa(T);F.offset=N}break;case"senc":{const T=this.currentTrack;if(!T||!T.encryptionInfo)break;m(this.currentFragment);const D=this.currentFragment.trackData.get(T.id);if(!D)break;e.skip(1);const B=!!(wt(e)&2),N=U(e),F=T.encryptionInfo.defaultPerSampleIvSize;m(F!==null);for(let W=0;W<Math.min(N,D.samples.length);W++){const G=new Uint8Array(16);F>0?G.set(K(e,F),0):G.set(T.encryptionInfo.defaultConstantIv,0);let Y=null;if(B){const oe=ke(e);Y=[];for(let fe=0;fe<oe;fe++){const $=ke(e),se=U(e);Y.push({clearLen:$,protectedLen:se})}}const J=D.samples[W];J.encryption={iv:G,subsamples:Y}}}break;case"udta":{const T=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(const{boxInfo:D,slice:E}of T){if(D.name!=="meta"&&!this.currentTrack){const B=E.filePos;(b=this.metadataTags).raw??(b.raw={}),D.name[0]==="©"?(k=this.metadataTags.raw)[S=D.name]??(k[S]=ot(E)):(A=this.metadataTags.raw)[_=D.name]??(A[_]=K(E,D.contentSize)),E.filePos=B}switch(D.name){case"meta":E.skip(-D.headerSize),this.traverseBox(E);break;case"©nam":case"name":this.currentTrack?this.currentTrack.name=qe.decode(K(E,D.contentSize)):(I=this.metadataTags).title??(I.title=ot(E));break;case"©des":this.currentTrack||((C=this.metadataTags).description??(C.description=ot(E)));break;case"©ART":this.currentTrack||((P=this.metadataTags).artist??(P.artist=ot(E)));break;case"©alb":this.currentTrack||((v=this.metadataTags).album??(v.album=ot(E)));break;case"albr":this.currentTrack||((M=this.metadataTags).albumArtist??(M.albumArtist=ot(E)));break;case"©gen":this.currentTrack||((R=this.metadataTags).genre??(R.genre=ot(E)));break;case"©day":if(!this.currentTrack){const B=new Date(ot(E));Number.isNaN(B.getTime())||((L=this.metadataTags).date??(L.date=B))}break;case"©cmt":this.currentTrack||((H=this.metadataTags).comment??(H.comment=ot(E)));break;case"©lyr":this.currentTrack||((q=this.metadataTags).lyrics??(q.lyrics=ot(E)));break}}}break;case"meta":{if(this.currentTrack)break;const D=U(e)!==0;this.currentMetadataKeys=new Map,D?this.readContiguousBoxes(e.slice(s,r.contentSize)):this.readContiguousBoxes(e.slice(s+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const T=U(e);for(let D=0;D<T;D++){const E=U(e);e.skip(4);const B=qe.decode(K(e,E-8));this.currentMetadataKeys.set(D+1,B)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const T=this.iterateContiguousBoxes(e.slice(s,r.contentSize));for(const{boxInfo:D,slice:E}of T){let B=D.name;const N=(B.charCodeAt(0)<<24)+(B.charCodeAt(1)<<16)+(B.charCodeAt(2)<<8)+B.charCodeAt(3);this.currentMetadataKeys.has(N)&&(B=this.currentMetadataKeys.get(N));const F=Ou(E);switch((O=this.metadataTags).raw??(O.raw={}),(ee=this.metadataTags.raw)[B]??(ee[B]=F),B){case"©nam":case"titl":case"com.apple.quicktime.title":case"title":typeof F=="string"&&((ue=this.metadataTags).title??(ue.title=F));break;case"©des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":typeof F=="string"&&((xe=this.metadataTags).description??(xe.description=F));break;case"©ART":case"com.apple.quicktime.artist":case"artist":typeof F=="string"&&((Ue=this.metadataTags).artist??(Ue.artist=F));break;case"©alb":case"albm":case"com.apple.quicktime.album":case"album":typeof F=="string"&&((Vr=this.metadataTags).album??(Vr.album=F));break;case"aART":case"album_artist":typeof F=="string"&&((Or=this.metadataTags).albumArtist??(Or.albumArtist=F));break;case"©cmt":case"com.apple.quicktime.comment":case"comment":typeof F=="string"&&((Wr=this.metadataTags).comment??(Wr.comment=F));break;case"©gen":case"gnre":case"com.apple.quicktime.genre":case"genre":typeof F=="string"&&((Lr=this.metadataTags).genre??(Lr.genre=F));break;case"©lyr":case"lyrics":typeof F=="string"&&((Hr=this.metadataTags).lyrics??(Hr.lyrics=F));break;case"©day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if(typeof F=="string"){const W=new Date(F);Number.isNaN(W.getTime())||((qr=this.metadataTags).date??(qr.date=W))}break;case"covr":case"com.apple.quicktime.artwork":F instanceof Cr?((jr=this.metadataTags).images??(jr.images=[]),this.metadataTags.images.push({data:F.data,kind:"coverFront",mimeType:F.mimeType})):F instanceof Uint8Array&&((Kr=this.metadataTags).images??(Kr.images=[]),this.metadataTags.images.push({data:F,kind:"coverFront",mimeType:"image/*"}));break;case"track":if(typeof F=="string"){const W=F.split("/"),G=Number.parseInt(W[0],10),Y=W[1]&&Number.parseInt(W[1],10);Number.isInteger(G)&&G>0&&((Gr=this.metadataTags).trackNumber??(Gr.trackNumber=G)),Y&&Number.isInteger(Y)&&Y>0&&((Qr=this.metadataTags).tracksTotal??(Qr.tracksTotal=Y))}break;case"trkn":if(F instanceof Uint8Array&&F.length>=6){const W=Z(F),G=W.getUint16(2,!1),Y=W.getUint16(4,!1);G>0&&((Xr=this.metadataTags).trackNumber??(Xr.trackNumber=G)),Y>0&&(($r=this.metadataTags).tracksTotal??($r.tracksTotal=Y))}break;case"disc":case"disk":if(F instanceof Uint8Array&&F.length>=6){const W=Z(F),G=W.getUint16(2,!1),Y=W.getUint16(4,!1);G>0&&((Yr=this.metadataTags).discNumber??(Yr.discNumber=G)),Y>0&&((Zr=this.metadataTags).discsTotal??(Zr.discsTotal=Y))}break}}}break}return e.filePos=n,!0}}class kc{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let r=0;for(const s of e.tracks)if(s.trackBacking.getType()===t&&r++,s===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;m(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return((t==null?void 0:t.timestamp)??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,r=>r.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return yi(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const r=this.mapTimestampIntoTimescale(e),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=mn(s,r),a=await this.fetchPacketForSampleIndex(n,t);return!Ba(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=ne(c.presentationTimestamps,r,h=>h.presentationTimestamp),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,t)}async getNextPacket(e,t){const r=this.packetToSampleIndex.get(e);if(r!==void 0)return this.fetchPacketForSampleIndex(r+1,t);const s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){const a=n.trackData.get(this.internalTrack.id);if(s.sampleIndex+1<a.samples.length)return{sampleIndex:s.sampleIndex+1,correctSampleFound:!0}}else if(n.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),s=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Hu(s,r),a=await this.fetchPacketForSampleIndex(n,t);return!Ba(s)||!this.internalTrack.demuxer.isFragmented?a:this.performFragmentedLookup(null,o=>{const c=o.trackData.get(this.internalTrack.id);if(!c)return{sampleIndex:-1,correctSampleFound:!1};const u=us(c.presentationTimestamps,h=>c.samples[h.sampleIndex].isKeyFrame&&h.presentationTimestamp<=r),l=u!==-1?c.presentationTimestamps[u].sampleIndex:-1,d=u!==-1&&r<c.endTimestamp;return{sampleIndex:l,correctSampleFound:d}},r,r,t)}async getNextKeyPacket(e,t){const r=this.packetToSampleIndex.get(e);if(r!==void 0){const n=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ju(n,r);return this.fetchPacketForSampleIndex(a,t)}const s=this.packetToFragmentLocation.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(s.fragment,n=>{if(n===s.fragment){const o=n.trackData.get(this.internalTrack.id).samples.findIndex((c,u)=>c.isKeyFrame&&u>s.sampleIndex);if(o!==-1)return{sampleIndex:o,correctSampleFound:!0}}else{const a=n.trackData.get(this.internalTrack.id);if(a&&a.firstKeyFrameTimestamp!==null){const o=a.samples.findIndex(c=>c.isKeyFrame);return m(o!==-1),{sampleIndex:o,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(e===-1)return null;const r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),s=qu(r,e);if(!s)return null;let n;if(t.metadataOnly)n=je;else{let u=this.internalTrack.demuxer.reader.requestSlice(s.sampleOffset,s.sampleSize);if(u instanceof Promise&&(u=await u),!u)return null;if(n=K(u,s.sampleSize),this.internalTrack.encryptionAuxInfo){m(this.internalTrack.encryptionInfo);const l=await Tc(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<l.length&&(n=await Ra(this.internalTrack,l[e],n,null))}}const a=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=s.duration/this.internalTrack.timescale,c=new de(n,s.isKeyFrame?"key":"delta",a,o,e,s.sampleSize);return this.packetToSampleIndex.set(c,e),c}async fetchPacketInFragment(e,t,r){if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).samples[t];m(n);let a;if(r.metadataOnly)a=je;else{let l=this.internalTrack.demuxer.reader.requestSlice(n.byteOffset,n.byteSize);if(l instanceof Promise&&(l=await l),!l)return null;a=K(l,n.byteSize),n.encryption&&(a=await Ra(this.internalTrack,n.encryption,a,e))}const o=(n.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,c=n.duration/this.internalTrack.timescale,u=new de(a,n.isKeyFrame?"key":"delta",o,c,e.moofOffset+t,n.byteSize);return this.packetToFragmentLocation.set(u,{fragment:e,sampleIndex:t}),u}async performFragmentedLookup(e,t,r,s,n){const a=this.internalTrack.demuxer;let o=null,c=null,u=-1;if(e){const{sampleIndex:w,correctSampleFound:g}=t(e);if(g)return this.fetchPacketInFragment(e,w,n);w!==-1&&(c=e,u=w)}const l=ne(this.internalTrack.fragmentLookupTable,r,w=>w.timestamp),d=l!==-1?this.internalTrack.fragmentLookupTable[l]:null,h=ne(this.internalTrack.fragmentPositionCache,r,w=>w.startTimestamp),p=h!==-1?this.internalTrack.fragmentPositionCache[h]:null,y=Math.max((d==null?void 0:d.moofOffset)??0,(p==null?void 0:p.moofOffset)??0)||null;let f;for(e?y===null||e.moofOffset>=y?(f=e.moofOffset+e.moofSize,o=e):f=y:f=y??0;;){if(o){const k=o.trackData.get(this.internalTrack.id);if(k&&k.startTimestamp>s)break}let w=a.reader.requestSliceRange(f,kt,Jt);if(w instanceof Promise&&(w=await w),!w)break;const g=f,b=Dt(w);if(!b)break;if(b.name==="moof"){o=await a.readFragment(g);const{sampleIndex:k,correctSampleFound:S}=t(o);if(S)return this.fetchPacketInFragment(o,k,n);k!==-1&&(c=o,u=k)}f=g+b.totalSize}if(d&&(!c||c.moofOffset<d.moofOffset)){const w=this.internalTrack.fragmentLookupTable[l-1];m(!w||w.timestamp<d.timestamp);const g=(w==null?void 0:w.timestamp)??-1/0;return this.performFragmentedLookup(null,t,g,s,n)}return c?this.fetchPacketInFragment(c,u,n):null}}class Ea extends kc{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){var e,t,r,s;return{primaries:(e=this.internalTrack.info.colorSpace)==null?void 0:e.primaries,transfer:(t=this.internalTrack.info.colorSpace)==null?void 0:t.transfer,matrix:(r=this.internalTrack.info.colorSpace)==null?void 0:r.matrix,fullRange:(s=this.internalTrack.info.colorSpace)==null?void 0:s.fullRange}}async canBeTransparent(){return!1}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if(this.internalTrack.info.codec==="vp9"&&!this.internalTrack.info.vp9CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=t&&nc(t.data)}else if(this.internalTrack.info.codec==="av1"&&!this.internalTrack.info.av1CodecInfo){const t=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=t&&oc(t.data)}const e={codec:Ln(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(e.displayAspectWidth=this.internalTrack.info.squarePixelWidth,e.displayAspectHeight=this.internalTrack.info.squarePixelHeight),e})()):null}}class va extends kc{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Hn(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}):null}}const mn=(i,e)=>{if(i.presentationTimestamps){const t=ne(i.presentationTimestamps,e,r=>r.presentationTimestamp);return t===-1?-1:i.presentationTimestamps[t].sampleIndex}else{const t=ne(i.sampleTimingEntries,e,s=>s.startDecodeTimestamp);if(t===-1)return-1;const r=i.sampleTimingEntries[t];return r.startIndex+Math.min(Math.floor((e-r.startDecodeTimestamp)/r.delta),r.count-1)}},Hu=(i,e)=>{if(!i.keySampleIndices)return mn(i,e);if(i.presentationTimestamps){const t=ne(i.presentationTimestamps,e,r=>r.presentationTimestamp);if(t===-1)return-1;for(let r=t;r>=0;r--){const s=i.presentationTimestamps[r].sampleIndex;if(vi(i.keySampleIndices,s,a=>a)!==-1)return s}return-1}else{const t=mn(i,e),r=ne(i.keySampleIndices,t,s=>s);return i.keySampleIndices[r]??-1}},qu=(i,e)=>{const t=ne(i.sampleTimingEntries,e,g=>g.startIndex),r=i.sampleTimingEntries[t];if(!r||r.startIndex+r.count<=e)return null;let n=r.startDecodeTimestamp+(e-r.startIndex)*r.delta;const a=ne(i.sampleCompositionTimeOffsets,e,g=>g.startIndex),o=i.sampleCompositionTimeOffsets[a];o&&e-o.startIndex<o.count&&(n+=o.offset);const c=i.sampleSizes[Math.min(e,i.sampleSizes.length-1)],u=ne(i.sampleToChunk,e,g=>g.startSampleIndex),l=i.sampleToChunk[u];m(l);const d=l.startChunkIndex+Math.floor((e-l.startSampleIndex)/l.samplesPerChunk),h=i.chunkOffsets[d],p=l.startSampleIndex+(d-l.startChunkIndex)*l.samplesPerChunk;let y=0,f=h;if(i.sampleSizes.length===1)f+=c*(e-p),y+=c*l.samplesPerChunk;else for(let g=p;g<p+l.samplesPerChunk;g++){const b=i.sampleSizes[g];g<e&&(f+=b),y+=b}let w=r.delta;if(i.presentationTimestamps){const g=i.presentationTimestampIndexMap[e];m(g!==void 0),g<i.presentationTimestamps.length-1&&(w=i.presentationTimestamps[g+1].presentationTimestamp-n)}return{presentationTimestamp:n,duration:w,sampleOffset:f,sampleSize:c,chunkOffset:h,chunkSize:y,isKeyFrame:i.keySampleIndices?vi(i.keySampleIndices,e,g=>g)!==-1:!0}},ju=(i,e)=>{if(!i.keySampleIndices)return e+1;const t=ne(i.keySampleIndices,e,r=>r);return i.keySampleIndices[t+1]??-1},Vs=(i,e)=>{i.startTimestamp+=e,i.endTimestamp+=e;for(const t of i.samples)t.presentationTimestamp+=e;for(const t of i.presentationTimestamps)t.presentationTimestamp+=e},Ku=i=>{const[e,t]=i,r=Math.atan2(t,e);return Number.isFinite(r)?r*(180/Math.PI):0},Ba=i=>i.sampleSizes.length===0,Fa=i=>{var e;return i.currentFragmentState?(e=i.currentFragmentState).encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):i.encryptionAuxInfo??(i.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},Tc=async(i,e,t)=>{if(t.resolved)return t.resolved;if(t.offset===null||t.sampleCount===0)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(t.defaultSampleInfoSize>0)r=t.defaultSampleInfoSize*t.sampleCount;else{m(t.sampleSizes);for(let o=0;o<t.sampleCount;o++)r+=t.sampleSizes[o]}let s=i.requestSlice(t.offset,r);if(s instanceof Promise&&(s=await s),!s)throw new Error("Failed to read auxiliary encryption info.");const n=e.defaultPerSampleIvSize;m(n!==null);const a=[];for(let o=0;o<t.sampleCount;o++){const c=t.defaultSampleInfoSize>0?t.defaultSampleInfoSize:t.sampleSizes[o],u=new Uint8Array(16);n>0?u.set(K(s,n),0):u.set(e.defaultConstantIv,0);let l=null;if(c>n){const d=ke(s);l=[];for(let h=0;h<d;h++){const p=ke(s),y=U(s);l.push({clearLen:p,protectedLen:y})}}a.push({iv:u,subsamples:l})}return t.resolved=a,a},Ra=async(i,e,t,r)=>{var c;m(i.encryptionInfo);const s=i.encryptionInfo;m(s.defaultKid!==null);const n=s.defaultKid;let a;const o=i.demuxer.decryptionKeyCache.get(n);if(o)a=await o;else{if(!((c=i.demuxer.input._formatOptions.isobmff)!=null&&c.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const u=(async()=>{let l=i.demuxer.psshBoxes;if(r){l=[...l,...r.psshBoxes].filter(h=>h.keyIds===null||h.keyIds.includes(n));for(let h=0;h<l.length-1;h++)for(let p=h+1;p<l.length;p++)gc(l[h],l[p])&&(l.splice(p,1),p--)}const d=await i.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:n,psshBoxes:l});if(!(typeof d=="string"&&d.length===32&&Ll.test(d)||d instanceof Uint8Array&&d.byteLength===16))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return d instanceof Uint8Array?d:Hl(d)})();i.demuxer.decryptionKeyCache.set(n,u),a=await u}return s.scheme==="cenc"||s.scheme==="cens"?Gu(a,s,e,t):Qu(a,s,e,t)},Gu=async(i,e,t,r)=>{const s=new Uint8Array(16);s.set(t.iv,0);const n=await crypto.subtle.importKey("raw",i,{name:"AES-CTR"},!1,["decrypt"]),a=async y=>{const f=await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,y);return new Uint8Array(f)};if(!t.subsamples)return a(r);m(e.defaultCryptByteBlock!==null&&e.defaultSkipByteBlock!==null);const o=Sc(t.subsamples,e.defaultCryptByteBlock,e.defaultSkipByteBlock);let c=0;for(const y of o)for(const f of y.perSubsample)c+=f.length;const u=new Uint8Array(c);let l=0;for(const y of o)for(const f of y.perSubsample)u.set(r.subarray(f.offset,f.offset+f.length),l),l+=f.length;const d=await a(u),h=new Uint8Array(r);let p=0;for(const y of o)for(const f of y.perSubsample)h.set(d.subarray(p,p+f.length),f.offset),p+=f.length;return h},Qu=(i,e,t,r)=>{const s=new bc;s.init({key:i,iv:t.iv});const n=e.defaultCryptByteBlock,a=e.defaultSkipByteBlock;if(m(n!==null&&a!==null),!t.subsamples){const l=new Uint8Array(r),d=Math.floor(r.length/16);for(let h=0;h<d;h++){const p=h*16;s.in.set(r.subarray(p,p+16)),s.decrypt(),l.set(s.out,p)}return l}if(n===0&&a===0)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),c=Sc(t.subsamples,n,a),u=new DataView(t.iv.buffer,t.iv.byteOffset,16);for(const l of c){s.iv[0]=u.getUint32(0,!1),s.iv[1]=u.getUint32(4,!1),s.iv[2]=u.getUint32(8,!1),s.iv[3]=u.getUint32(12,!1);for(const d of l.perSubsample){const h=d.length/16;for(let p=0;p<h;p++){const y=d.offset+p*16;s.in.set(r.subarray(y,y+16)),s.decrypt(),o.set(s.out,y)}}}return o},Sc=(i,e,t)=>{const r=[],s=e!==0||t!==0;let n=0;for(const a of i){n+=a.clearLen;const o=[];if(!s)a.protectedLen>0&&o.push({offset:n,length:a.protectedLen}),n+=a.protectedLen;else{let c=a.protectedLen,u=n;for(;c>0&&!(c<16*e);){const l=16*e;o.push({offset:u,length:l}),u+=l,c-=l;const d=Math.min(16*t,c);u+=d,c-=d}n+=a.protectedLen}r.push({perSubsample:o})}return r};/*!
|
|
86
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
87
|
+
*
|
|
88
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
89
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
90
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
91
|
+
*/class pn{constructor(e){this.value=e}}class gn{constructor(e){this.value=e}}class Ac{constructor(e){this.value=e}}class Rt{constructor(e){this.value=e}}var x;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Duration=17545]="Duration",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.MuxingApp=19840]="MuxingApp",i[i.WritingApp=22337]="WritingApp",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.TrackNumber=215]="TrackNumber",i[i.TrackUID=29637]="TrackUID",i[i.TrackType=131]="TrackType",i[i.FlagEnabled=185]="FlagEnabled",i[i.FlagDefault=136]="FlagDefault",i[i.FlagForced=21930]="FlagForced",i[i.FlagOriginal=21934]="FlagOriginal",i[i.FlagHearingImpaired=21931]="FlagHearingImpaired",i[i.FlagVisualImpaired=21932]="FlagVisualImpaired",i[i.FlagCommentary=21935]="FlagCommentary",i[i.FlagLacing=156]="FlagLacing",i[i.Name=21358]="Name",i[i.Language=2274716]="Language",i[i.LanguageBCP47=2274717]="LanguageBCP47",i[i.CodecID=134]="CodecID",i[i.CodecPrivate=25506]="CodecPrivate",i[i.CodecDelay=22186]="CodecDelay",i[i.SeekPreRoll=22203]="SeekPreRoll",i[i.DefaultDuration=2352003]="DefaultDuration",i[i.Video=224]="Video",i[i.PixelWidth=176]="PixelWidth",i[i.PixelHeight=186]="PixelHeight",i[i.DisplayWidth=21680]="DisplayWidth",i[i.DisplayHeight=21690]="DisplayHeight",i[i.DisplayUnit=21682]="DisplayUnit",i[i.AlphaMode=21440]="AlphaMode",i[i.Audio=225]="Audio",i[i.SamplingFrequency=181]="SamplingFrequency",i[i.Channels=159]="Channels",i[i.BitDepth=25188]="BitDepth",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.Block=161]="Block",i[i.BlockAdditions=30113]="BlockAdditions",i[i.BlockMore=166]="BlockMore",i[i.BlockAdditional=165]="BlockAdditional",i[i.BlockAddID=238]="BlockAddID",i[i.BlockDuration=155]="BlockDuration",i[i.ReferenceBlock=251]="ReferenceBlock",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.Colour=21936]="Colour",i[i.MatrixCoefficients=21937]="MatrixCoefficients",i[i.TransferCharacteristics=21946]="TransferCharacteristics",i[i.Primaries=21947]="Primaries",i[i.Range=21945]="Range",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPoseRoll=30325]="ProjectionPoseRoll",i[i.Attachments=423732329]="Attachments",i[i.AttachedFile=24999]="AttachedFile",i[i.FileDescription=18046]="FileDescription",i[i.FileName=18030]="FileName",i[i.FileMediaType=18016]="FileMediaType",i[i.FileData=18012]="FileData",i[i.FileUID=18094]="FileUID",i[i.Chapters=272869232]="Chapters",i[i.Tags=307544935]="Tags",i[i.Tag=29555]="Tag",i[i.Targets=25536]="Targets",i[i.TargetTypeValue=26826]="TargetTypeValue",i[i.TargetType=25546]="TargetType",i[i.TagTrackUID=25541]="TagTrackUID",i[i.TagEditionUID=25545]="TagEditionUID",i[i.TagChapterUID=25540]="TagChapterUID",i[i.TagAttachmentUID=25542]="TagAttachmentUID",i[i.SimpleTag=26568]="SimpleTag",i[i.TagName=17827]="TagName",i[i.TagLanguage=17530]="TagLanguage",i[i.TagString=17543]="TagString",i[i.TagBinary=17541]="TagBinary",i[i.ContentEncodings=28032]="ContentEncodings",i[i.ContentEncoding=25152]="ContentEncoding",i[i.ContentEncodingOrder=20529]="ContentEncodingOrder",i[i.ContentEncodingScope=20530]="ContentEncodingScope",i[i.ContentCompression=20532]="ContentCompression",i[i.ContentCompAlgo=16980]="ContentCompAlgo",i[i.ContentCompSettings=16981]="ContentCompSettings",i[i.ContentEncryption=20533]="ContentEncryption"})(x||(x={}));const Xu=[x.EBML,x.Segment],Ai=[x.SeekHead,x.Info,x.Cluster,x.Tracks,x.Cues,x.Attachments,x.Chapters,x.Tags],ji=[...Xu,...Ai],Ma=i=>i<256?1:i<65536?2:i<1<<24?3:i<2**32?4:i<2**40?5:6,Da=i=>i<1n<<8n?1:i<1n<<16n?2:i<1n<<24n?3:i<1n<<32n?4:i<1n<<40n?5:i<1n<<48n?6:i<1n<<56n?7:8,za=i=>i>=-64&&i<64?1:i>=-8192&&i<8192?2:i>=-1048576&&i<1<<20?3:i>=-134217728&&i<1<<27?4:i>=-17179869184&&i<2**34?5:6,$u=i=>{if(i<127)return 1;if(i<16383)return 2;if(i<(1<<21)-1)return 3;if(i<(1<<28)-1)return 4;if(i<2**35-1)return 5;if(i<2**42-1)return 6;throw new Error("EBML varint size not supported "+i)};class Yu{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=Ma(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=Da(e)){let r=0;for(let s=t-1;s>=0;s--)this.helperView.setUint8(r++,Number(e>>BigInt(s*8)&0xffn));this.writer.write(this.helper.subarray(0,r))}writeSignedInt(e,t=za(e)){e<0&&(e+=2**(t*8)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=$u(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(t=>t.charCodeAt(0))))}writeEBML(e){if(e!==null)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(const t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){const t=this.writer.getPos(),r=e.size===-1?1:e.size??4;e.size===-1?this.writeByte(255):this.writer.seek(this.writer.getPos()+r);const s=this.writer.getPos();if(this.dataOffsets.set(e,s),this.writeEBML(e.data),e.size!==-1){const n=this.writer.getPos()-s,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(n,r),this.writer.seek(a)}}else if(typeof e.data=="number"){const t=e.size??Ma(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if(typeof e.data=="bigint"){const t=e.size??Da(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if(typeof e.data=="string")this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof pn)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof gn)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof Ac){const t=e.size??za(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof Rt){const t=le.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else De(e.data)}}const wn=8,Qe=2,Tt=2*wn,xc=i=>{if(i.remainingLength<1)return null;const e=j(i);if(i.skip(-1),e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;return i.remainingLength<t?null:t},di=i=>{if(i.remainingLength<1)return null;const e=j(i);if(e===0)return null;let t=1,r=128;for(;(e&r)===0;)t++,r>>=1;if(i.remainingLength<t-1)return null;let s=e&r-1;for(let n=1;n<t;n++)s*=256,s+=j(i);return s},ie=(i,e)=>{if(e<1||e>8)throw new Error("Bad unsigned int size "+e);let t=0;for(let r=0;r<e;r++)t*=256,t+=j(i);return t},Zu=(i,e)=>{if(e<1)throw new Error("Bad unsigned int size "+e);let t=0n;for(let r=0;r<e;r++)t<<=8n,t+=BigInt(j(i));return t},Zn=i=>{const e=xc(i);return e===null||i.remainingLength<e?null:ie(i,e)},Pc=i=>{if(i.remainingLength<1)return null;if(j(i)===255)return;i.skip(-1);const t=di(i);if(t===null)return null;if(t!==72057594037927940)return t},bt=i=>{m(i.remainingLength>=Qe);const e=Zn(i);if(e===null)return null;const t=Pc(i);return t===null?null:{id:e,size:t}},br=(i,e)=>{const t=K(i,e);let r=0;for(;r<e&&t[r]!==0;)r+=1;return String.fromCharCode(...t.subarray(0,r))},ei=(i,e)=>{const t=K(i,e);let r=0;for(;r<e&&t[r]!==0;)r+=1;return qe.decode(t.subarray(0,r))},Os=(i,e)=>{if(e===0)return 0;if(e!==4&&e!==8)throw new Error("Bad float size "+e);return e===4?_h(i):pl(i)},yn=async(i,e,t,r)=>{const s=new Set(t);let n=e;for(;r===null||n<r;){let a=i.requestSliceRange(n,Qe,Tt);if(a instanceof Promise&&(a=await a),!a)break;const o=bt(a);if(!o)break;if(s.has(o.id))return{pos:n,found:!0};Mt(o.size),n=a.filePos+o.size}return{pos:r!==null&&r>n?r:n,found:!1}},Cc=async(i,e,t,r)=>{const n=new Set(t);let a=e;for(;a<r;){let o=i.requestSliceRange(a,0,Math.min(65536,r-a));if(o instanceof Promise&&(o=await o),!o||o.length<wn)break;for(let c=0;c<o.length-wn;c++){o.filePos=a;const u=Zn(o);if(u!==null&&n.has(u))return a;a++}}return null},Ve={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",ac3:"A_AC3",eac3:"A_EAC3","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 Mt(i){if(i===void 0)throw new Error("Undefined element size is used in a place where it is not supported.")}/*!
|
|
92
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
93
|
+
*
|
|
94
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
95
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
96
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
97
|
+
*/const _c=i=>{let t=(i.hasVideo?"video/":i.hasAudio?"audio/":"application/")+(i.isWebM?"webm":"x-matroska");if(i.codecStrings.length>0){const r=[...new Set(i.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};/*!
|
|
98
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
99
|
+
*
|
|
100
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
101
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
102
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
103
|
+
*/var yt;(function(i){i[i.None=0]="None",i[i.Xiph=1]="Xiph",i[i.FixedSize=2]="FixedSize",i[i.Ebml=3]="Ebml"})(yt||(yt={}));var is;(function(i){i[i.Block=1]="Block",i[i.Private=2]="Private",i[i.Next=4]="Next"})(is||(is={}));var mi;(function(i){i[i.Zlib=0]="Zlib",i[i.Bzlib=1]="Bzlib",i[i.lzo1x=2]="lzo1x",i[i.HeaderStripping=3]="HeaderStripping"})(mi||(mi={}));const Ws=[{id:x.SeekHead,flag:"seekHeadSeen"},{id:x.Info,flag:"infoSeen"},{id:x.Tracks,flag:"tracksSeen"},{id:x.Cues,flag:"cuesSeen"}],Ic=10*2**20;class Ju extends vt{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(t=>t.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(r=>r.getDecoderConfig().then(s=>(s==null?void 0:s.codec)??null)));return _c({isWebM:this.isWebM,hasVideo:this.segments.some(r=>r.tracks.some(s=>{var n;return((n=s.info)==null?void 0:n.type)==="video"})),hasAudio:this.segments.some(r=>r.tracks.some(s=>{var n;return((n=s.info)==null?void 0:n.type)==="audio"})),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(this.reader.fileSize!==null&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Qe,Tt);if(t instanceof Promise&&(t=await t),!t)break;const r=bt(t);if(!r)break;const s=r.id;let n=r.size;const a=t.filePos;if(s===x.EBML){Mt(n);let o=this.reader.requestSlice(a,n);if(o instanceof Promise&&(o=await o),!o)break;this.readContiguousElements(o)}else if(s===x.Segment){if(await this.readSegment(a,n),n===void 0||this.reader.fileSize===null)break}else if(s===x.Cluster){if(this.reader.fileSize===null)break;n===void 0&&(n=(await yn(this.reader,a,ji,this.reader.fileSize)).pos-a);const o=we(this.segments);o&&(o.elementEndPos=a+n)}Mt(n),e=a+n}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:t===void 0?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;this.currentSegment.elementEndPos===null||r<this.currentSegment.elementEndPos;){let o=this.reader.requestSliceRange(r,Qe,Tt);if(o instanceof Promise&&(o=await o),!o)break;const c=r,u=bt(o);if(!u||!Ai.includes(u.id)&&u.id!==x.Void){const y=await Cc(this.reader,c,Ai,Math.min(this.currentSegment.elementEndPos??1/0,c+Ic));if(y){r=y;continue}else break}const{id:l,size:d}=u,h=o.filePos,p=Ws.findIndex(y=>y.id===l);if(p!==-1){const y=Ws[p].flag;this.currentSegment[y]=!0,Mt(d);let f=this.reader.requestSlice(h,d);f instanceof Promise&&(f=await f),f&&this.readContiguousElements(f)}else if(l===x.Tags||l===x.Attachments){l===x.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Mt(d);let y=this.reader.requestSlice(h,d);y instanceof Promise&&(y=await y),y&&this.readContiguousElements(y)}else if(l===x.Cluster){this.currentSegment.clusterSeekStartPos=c;break}if(d===void 0)break;r=h+d}if(this.currentSegment.seekEntries.sort((o,c)=>o.segmentPosition-c.segmentPosition),this.reader.fileSize!==null)for(const o of this.currentSegment.seekEntries){const c=Ws.find(y=>y.id===o.id);if(!c||this.currentSegment[c.flag])continue;let u=this.reader.requestSliceRange(e+o.segmentPosition,Qe,Tt);if(u instanceof Promise&&(u=await u),!u)continue;const l=bt(u);if(!l)continue;const{id:d,size:h}=l;if(d!==c.id)continue;Mt(h),this.currentSegment[c.flag]=!0;let p=this.reader.requestSlice(u.filePos,h);p instanceof Promise&&(p=await p),p&&this.readContiguousElements(p)}this.currentSegment.timestampScale===-1&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e9/1e6);for(const o of this.currentSegment.tracks)o.defaultDurationNs!==null&&(o.defaultDuration=this.currentSegment.timestampFactor*o.defaultDurationNs/1e9);const s=new Map(this.currentSegment.tracks.map(o=>[o.id,o]));for(const o of this.currentSegment.cuePoints){const c=s.get(o.trackId);c&&c.cuePoints.push(o)}for(const o of this.currentSegment.tracks){o.cuePoints.sort((c,u)=>c.time-u.time);for(let c=0;c<o.cuePoints.length-1;c++){const u=o.cuePoints[c],l=o.cuePoints[c+1];u.time===l.time&&(o.cuePoints.splice(c+1,1),c--)}}let n=null,a=-1/0;for(const o of this.currentSegment.tracks)o.cuePoints.length>a&&(a=o.cuePoints.length,n=o);for(const o of this.currentSegment.tracks)o.cuePoints.length===0&&(o.cuePoints=n.cuePoints);this.currentSegment=null}async readCluster(e,t){var d;if(((d=t.lastReadCluster)==null?void 0:d.elementStartPos)===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,Qe,Tt);r instanceof Promise&&(r=await r),m(r);const s=e,n=bt(r);m(n);const a=n.id;m(a===x.Cluster);let o=n.size;const c=r.filePos;o===void 0&&(o=(await yn(this.reader,c,ji,t.elementEndPos)).pos-c);let u=this.reader.requestSlice(c,o);u instanceof Promise&&(u=await u);const l={segment:t,elementStartPos:s,elementEndPos:c+o,dataStartPos:c,timestamp:-1,trackData:new Map};if(this.currentCluster=l,u){const h=this.readContiguousElements(u,ji);l.elementEndPos=h}for(const[,h]of l.trackData){const p=h.track;m(h.blocks.length>0);let y=!1;for(let b=0;b<h.blocks.length;b++){const k=h.blocks[b];k.timestamp+=l.timestamp,y||(y=k.lacing!==yt.None)}h.presentationTimestamps=h.blocks.map((b,k)=>({timestamp:b.timestamp,blockIndex:k})).sort((b,k)=>b.timestamp-k.timestamp);for(let b=0;b<h.presentationTimestamps.length;b++){const k=h.presentationTimestamps[b],S=h.blocks[k.blockIndex];if(h.firstKeyFrameTimestamp===null&&S.isKeyFrame&&(h.firstKeyFrameTimestamp=S.timestamp),b<h.presentationTimestamps.length-1){const A=h.presentationTimestamps[b+1];S.duration=A.timestamp-S.timestamp}else S.duration===0&&p.defaultDuration!=null&&S.lacing===yt.None&&(S.duration=p.defaultDuration)}y&&(this.expandLacedBlocks(h.blocks,p),h.presentationTimestamps=h.blocks.map((b,k)=>({timestamp:b.timestamp,blockIndex:k})).sort((b,k)=>b.timestamp-k.timestamp));const f=h.blocks[h.presentationTimestamps[0].blockIndex],w=h.blocks[we(h.presentationTimestamps).blockIndex];h.startTimestamp=f.timestamp,h.endTimestamp=w.timestamp+w.duration;const g=ne(p.clusterPositionCache,h.startTimestamp,b=>b.startTimestamp);(g===-1||p.clusterPositionCache[g].elementStartPos!==s)&&p.clusterPositionCache.splice(g+1,0,{elementStartPos:l.elementStartPos,startTimestamp:h.startTimestamp})}return t.lastReadCluster=l,l}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){const s=e.segment.tracks.find(n=>n.id===t);if(!s)return null;r={track:s,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){const s=e[r];if(s.lacing===yt.None)continue;s.decoded||(s.data=this.decodeBlockData(t,s.data),s.decoded=!0);const n=Me.tempFromBytes(s.data),a=[],o=j(n)+1;switch(s.lacing){case yt.Xiph:{let u=0;for(let l=0;l<o-1;l++){let d=0;for(;n.bufferPos<n.length;){const h=j(n);if(d+=h,h<255){a.push(d),u+=d;break}}}a.push(n.length-(n.bufferPos+u))}break;case yt.FixedSize:{const u=n.length-1,l=Math.floor(u/o);for(let d=0;d<o;d++)a.push(l)}break;case yt.Ebml:{const u=di(n);m(u!==null);let l=u;a.push(l);let d=l;for(let h=1;h<o-1;h++){const p=n.bufferPos,y=di(n);m(y!==null);const f=y,g=(1<<(n.bufferPos-p)*7-1)-1,b=f-g;l+=b,a.push(l),d+=l}a.push(n.length-(n.bufferPos+d))}break;default:m(!1)}m(a.length===o),e.splice(r,1);const c=s.duration||o*(t.defaultDuration??0);for(let u=0;u<o;u++){const l=a[u],d=K(n,l),h=s.timestamp+c*u/o,p=c/o;e.splice(r+u,0,{timestamp:h,duration:p,isKeyFrame:s.isKeyFrame,data:d,lacing:yt.None,decoded:!0,mainAdditional:s.mainAdditional})}r+=o,r--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(!(t.id===x.Tags&&!e.tagsSeen)){if(!(t.id===x.Attachments&&!e.attachmentsSeen))continue}let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,Qe,Tt);if(r instanceof Promise&&(r=await r),!r)continue;const s=bt(r);if(!s||s.id!==t.id)continue;const{size:n}=s;Mt(n),m(!this.currentSegment),this.currentSegment=e;let a=this.reader.requestSlice(r.filePos,n);a instanceof Promise&&(a=await a),a&&this.readContiguousElements(a),this.currentSegment=null,t.id===x.Tags?e.tagsSeen=!0:t.id===x.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=Qe;){const r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}traverseElement(e,t){var o,c,u,l,d,h,p,y,f,w,g,b,k,S,A,_,I,C,P,v,M,R,L,H,q,O,ee,ue,xe,Ue,Vr,Or,Wr,Lr,Hr,qr,jr,Kr,Gr,Qr,Xr,$r,Yr,Zr,T,D;const r=bt(e);if(!r||t&&t.includes(r.id))return!1;const{id:s,size:n}=r,a=e.filePos;switch(Mt(n),s){case x.DocType:this.isWebM=br(e,n)==="webm";break;case x.Seek:{if(!this.currentSegment)break;const E={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(E),this.readContiguousElements(e.slice(a,n)),(E.id===-1||E.segmentPosition===-1)&&this.currentSegment.seekEntries.pop()}break;case x.SeekID:{const E=(o=this.currentSegment)==null?void 0:o.seekEntries[this.currentSegment.seekEntries.length-1];if(!E)break;E.id=ie(e,n)}break;case x.SeekPosition:{const E=(c=this.currentSegment)==null?void 0:c.seekEntries[this.currentSegment.seekEntries.length-1];if(!E)break;E.segmentPosition=ie(e,n)}break;case x.TimestampScale:{if(!this.currentSegment)break;this.currentSegment.timestampScale=ie(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale}break;case x.Duration:{if(!this.currentSegment)break;this.currentSegment.duration=Os(e,n)}break;case x.TrackEntry:{if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Et,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(a,n)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(E=>{var B;return((B=E.data)==null?void 0:B.type)!=="decompress"||E.scope!==is.Block||E.data.algorithm!==mi.HeaderStripping})&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&this.currentTrack.id!==-1&&this.currentTrack.codecId&&this.currentTrack.info){const E=this.currentTrack.codecId.indexOf("/"),B=E===-1?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,E);if(this.currentTrack.info.type==="video"&&this.currentTrack.info.width!==-1&&this.currentTrack.info.height!==-1){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,this.currentTrack.info.displayWidth!==null&&this.currentTrack.info.displayHeight!==null){const F=this.currentTrack.info.displayWidth*this.currentTrack.info.height,W=this.currentTrack.info.displayHeight*this.currentTrack.info.width;F>0&&W>0&&(F>W?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*F/W):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*W/F))}this.currentTrack.codecId===Ve.avc?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Ve.hevc?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):B===Ve.vp8?this.currentTrack.info.codec="vp8":B===Ve.vp9?this.currentTrack.info.codec="vp9":B===Ve.av1&&(this.currentTrack.info.codec="av1");const N=this.currentTrack;this.currentTrack.trackBacking=new ed(N),this.currentSegment.tracks.push(this.currentTrack)}else if(this.currentTrack.info.type==="audio"){B===Ve.aac?(this.currentTrack.info.codec="aac",this.currentTrack.info.aacCodecInfo={isMpeg2:this.currentTrack.codecId.includes("MPEG2"),objectType:null},this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Ve.mp3?this.currentTrack.info.codec="mp3":B===Ve.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=zr):B===Ve.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):B===Ve.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):B===Ve.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):B===Ve.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId==="A_PCM/INT/LIT"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32"):this.currentTrack.codecId==="A_PCM/INT/BIG"?this.currentTrack.info.bitDepth===8?this.currentTrack.info.codec="pcm-u8":this.currentTrack.info.bitDepth===16?this.currentTrack.info.codec="pcm-s16be":this.currentTrack.info.bitDepth===24?this.currentTrack.info.codec="pcm-s24be":this.currentTrack.info.bitDepth===32&&(this.currentTrack.info.codec="pcm-s32be"):this.currentTrack.codecId==="A_PCM/FLOAT/IEEE"&&(this.currentTrack.info.bitDepth===32?this.currentTrack.info.codec="pcm-f32":this.currentTrack.info.bitDepth===64&&(this.currentTrack.info.codec="pcm-f64"));const N=this.currentTrack;this.currentTrack.trackBacking=new td(N),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null}break;case x.TrackNumber:{if(!this.currentTrack)break;this.currentTrack.id=ie(e,n)}break;case x.TrackType:{if(!this.currentTrack)break;const E=ie(e,n);E===1?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:E===2&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case x.FlagEnabled:{if(!this.currentTrack)break;ie(e,n)||(this.currentTrack=null)}break;case x.FlagDefault:{if(!this.currentTrack)break;this.currentTrack.disposition.default=!!ie(e,n)}break;case x.FlagForced:{if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!ie(e,n)}break;case x.FlagOriginal:{if(!this.currentTrack)break;this.currentTrack.disposition.original=!!ie(e,n)}break;case x.FlagHearingImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!ie(e,n)}break;case x.FlagVisualImpaired:{if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!ie(e,n)}break;case x.FlagCommentary:{if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!ie(e,n)}break;case x.CodecID:{if(!this.currentTrack)break;this.currentTrack.codecId=br(e,n)}break;case x.CodecPrivate:{if(!this.currentTrack)break;this.currentTrack.codecPrivate=K(e,n)}break;case x.DefaultDuration:{if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=ie(e,n)}break;case x.Name:{if(!this.currentTrack)break;this.currentTrack.name=ei(e,n)}break;case x.Language:{if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=br(e,n),bi(this.currentTrack.languageCode)||(this.currentTrack.languageCode=ve)}break;case x.LanguageBCP47:{if(!this.currentTrack)break;const B=br(e,n).split("-")[0];B?this.currentTrack.languageCode=B:this.currentTrack.languageCode=ve,this.currentTrack.hasLanguageBcp47=!0}break;case x.Video:{if(((l=(u=this.currentTrack)==null?void 0:u.info)==null?void 0:l.type)!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case x.PixelWidth:{if(((h=(d=this.currentTrack)==null?void 0:d.info)==null?void 0:h.type)!=="video")break;this.currentTrack.info.width=ie(e,n)}break;case x.PixelHeight:{if(((y=(p=this.currentTrack)==null?void 0:p.info)==null?void 0:y.type)!=="video")break;this.currentTrack.info.height=ie(e,n)}break;case x.DisplayWidth:{if(((w=(f=this.currentTrack)==null?void 0:f.info)==null?void 0:w.type)!=="video")break;this.currentTrack.info.displayWidth=ie(e,n)}break;case x.DisplayHeight:{if(((b=(g=this.currentTrack)==null?void 0:g.info)==null?void 0:b.type)!=="video")break;this.currentTrack.info.displayHeight=ie(e,n)}break;case x.DisplayUnit:{if(((S=(k=this.currentTrack)==null?void 0:k.info)==null?void 0:S.type)!=="video")break;this.currentTrack.info.displayUnit=ie(e,n)}break;case x.AlphaMode:{if(((_=(A=this.currentTrack)==null?void 0:A.info)==null?void 0:_.type)!=="video")break;this.currentTrack.info.alphaMode=ie(e,n)===1}break;case x.Colour:{if(((C=(I=this.currentTrack)==null?void 0:I.info)==null?void 0:C.type)!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(a,n))}break;case x.MatrixCoefficients:{if(((v=(P=this.currentTrack)==null?void 0:P.info)==null?void 0:v.type)!=="video"||!this.currentTrack.info.colorSpace)break;const E=ie(e,n),B=$i[E]??null;this.currentTrack.info.colorSpace.matrix=B}break;case x.Range:{if(((R=(M=this.currentTrack)==null?void 0:M.info)==null?void 0:R.type)!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=ie(e,n)===2}break;case x.TransferCharacteristics:{if(((H=(L=this.currentTrack)==null?void 0:L.info)==null?void 0:H.type)!=="video"||!this.currentTrack.info.colorSpace)break;const E=ie(e,n),B=Xi[E]??null;this.currentTrack.info.colorSpace.transfer=B}break;case x.Primaries:{if(((O=(q=this.currentTrack)==null?void 0:q.info)==null?void 0:O.type)!=="video"||!this.currentTrack.info.colorSpace)break;const E=ie(e,n),B=Qi[E]??null;this.currentTrack.info.colorSpace.primaries=B}break;case x.Projection:{if(((ue=(ee=this.currentTrack)==null?void 0:ee.info)==null?void 0:ue.type)!=="video")break;this.readContiguousElements(e.slice(a,n))}break;case x.ProjectionPoseRoll:{if(((Ue=(xe=this.currentTrack)==null?void 0:xe.info)==null?void 0:Ue.type)!=="video")break;const B=-Os(e,n);try{this.currentTrack.info.rotation=Er(B)}catch{}}break;case x.Audio:{if(((Or=(Vr=this.currentTrack)==null?void 0:Vr.info)==null?void 0:Or.type)!=="audio")break;this.readContiguousElements(e.slice(a,n))}break;case x.SamplingFrequency:{if(((Lr=(Wr=this.currentTrack)==null?void 0:Wr.info)==null?void 0:Lr.type)!=="audio")break;this.currentTrack.info.sampleRate=Os(e,n)}break;case x.Channels:{if(((qr=(Hr=this.currentTrack)==null?void 0:Hr.info)==null?void 0:qr.type)!=="audio")break;this.currentTrack.info.numberOfChannels=ie(e,n)}break;case x.BitDepth:{if(((Kr=(jr=this.currentTrack)==null?void 0:jr.info)==null?void 0:Kr.type)!=="audio")break;this.currentTrack.info.bitDepth=ie(e,n)}break;case x.CuePoint:{if(!this.currentSegment)break;this.readContiguousElements(e.slice(a,n)),this.currentCueTime=null}break;case x.CueTime:this.currentCueTime=ie(e,n);break;case x.CueTrackPositions:{if(this.currentCueTime===null)break;m(this.currentSegment);const E={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(E),this.readContiguousElements(e.slice(a,n)),(E.trackId===-1||E.clusterPosition===-1)&&this.currentSegment.cuePoints.pop()}break;case x.CueTrack:{const E=(Gr=this.currentSegment)==null?void 0:Gr.cuePoints[this.currentSegment.cuePoints.length-1];if(!E)break;E.trackId=ie(e,n)}break;case x.CueClusterPosition:{const E=(Qr=this.currentSegment)==null?void 0:Qr.cuePoints[this.currentSegment.cuePoints.length-1];if(!E)break;m(this.currentSegment),E.clusterPosition=this.currentSegment.dataStartPos+ie(e,n)}break;case x.Timestamp:{if(!this.currentCluster)break;this.currentCluster.timestamp=ie(e,n)}break;case x.SimpleBlock:{if(!this.currentCluster)break;const E=di(e);if(E===null)break;const B=this.getTrackDataInCluster(this.currentCluster,E);if(!B)break;const N=Bn(e),F=j(e),W=F>>1&3;let G=!!(F&128);((Xr=B.track.info)==null?void 0:Xr.type)==="audio"&&B.track.info.codec&&(G=!0);const Y=K(e,n-(e.filePos-a)),J=B.track.decodingInstructions.length>0;B.blocks.push({timestamp:N,duration:0,isKeyFrame:G,data:Y,lacing:W,decoded:!J,mainAdditional:null})}break;case x.BlockGroup:{if(!this.currentCluster)break;this.readContiguousElements(e.slice(a,n)),this.currentBlock=null}break;case x.Block:{if(!this.currentCluster)break;const E=di(e);if(E===null)break;const B=this.getTrackDataInCluster(this.currentCluster,E);if(!B)break;const N=Bn(e),W=j(e)>>1&3,G=K(e,n-(e.filePos-a)),Y=B.track.decodingInstructions.length>0;this.currentBlock={timestamp:N,duration:0,isKeyFrame:!0,data:G,lacing:W,decoded:!Y,mainAdditional:null},B.blocks.push(this.currentBlock)}break;case x.BlockAdditions:this.readContiguousElements(e.slice(a,n));break;case x.BlockMore:{if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(a,n)),this.currentBlockAdditional.data&&this.currentBlockAdditional.addId===1&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null}break;case x.BlockAdditional:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=K(e,n)}break;case x.BlockAddID:{if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=ie(e,n)}break;case x.BlockDuration:{if(!this.currentBlock)break;this.currentBlock.duration=ie(e,n)}break;case x.ReferenceBlock:{if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1}break;case x.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(a,n));break;case x.Targets:this.readContiguousElements(e.slice(a,n));break;case x.TargetTypeValue:ie(e,n)!==50&&(this.currentTagTargetIsMovie=!1);break;case x.TagTrackUID:case x.TagEditionUID:case x.TagChapterUID:case x.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case x.SimpleTag:{if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(a,n))}break;case x.TagName:this.currentSimpleTagName=ei(e,n);break;case x.TagString:{if(!this.currentSimpleTagName)break;const E=ei(e,n);this.processTagValue(this.currentSimpleTagName,E)}break;case x.TagBinary:{if(!this.currentSimpleTagName)break;const E=K(e,n);this.processTagValue(this.currentSimpleTagName,E)}break;case x.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(a,n));const E=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(E.raw??(E.raw={}),E.raw[this.currentAttachedFile.fileUid.toString()]=new On(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),($r=this.currentAttachedFile.fileMediaType)!=null&&$r.startsWith("image/")&&this.currentAttachedFile.fileData){const B=this.currentAttachedFile.fileName;let N="unknown";if(B){const F=B.toLowerCase();F.startsWith("cover.")?N="coverFront":F.startsWith("back.")&&(N="coverBack")}E.images??(E.images=[]),E.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:N,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case x.FileUID:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=Zu(e,n)}break;case x.FileName:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ei(e,n)}break;case x.FileMediaType:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=br(e,n)}break;case x.FileData:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=K(e,n)}break;case x.FileDescription:{if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ei(e,n)}break;case x.ContentEncodings:{if(!this.currentTrack)break;this.readContiguousElements(e.slice(a,n)),this.currentTrack.decodingInstructions.sort((E,B)=>B.order-E.order)}break;case x.ContentEncoding:this.currentDecodingInstruction={order:0,scope:is.Block,data:null},this.readContiguousElements(e.slice(a,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case x.ContentEncodingOrder:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=ie(e,n)}break;case x.ContentEncodingScope:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=ie(e,n)}break;case x.ContentCompression:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:mi.Zlib,settings:null},this.readContiguousElements(e.slice(a,n))}break;case x.ContentCompAlgo:{if(((Zr=(Yr=this.currentDecodingInstruction)==null?void 0:Yr.data)==null?void 0:Zr.type)!=="decompress")break;this.currentDecodingInstruction.data.algorithm=ie(e,n)}break;case x.ContentCompSettings:{if(((D=(T=this.currentDecodingInstruction)==null?void 0:T.data)==null?void 0:D.type)!=="decompress")break;this.currentDecodingInstruction.data.settings=K(e,n)}break;case x.ContentEncryption:{if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}break}return e.filePos=a+n,!0}decodeBlockData(e,t){m(e.decodingInstructions.length>0);let r=t;for(const s of e.decodingInstructions)switch(m(s.data),s.data.type){case"decompress":switch(s.data.algorithm){case mi.HeaderStripping:if(s.data.settings&&s.data.settings.length>0){const n=s.data.settings,a=new Uint8Array(n.length+r.length);a.set(n,0),a.set(r,n.length),r=a}break}break}return r}processTagValue(e,t){var s,n;if(!((s=this.currentSegment)!=null&&s.metadataTags))return;const r=this.currentSegment.metadataTags;if(r.raw??(r.raw={}),(n=r.raw)[e]??(n[e]=t),typeof t=="string")switch(e.toLowerCase()){case"title":r.title??(r.title=t);break;case"description":r.description??(r.description=t);break;case"artist":r.artist??(r.artist=t);break;case"album":r.album??(r.album=t);break;case"album_artist":r.albumArtist??(r.albumArtist=t);break;case"genre":r.genre??(r.genre=t);break;case"comment":r.comment??(r.comment=t);break;case"lyrics":r.lyrics??(r.lyrics=t);break;case"date":{const a=new Date(t);Number.isNaN(a.getTime())||(r.date??(r.date=a))}break;case"track_number":case"part_number":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(r.trackNumber??(r.trackNumber=o)),c&&Number.isInteger(c)&&c>0&&(r.tracksTotal??(r.tracksTotal=c))}break;case"disc_number":case"disc":{const a=t.split("/"),o=Number.parseInt(a[0],10),c=a[1]&&Number.parseInt(a[1],10);Number.isInteger(o)&&o>0&&(r.discNumber??(r.discNumber=o)),c&&Number.isInteger(c)&&c>0&&(r.discsTotal??(r.discsTotal=c))}break}}}class Ec{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let r=0;for(const s of e.segments)for(const n of s.tracks)if(n.trackBacking.getType()===t&&r++,n===this.internalTrack)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor;const r=await this.getFirstPacket({metadataOnly:!0});return t+=(r==null?void 0:r.timestamp)??0,t}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,t=>t.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return yi(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const r=this.intoTimescale(e);return this.performClusterLookup(null,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=ne(n.presentationTimestamps,r,u=>u.timestamp),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,t)}async getNextPacket(e,t){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,s=>{if(s===r.cluster){const n=s.trackData.get(this.internalTrack.id);if(r.blockIndex+1<n.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else if(s.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,s=>{const n=s.trackData.get(this.internalTrack.id);if(!n)return{blockIndex:-1,correctBlockFound:!1};const a=us(n.presentationTimestamps,u=>n.blocks[u.blockIndex].isKeyFrame&&u.timestamp<=r),o=a!==-1?n.presentationTimestamps[a].blockIndex:-1,c=a!==-1&&r<n.endTimestamp;return{blockIndex:o,correctBlockFound:c}},r,r,t)}async getNextKeyPacket(e,t){const r=this.packetToClusterLocation.get(e);if(r===void 0)throw new Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,s=>{if(s===r.cluster){const a=s.trackData.get(this.internalTrack.id).blocks.findIndex((o,c)=>o.isKeyFrame&&c>r.blockIndex);if(a!==-1)return{blockIndex:a,correctBlockFound:!0}}else{const n=s.trackData.get(this.internalTrack.id);if(n&&n.firstKeyFrameTimestamp!==null){const a=n.blocks.findIndex(o=>o.isKeyFrame);return m(a!==-1),{blockIndex:a,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){var d;if(t===-1)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];m(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);const a=r.metadataOnly?je:n.data,o=n.timestamp/this.internalTrack.segment.timestampFactor,c=n.duration/this.internalTrack.segment.timestampFactor,u={};n.mainAdditional&&((d=this.internalTrack.info)==null?void 0:d.type)==="video"&&this.internalTrack.info.alphaMode&&(u.alpha=r.metadataOnly?je:n.mainAdditional,u.alphaByteLength=n.mainAdditional.byteLength);const l=new de(a,n.isKeyFrame?"key":"delta",o,c,e.dataStartPos+t,n.data.byteLength,u);return this.packetToClusterLocation.set(l,{cluster:e,blockIndex:t}),l}async performClusterLookup(e,t,r,s,n){const{demuxer:a,segment:o}=this.internalTrack;let c=null,u=null,l=-1;if(e){const{blockIndex:g,correctBlockFound:b}=t(e);if(b)return this.fetchPacketInCluster(e,g,n);g!==-1&&(u=e,l=g)}const d=ne(this.internalTrack.cuePoints,r,g=>g.time),h=d!==-1?this.internalTrack.cuePoints[d]:null,p=ne(this.internalTrack.clusterPositionCache,r,g=>g.startTimestamp),y=p!==-1?this.internalTrack.clusterPositionCache[p]:null,f=Math.max((h==null?void 0:h.clusterPosition)??0,(y==null?void 0:y.elementStartPos)??0)||null;let w;for(e?f===null||e.elementStartPos>=f?(w=e.elementEndPos,c=e):w=f:w=f??o.clusterSeekStartPos;o.elementEndPos===null||w<=o.elementEndPos-Qe;){if(c){const C=c.trackData.get(this.internalTrack.id);if(C&&C.startTimestamp>s)break}let g=a.reader.requestSliceRange(w,Qe,Tt);if(g instanceof Promise&&(g=await g),!g)break;const b=w,k=bt(g);if(!k||!Ai.includes(k.id)&&k.id!==x.Void){const C=await Cc(a.reader,b,Ai,Math.min(o.elementEndPos??1/0,b+Ic));if(C){w=C;continue}else break}const S=k.id;let A=k.size;const _=g.filePos;if(S===x.Cluster){c=await a.readCluster(b,o),A=c.elementEndPos-_;const{blockIndex:C,correctBlockFound:P}=t(c);if(P)return this.fetchPacketInCluster(c,C,n);C!==-1&&(u=c,l=C)}A===void 0&&(m(S!==x.Cluster),A=(await yn(a.reader,_,ji,o.elementEndPos)).pos-_);const I=_+A;if(o.elementEndPos===null){let C=a.reader.requestSliceRange(I,Qe,Tt);if(C instanceof Promise&&(C=await C),!C)break;if(Zn(C)===x.Segment){o.elementEndPos=I;break}}w=I}if(h&&(!u||u.elementStartPos<h.clusterPosition)){const g=this.internalTrack.cuePoints[d-1];m(!g||g.time<h.time);const b=(g==null?void 0:g.time)??-1/0;return this.performClusterLookup(null,t,b,s,n)}return u?this.fetchPacketInCluster(u,l,n):null}}class ed extends Ec{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){var e,t,r,s;return{primaries:(e=this.internalTrack.info.colorSpace)==null?void 0:e.primaries,transfer:(t=this.internalTrack.info.colorSpace)==null?void 0:t.transfer,matrix:(r=this.internalTrack.info.colorSpace)==null?void 0:r.matrix,fullRange:(s=this.internalTrack.info.colorSpace)==null?void 0:s.fullRange}}async canBeTransparent(){return this.internalTrack.info.alphaMode}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{let e=null;(this.internalTrack.info.codec==="vp9"||this.internalTrack.info.codec==="av1"||this.internalTrack.info.codec==="avc"&&!this.internalTrack.info.codecDescription||this.internalTrack.info.codec==="hevc"&&!this.internalTrack.info.codecDescription)&&(e=await this.getFirstPacket({}));const r={codec:Ln({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:this.internalTrack.info.codec==="avc"&&e?Gn(e.data):null,hevcCodecInfo:this.internalTrack.info.codec==="hevc"&&e?Xn(e.data):null,vp9CodecInfo:this.internalTrack.info.codec==="vp9"&&e?nc(e.data):null,av1CodecInfo:this.internalTrack.info.codec==="av1"&&e?oc(e.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(r.displayAspectWidth=this.internalTrack.info.squarePixelWidth,r.displayAspectHeight=this.internalTrack.info.squarePixelHeight),r})()):null}}class td extends Ec{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??(this.decoderConfig={codec:Hn({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}}/*!
|
|
104
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
105
|
+
*
|
|
106
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
107
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
108
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
109
|
+
*/const bn=async(i,e,t)=>{let s=e;for(;t===null||s<t;){const n=t!==null?Math.min(65536,t-s):65536;let a=i.requestSliceRange(s,ir,n);if(a instanceof Promise&&(a=await a),!a||a.length<ir)break;for(;a.remainingLength>=ir;){const o=a.filePos,c=U(a),u=i.fileSize!==null?i.fileSize-s:null,l=ws(c,u);if(l.header)return{header:l.header,startPos:s};a.filePos=o+l.bytesAdvanced,s=a.filePos}}return null};/*!
|
|
110
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
111
|
+
*
|
|
112
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
113
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
114
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
115
|
+
*/class rd extends vt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new lr,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new id(this)]})())}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let o=this.reader.requestSlice(this.lastLoadedPos,It);if(o instanceof Promise&&(o=await o),!o){this.lastSampleLoaded=!0;return}const c=nr(o);if(!c)break;this.lastLoadedPos=o.filePos+c.size}const e=await bn(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e){this.lastSampleLoaded=!0;return}const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const r=gs(t.mpegVersionId,t.channel);let s=this.reader.requestSlice(e.startPos+r,4);if(s instanceof Promise&&(s=await s),s){const o=U(s);if(o===ps||o===qn){if(!this.xingData){let u=this.reader.requestSlice(e.startPos+r+4,12);if(u instanceof Promise&&(u=await u),u){const l=K(u,12),d=Z(l),h=d.getUint32(0,!1);this.xingData={frameCount:h&sr.FrameCount?d.getUint32(4,!1):null,fileSize:h&sr.FileSize?d.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,a={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(a),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0,r=!1;for(;;){let s=this.reader.requestSlice(t,It);if(s instanceof Promise&&(s=await s),!s)break;const n=nr(s);if(!n)break;r=!0;let a=this.reader.requestSlice(s.filePos,n.size);if(a instanceof Promise&&(a=await a),!a)break;la(a,n,this.metadataTags),t=s.filePos+n.size}if(!r&&this.reader.fileSize!==null&&this.reader.fileSize>=Gi){let s=this.reader.requestSlice(this.reader.fileSize-Gi,Gi);s instanceof Promise&&(s=await s),m(s),ye(s,3)==="TAG"&&Ih(s,this.metadataTags)}return this.metadataTags}finally{e()}}}class id{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(m(e.firstFrameHeader!==null),m(e.firstFrameHeaderPos!==null),e.xingData){if(e.xingData.frameCount!==null)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(e.reader.fileSize!==null){const t=Tu(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate),r=(e.reader.fileSize-e.firstFrameHeaderPos)/t;return Math.round(r)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ve}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.channel===3?1:2}getSampleRate(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Et}}async getDecoderConfig(){return m(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:this.demuxer.firstFrameHeader.channel===3?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(e===-1)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=je;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=K(n,r.dataSize)}return new de(s,"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 s=vi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const s=ne(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
|
|
116
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
117
|
+
*
|
|
118
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
119
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
120
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
121
|
+
*/const Jn=1399285583,sd=79764919,vc=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^sd:e<<1;vc[i]=e>>>0&4294967295}const Bc=i=>{const e=Z(i),t=e.getUint32(22,!0);e.setUint32(22,0,!0);let r=0;for(let s=0;s<i.length;s++){const n=i[s];r=(r<<8^vc[r>>>24^n])>>>0}return e.setUint32(22,t,!0),r},Fc=(i,e,t)=>{let r=0,s=null;if(i.length>0)if(e.codec==="vorbis"){m(e.vorbisInfo);const n=e.vorbisInfo.modeBlockflags.length,o=(1<<Xl(n-1))-1<<1,c=(i[0]&o)>>1;if(c>=e.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let u=t;const l=e.vorbisInfo.modeBlockflags[c];if(s=e.vorbisInfo.blocksizes[l],l===1){const d=(o|1)+1,h=i[0]&d?1:0;u=e.vorbisInfo.blocksizes[h]}r=u!==null?u+s>>2:0}else e.codec==="opus"&&(r=zu(i).durationInSamples);return{durationInSamples:r,vorbisBlockSize:s}},Rc=i=>{let e="audio/ogg";if(i.codecStrings){const t=[...new Set(i.codecStrings)];e+=`; codecs="${t.join(", ")}"`}return e};/*!
|
|
122
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
123
|
+
*
|
|
124
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
125
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
126
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
127
|
+
*/const er=27,_r=282,Mc=_r+65025,pi=i=>{const e=i.filePos;if(Sr(i)!==Jn)return null;i.skip(1);const r=j(i),s=Ch(i),n=Sr(i),a=Sr(i),o=Sr(i),c=j(i),u=new Uint8Array(c);for(let p=0;p<c;p++)u[p]=j(i);const l=27+c,d=u.reduce((p,y)=>p+y,0),h=l+d;return{headerStartPos:e,totalSize:h,dataStartPos:e+l,dataSize:d,headerType:r,granulePosition:s,serialNumber:n,sequenceNumber:a,checksum:o,lacingValues:u}},nd=(i,e)=>{for(;i.filePos<e-3;){const t=Sr(i),r=t&255,s=t>>>8&255,n=t>>>16&255,a=t>>>24&255,o=79;if(!(r!==o&&s!==o&&n!==o&&a!==o)){if(i.skip(-4),t===Jn)return!0;i.skip(1)}}return!1};/*!
|
|
128
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
129
|
+
*
|
|
130
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
131
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
132
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
133
|
+
*/class ad extends vt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,er,_r);if(t instanceof Promise&&(t=await t),!t)break;const r=pi(t);if(!r||!!!(r.headerType&2))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 t of this.bitstreams){const r=await this.readPacket(t.bosPage,0);r&&(r.data.byteLength>=7&&r.data[0]===1&&r.data[1]===118&&r.data[2]===111&&r.data[3]===114&&r.data[4]===98&&r.data[5]===105&&r.data[6]===115?await this.readVorbisMetadata(r,t):r.data.byteLength>=8&&r.data[0]===79&&r.data[1]===112&&r.data[2]===117&&r.data[3]===115&&r.data[4]===72&&r.data[5]===101&&r.data[6]===97&&r.data[7]===100&&await this.readOpusMetadata(r,t),t.codecInfo.codec!==null&&this.trackBackings.push(new od(t,this)))}})())}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;const s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s||(r=await this.findNextPacketStart(s),!r))return;const n=await this.readPacket(r.startPage,r.startSegmentIndex);if(!n||s.data[0]!==3||n.data[0]!==5)return;const a=[],o=d=>{for(;a.push(Math.min(255,d)),!(d<255);)d-=255};o(e.data.length),o(s.data.length);const c=new Uint8Array(1+a.length+e.data.length+s.data.length+n.data.length);c[0]=2,c.set(a,1),c.set(e.data,1+a.length),c.set(s.data,1+a.length+e.data.length),c.set(n.data,1+a.length+e.data.length+s.data.length),t.codecInfo.codec="vorbis",t.description=c,t.lastMetadataPacket=n;const u=Z(e.data);t.numberOfChannels=u.getUint8(11),t.sampleRate=u.getUint32(12,!0);const l=u.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(l&15),1<<(l>>4)],modeBlockflags:cc(n.data).modeBlockflags},hn(s.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const r=await this.findNextPacketStart(e);if(!r)return;const s=await this.readPacket(r.startPage,r.startSegmentIndex);if(!s)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=s;const n=ks(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=zr,t.codecInfo.opusInfo={preSkip:n.preSkip},hn(s.data.subarray(8),this.metadataTags)}async readPacket(e,t){m(t<e.lacingValues.length);let r=0;for(let d=0;d<t;d++)r+=e.lacingValues[d];let s=e,n=r,a=t;const o=[];e:for(;;){let d=this.reader.requestSlice(s.dataStartPos,s.dataSize);d instanceof Promise&&(d=await d),m(d);const h=K(d,s.dataSize);for(;;){if(a===s.lacingValues.length){o.push(h.subarray(r,n));break}const y=s.lacingValues[a];if(n+=y,y<255){o.push(h.subarray(r,n));break e}a++}let p=s.headerStartPos+s.totalSize;for(;;){let y=this.reader.requestSliceRange(p,er,_r);if(y instanceof Promise&&(y=await y),!y)return null;const f=pi(y);if(!f)return null;if(s=f,s.serialNumber===e.serialNumber)break;p=s.headerStartPos+s.totalSize}r=0,n=0,a=0}const c=o.reduce((d,h)=>d+h.length,0);if(c===0)return null;const u=new Uint8Array(c);let l=0;for(let d=0;d<o.length;d++){const h=o[d];u.set(h,l),l+=h.length}return{data:u,endPage:s,endSegmentIndex:a}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(!!(e.endPage.headerType&4))return null;let r=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let s=this.reader.requestSliceRange(r,er,_r);if(s instanceof Promise&&(s=await s),!s)return null;const n=pi(s);if(!n)return null;if(n.serialNumber===e.endPage.serialNumber)return{startPage:n,startSegmentIndex:0};r=n.headerStartPos+n.totalSize}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackings.map(t=>t.getDecoderConfig().then(r=>(r==null?void 0:r.codec)??null)));return Rc({codecStrings:e.filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class od{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new lr,this.internalSampleRate=e.codecInfo.codec==="opus"?zr:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(t=>t.bitstream===this.bitstream);return m(e!==-1),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return m(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 ve}getDisposition(){return{...Et,primary:!1}}granulePositionToTimestampInSamples(e){return this.bitstream.codecInfo.codec==="opus"?(m(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;const{durationInSamples:s,vorbisBlockSize:n}=Fc(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),a=new de(r.metadataOnly?je:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,s/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(a,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:s,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:n}),a}async getFirstPacket(e){m(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;this.bitstream.codecInfo.codec==="opus"&&(m(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);const s=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:r,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 s=await this.demuxer.findNextPacketStart(r.packet);if(!s)return null;const n=r.timestampInSamples+r.durationInSamples,a=await this.demuxer.readPacket(s.startPage,s.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:n,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){if(this.demuxer.reader.fileSize===null)return this.getPacketSequential(e,t);const r=yi(e*this.internalSampleRate);if(r===0)return this.getFirstPacket(t);if(r<0)return null;m(this.bitstream.lastMetadataPacket);const s=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let n=s.startPage,a=this.demuxer.reader.fileSize;const o=[n];e:for(;n.headerStartPos+n.totalSize<a;){const b=n.headerStartPos,k=Math.floor((b+a)/2);let S=k;for(;;){const A=Math.min(S+Mc,a-er);let _=this.demuxer.reader.requestSlice(S,A-S);if(_ instanceof Promise&&(_=await _),m(_),!nd(_,A)){a=k+er;continue e}let C=this.demuxer.reader.requestSliceRange(_.filePos,er,_r);C instanceof Promise&&(C=await C),m(C);const P=pi(C);m(P);let v=!1;if(P.serialNumber===this.bitstream.serialNumber)v=!0;else{let R=this.demuxer.reader.requestSlice(P.headerStartPos,P.totalSize);R instanceof Promise&&(R=await R),m(R);const L=K(R,P.totalSize);v=Bc(L)===P.checksum}if(!v){S=P.headerStartPos+4;continue}if(v&&P.serialNumber!==this.bitstream.serialNumber){S=P.headerStartPos+P.totalSize;continue}if(P.granulePosition===-1){S=P.headerStartPos+P.totalSize;continue}this.granulePositionToTimestampInSamples(P.granulePosition)>r?a=P.headerStartPos:(n=P,o.push(P));continue e}}let c=s.startPage;for(const b of o){if(b.granulePosition===n.granulePosition)break;(!c||b.headerStartPos>c.headerStartPos)&&(c=b)}let u=c;const l=[u];for(;!(u.serialNumber===this.bitstream.serialNumber&&u.granulePosition===n.granulePosition);){const b=u.headerStartPos+u.totalSize;let k=this.demuxer.reader.requestSliceRange(b,er,_r);k instanceof Promise&&(k=await k),m(k);const S=pi(k);m(S),u=S,u.serialNumber===this.bitstream.serialNumber&&l.push(u)}m(u.granulePosition!==-1);let d=null,h,p,y=u,f=0;if(u.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),p=!0,d=0;else{h=0,p=!1;for(let S=u.lacingValues.length-1;S>=0;S--)if(u.lacingValues[S]<255){d=S+1;break}if(d===null)throw new Error("Invalid page with granule position: no packets end on this page.");f=d-1;const b={data:je,endPage:y,endSegmentIndex:f};if(await this.demuxer.findNextPacketStart(b)){const S=Na(l,u,d);m(S);const A=Ua(l,S.page,S.segmentIndex);A&&(u=A.page,d=A.segmentIndex)}else for(;;){const S=Na(l,u,d);if(!S)break;const A=Ua(l,S.page,S.segmentIndex);if(!A)break;if(u=A.page,d=A.segmentIndex,S.page.headerStartPos!==y.headerStartPos){y=S.page,f=S.segmentIndex;break}}}let w=null,g=null;for(;u!==null;){m(d!==null);const b=await this.demuxer.readPacket(u,d);if(!b)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&d<s.startSegmentIndex)){let A=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h,vorbisLastBlocksize:(g==null?void 0:g.vorbisBlockSize)??null},t);m(A);let _=this.encodedPacketToMetadata.get(A);if(m(_),!p&&b.endPage.headerStartPos===y.headerStartPos&&b.endSegmentIndex===f?(h=this.granulePositionToTimestampInSamples(u.granulePosition),p=!0,A=this.createEncodedPacketFromOggPacket(b,{timestampInSamples:h-_.durationInSamples,vorbisLastBlocksize:(g==null?void 0:g.vorbisBlockSize)??null},t),m(A),_=this.encodedPacketToMetadata.get(A),m(_)):h+=_.durationInSamples,w=A,g=_,p&&(Math.max(h,0)>r||Math.max(_.timestampInSamples,0)===r))break}const S=await this.demuxer.findNextPacketStart(b);if(!S)break;u=S.startPage,d=S.startSegmentIndex}return w}async getPacketSequential(e,t){const r=await this.sequentialScanMutex.acquire();try{const s=yi(e*this.internalSampleRate);e=s/this.internalSampleRate;const n=ne(this.sequentialScanCache,s,c=>c.timestampInSamples);let a;if(n!==-1){const c=this.sequentialScanCache[n];a=this.createEncodedPacketFromOggPacket(c.packet,{timestampInSamples:c.timestampInSamples,vorbisLastBlocksize:c.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let o=0;for(;a&&a.timestamp<e;){const c=await this.getNextPacket(a,t);if(!c||c.timestamp>e)break;if(a=c,o++,o===100){o=0;const u=this.encodedPacketToMetadata.get(a);m(u),this.sequentialScanCache.length>0&&m(we(this.sequentialScanCache).timestampInSamples<=u.timestampInSamples),this.sequentialScanCache.push(u)}}return a}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ua=(i,e,t)=>{let r=e,s=t;e:for(;;){for(s--,s;s>=0;s--)if(r.lacingValues[s]<255){s++;break e}if(m(s===-1),!(r.headerType&1)){s=0;break}const a=Lo(i,o=>o.headerStartPos<r.headerStartPos);if(!a)return null;r=a,s=r.lacingValues.length}if(m(s!==-1),s===r.lacingValues.length){const n=i[i.indexOf(r)+1];m(n),r=n,s=0}return{page:r,segmentIndex:s}},Na=(i,e,t)=>{if(t>0)return{page:e,segmentIndex:t-1};const r=Lo(i,s=>s.headerStartPos<e.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};/*!
|
|
134
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
135
|
+
*
|
|
136
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
137
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
138
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
139
|
+
*/var Oe;(function(i){i[i.PCM=1]="PCM",i[i.IEEE_FLOAT=3]="IEEE_FLOAT",i[i.ALAW=6]="ALAW",i[i.MULAW=7]="MULAW",i[i.EXTENSIBLE=65534]="EXTENSIBLE"})(Oe||(Oe={}));class cd extends vt{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),m(e);const t=ye(e,4),r=t!=="RIFX",s=t==="RF64",n=Vt(e,r);let a=s?this.reader.fileSize:Math.min(n+8,this.reader.fileSize??1/0);if(ye(e,4)!=="WAVE")throw new Error("Invalid WAVE file - wrong format");let c=0,u=null,l=e.filePos;for(;a===null||l<a;){let h=this.reader.requestSlice(l,8);if(h instanceof Promise&&(h=await h),!h)break;const p=ye(h,4),y=Vt(h,r),f=h.filePos;if(s&&c===0&&p!=="ds64")throw new Error('Invalid RF64 file: First chunk must be "ds64".');if(p==="fmt ")await this.parseFmtChunk(f,y,r);else if(p==="data"){if(u??(u=y),this.dataStart=h.filePos,this.dataSize=Math.min(u,(a??1/0)-this.dataStart),this.reader.fileSize===null)break}else if(p==="ds64"){let w=this.reader.requestSlice(f,y);if(w instanceof Promise&&(w=await w),!w)break;const g=wo(w,r);u=wo(w,r),a=Math.min(g+8,this.reader.fileSize??1/0)}else p==="LIST"?await this.parseListChunk(f,y,r):(p==="ID3 "||p==="id3 ")&&await this.parseId3Chunk(f,y);l=f+y+(y&1),c++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(this.dataStart===-1)throw new Error('Invalid WAVE file - missing "data" chunk');const d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new ld(this))})())}async parseFmtChunk(e,t,r){let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;let n=oi(s,r);const a=oi(s,r),o=Vt(s,r);s.skip(4);const c=oi(s,r);let u;if(t===14?u=8:u=oi(s,r),t>=18&&n!==357){const l=oi(s,r),d=t-18;if(Math.min(d,l)>=22&&n===Oe.EXTENSIBLE){s.skip(6);const p=K(s,16);n=p[0]|p[1]<<8}}(n===Oe.MULAW||n===Oe.ALAW)&&(u=8),this.audioInfo={format:n,numberOfChannels:a,sampleRate:o,sampleSizeInBytes:Math.ceil(u/8),blockSizeInBytes:c}}async parseListChunk(e,t,r){var o,c,u,l,d,h,p,y,f,w,g;let s=this.reader.requestSlice(e,t);if(s instanceof Promise&&(s=await s),!s)return;const n=ye(s,4);if(n!=="INFO"&&n!=="INF0")return;let a=s.filePos;for(;a<=e+t-8;){s.filePos=a;const b=ye(s,4),k=Vt(s,r),S=K(s,k);let A=0;for(let I=0;I<S.length&&S[I]!==0;I++)A++;const _=String.fromCharCode(...S.subarray(0,A));switch((o=this.metadataTags).raw??(o.raw={}),this.metadataTags.raw[b]=_,b){case"INAM":case"TITL":(c=this.metadataTags).title??(c.title=_);break;case"TIT3":(u=this.metadataTags).description??(u.description=_);break;case"IART":(l=this.metadataTags).artist??(l.artist=_);break;case"IPRD":(d=this.metadataTags).album??(d.album=_);break;case"IPRT":case"ITRK":case"TRCK":{const I=_.split("/"),C=Number.parseInt(I[0],10),P=I[1]&&Number.parseInt(I[1],10);Number.isInteger(C)&&C>0&&((h=this.metadataTags).trackNumber??(h.trackNumber=C)),P&&Number.isInteger(P)&&P>0&&((p=this.metadataTags).tracksTotal??(p.tracksTotal=P))}break;case"ICRD":case"IDIT":{const I=new Date(_);Number.isNaN(I.getTime())||((y=this.metadataTags).date??(y.date=I))}break;case"YEAR":{const I=Number.parseInt(_,10);Number.isInteger(I)&&I>0&&((f=this.metadataTags).date??(f.date=new Date(I,0,1)))}break;case"IGNR":case"GENR":(w=this.metadataTags).genre??(w.genre=_);break;case"ICMT":case"CMNT":case"COMM":(g=this.metadataTags).comment??(g.comment=_);break}a+=8+k+(k&1)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;const s=nr(r);if(s){const n=t-It;if(s.size=Math.min(s.size,n),s.size>0){const a=r.slice(e+It,s.size);la(a,s,this.metadataTags)}}}getCodec(){if(m(this.audioInfo),this.audioInfo.format===Oe.MULAW)return"ulaw";if(this.audioInfo.format===Oe.ALAW)return"alaw";if(this.audioInfo.format===Oe.PCM){if(this.audioInfo.sampleSizeInBytes===1)return"pcm-u8";if(this.audioInfo.sampleSizeInBytes===2)return"pcm-s16";if(this.audioInfo.sampleSizeInBytes===3)return"pcm-s24";if(this.audioInfo.sampleSizeInBytes===4)return"pcm-s32"}return this.audioInfo.format===Oe.IEEE_FLOAT&&this.audioInfo.sampleSizeInBytes===4?"pcm-f32":null}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const hr=2048;class ld{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(m(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return m(this.demuxer.dataSize!==-1),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ve}getDisposition(){return{...Et}}async getPacketAtIndex(e,t){m(e>=0),m(this.demuxer.audioInfo);const r=e*hr*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;const s=Math.min(hr*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(this.demuxer.reader.fileSize===null){let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);if(c instanceof Promise&&(c=await c),!c)return null}let n;if(t.metadataOnly)n=je;else{let c=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);c instanceof Promise&&(c=await c),m(c),n=K(c,s)}const a=e*hr/this.demuxer.audioInfo.sampleRate,o=s/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new de(n,"key",a,o,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){m(this.demuxer.audioInfo);const r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/hr,(this.demuxer.dataSize-1)/(hr*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;const s=await this.getPacketAtIndex(r,t);if(s)return s;if(r===0)return null;m(this.demuxer.reader.fileSize===null);let n=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const a=await this.getNextPacket(n,t);if(!a)break;n=a}return n}getNextPacket(e,t){m(this.demuxer.audioInfo);const r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/hr);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
|
|
140
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
141
|
+
*
|
|
142
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
143
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
144
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
145
|
+
*/const xi=7,Ot=9,_t=i=>{const e=i.filePos,t=K(i,9),r=new re(t);if(r.readBits(12)!==4095||(r.skipBits(1),r.readBits(2)!==0))return null;const a=r.readBits(1),o=r.readBits(2)+1,c=r.readBits(4);if(c===15)return null;r.skipBits(1);const u=r.readBits(3);if(u===0)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const l=r.readBits(13);r.skipBits(11);const d=r.readBits(2)+1;if(d!==1)throw new Error("ADTS frames with more than one AAC frame are not supported.");let h=null;return a===1?i.filePos-=2:h=r.readBits(16),{objectType:o,samplingFrequencyIndex:c,channelConfiguration:u,frameLength:l,numberOfAacFrames:d,crcCheck:h,startPos:e}};/*!
|
|
146
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
147
|
+
*
|
|
148
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
149
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
150
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
151
|
+
*/const ss=1024;class ud extends vt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new lr,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();m(this.firstFrameHeader),this.trackBackings=[new dd(this)]})())}async advanceReader(){if(this.lastLoadedPos===0)for(;;){let a=this.reader.requestSlice(this.lastLoadedPos,It);if(a instanceof Promise&&(a=await a),!a){this.lastSampleLoaded=!0;return}const o=nr(a);if(!o)break;this.lastLoadedPos=a.filePos+o.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,xi,Ot);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}const t=_t(e);if(!t){this.lastSampleLoaded=!0;return}if(this.reader.fileSize!==null&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);const r=Lt[t.samplingFrequencyIndex];m(r!==void 0);const s=ss/r,n={timestamp:this.nextTimestampInSamples/r,duration:s,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=ss,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let t=0;for(;;){let r=this.reader.requestSlice(t,It);if(r instanceof Promise&&(r=await r),!r)break;const s=nr(r);if(!s)break;let n=this.reader.requestSlice(r.filePos,s.size);if(n instanceof Promise&&(n=await n),!n)break;la(n,s,this.metadataTags),t=r.filePos+s.size}return this.metadataTags}finally{e()}}}class dd{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ss}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ve}getCodec(){return"aac"}getInternalCodecId(){return m(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){m(this.demuxer.firstFrameHeader);const e=Dr[this.demuxer.firstFrameHeader.channelConfiguration];return m(e!==void 0),e}getSampleRate(){m(this.demuxer.firstFrameHeader);const e=Lt[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return m(e!==void 0),e}getDisposition(){return{...Et}}async getDecoderConfig(){return m(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(e===-1)return null;const r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=je;else{let n=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(n instanceof Promise&&(n=await n),!n)return null;s=K(n,r.dataSize)}return new de(s,"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 s=vi(this.demuxer.loadedSamples,e.timestamp,a=>a.timestamp);if(s===-1)throw new Error("Packet was not created from this track.");const n=s+1;for(;n>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(n,t)}finally{r()}}async getPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{for(;;){const s=ne(this.demuxer.loadedSamples,e,n=>n.timestamp);if(s===-1&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(s,t);if(s>=0&&s+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(s,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}/*!
|
|
152
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
153
|
+
*
|
|
154
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
155
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
156
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
157
|
+
*/const Dc=i=>i===0?null:i===1?192:i>=2&&i<=5?144*2**i:i===6?"uncommon-u8":i===7?"uncommon-u16":i>=8&&i<=15?2**i:null,hd=(i,e)=>{switch(i){case 0:return e;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},zc=i=>{let e=0;const t=new re(K(i,1));for(;t.readBits(1)===1;)e++;if(e===0)return t.readBits(7);const r=[],s=e-1,n=new re(K(i,s)),a=8-e-1;for(let c=0;c<a;c++)r.unshift(t.readBits(1));for(let c=0;c<s;c++)for(let u=0;u<8;u++){const l=n.readBits(1);u<2||r.unshift(l)}return r.reduce((c,u,l)=>c|u<<l,0)},Uc=(i,e)=>{if(e==="uncommon-u16")return ke(i)+1;if(e==="uncommon-u8")return j(i)+1;if(typeof e=="number")return e;De(e),m(!1)},fd=(i,e)=>e==="uncommon-u16"?ke(i):e==="uncommon-u16-10"?ke(i)*10:e==="uncommon-u8"?j(i):typeof e=="number"?e:null,md=i=>{let t=0;for(const r of i){t^=r;for(let s=0;s<8;s++)(t&128)!==0?t=t<<1^7:t<<=1,t&=255}return t};/*!
|
|
158
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
159
|
+
*
|
|
160
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
161
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
162
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
163
|
+
*/class pd extends vt{constructor(e){super(e),this.loadedSamples=[],this.metadataPromise=null,this.trackBacking=null,this.metadataTags={},this.audioInfo=null,this.lastLoadedPos=null,this.blockingBit=null,this.readingMutex=new lr,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),m(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){let e=4;return this.metadataPromise??(this.metadataPromise=(async()=>{var t;for(;this.reader.fileSize===null||e<this.reader.fileSize;){let r=this.reader.requestSlice(e,4);if(r instanceof Promise&&(r=await r),e+=4,r===null)throw new Error(`Metadata block at position ${e} is too small! Corrupted file.`);m(r);const s=j(r),n=wt(r),a=(s&128)!==0;switch(s&127){case Pt.STREAMINFO:{let c=this.reader.requestSlice(e,n);if(c instanceof Promise&&(c=await c),m(c),c===null)throw new Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);const u=K(c,34),l=new re(u),d=l.readBits(16),h=l.readBits(16),p=l.readBits(24),y=l.readBits(24),f=l.readBits(20),w=l.readBits(3)+1;l.readBits(5);const g=l.readBits(36);l.skipBits(128);const b=new Uint8Array(42);b.set(new Uint8Array([102,76,97,67]),0),b.set(new Uint8Array([128,0,0,34]),4),b.set(u,8),this.audioInfo={numberOfChannels:w,sampleRate:f,totalSamples:g,minimumBlockSize:d,maximumBlockSize:h,minimumFrameSize:p,maximumFrameSize:y,description:b},this.trackBacking=new gd(this);break}case Pt.VORBIS_COMMENT:{let c=this.reader.requestSlice(e,n);c instanceof Promise&&(c=await c),m(c),hn(K(c,n),this.metadataTags);break}case Pt.PICTURE:{let c=this.reader.requestSlice(e,n);c instanceof Promise&&(c=await c),m(c);const u=U(c),l=U(c),d=qe.decode(K(c,l)),h=U(c),p=qe.decode(K(c,h));c.skip(16);const y=U(c),f=K(c,y);(t=this.metadataTags).images??(t.images=[]),this.metadataTags.images.push({data:f,mimeType:d,kind:u===3?"coverFront":u===4?"coverBack":"unknown",description:p});break}}if(e+=n,a){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})())}async readNextFlacFrame({startPos:e,isFirstPacket:t}){m(this.audioInfo);const r=6,s=16,n=10,a=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+s+2,o=this.audioInfo.minimumFrameSize||n,u=(this.audioInfo.maximumFrameSize||a)+s,l=await this.reader.requestSliceRange(e,s,u);if(!l)return null;const d=this.readFlacFrameHeader({slice:l,isFirstPacket:t});if(!d)return null;for(l.filePos=e+o;;){if(l.filePos>l.end-r)return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:l.end-e,isLastFrame:!0};if(j(l)===255){const p=l.filePos,y=j(l),f=this.blockingBit===1?249:248;if(y!==f){l.filePos=p;continue}l.skip(-2);const w=l.filePos-e,g=this.readFlacFrameHeader({slice:l,isFirstPacket:!1});if(!g){l.filePos=p;continue}if(this.blockingBit===0){if(g.num-d.num!==1){l.filePos=p;continue}}else if(g.num-d.num!==d.blockSize){l.filePos=p;continue}return{num:d.num,blockSize:d.blockSize,sampleRate:d.sampleRate,size:w,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const r=e.filePos,s=K(e,4),n=new re(s);if(n.readBits(15)!==32764)return null;if(this.blockingBit===null){m(t);const w=n.readBits(1);this.blockingBit=w}else if(this.blockingBit===1){if(m(!t),n.readBits(1)!==1)return null}else if(this.blockingBit===0){if(m(!t),n.readBits(1)!==0)return null}else throw new Error("Invalid blocking bit");const o=Dc(n.readBits(4));if(!o)return null;m(this.audioInfo);const c=hd(n.readBits(4),this.audioInfo.sampleRate);if(!c||(n.readBits(4),n.readBits(3),n.readBits(1)!==0))return null;const l=zc(e),d=Uc(e,o),h=fd(e,c);if(h===null||h!==this.audioInfo.sampleRate)return null;const p=e.filePos-r,y=j(e);e.skip(-p),e.skip(-1);const f=md(K(e,p));return y!==f?null:{num:l,blockSize:d,sampleRate:h}}async advanceReader(){await this.readMetadata(),m(this.lastLoadedPos!==null),m(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:this.loadedSamples.length===0});if(!t){this.lastSampleLoaded=!0;return}const r=this.loadedSamples[this.loadedSamples.length-1],n={blockOffset:r?r.blockOffset+r.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(n),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class gd{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return ve}getTimeResolution(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return m(this.demuxer.audioInfo),this.demuxer.audioInfo.totalSamples===0?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Et}}async getDecoderConfig(){return m(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(m(this.demuxer.audioInfo),e<0)return null;const r=await this.demuxer.readingMutex.acquire();try{for(;;){const s=ne(this.demuxer.loadedSamples,e,c=>c.blockOffset/this.demuxer.audioInfo.sampleRate);if(s===-1){await this.demuxer.advanceReader();continue}const n=this.demuxer.loadedSamples[s],a=n.blockOffset/this.demuxer.audioInfo.sampleRate,o=n.blockSize/this.demuxer.audioInfo.sampleRate;if(a+o<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(s,t)}}finally{r()}}async getNextPacket(e,t){const r=await this.demuxer.readingMutex.acquire();try{const s=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&s>=this.demuxer.loadedSamples.length)return null;for(;s>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(s,t)}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const r=this.demuxer.loadedSamples[e];if(!r)return null;let s;if(t.metadataOnly)s=je;else{let o=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(o instanceof Promise&&(o=await o),!o)return null;s=K(o,r.byteSize)}m(this.demuxer.audioInfo);const n=r.blockOffset/this.demuxer.audioInfo.sampleRate,a=r.blockSize/this.demuxer.audioInfo.sampleRate;return new de(s,"key",n,a,e,r.byteSize)}async getFirstPacket(e){for(;this.demuxer.loadedSamples.length===0&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}/*!
|
|
164
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
165
|
+
*
|
|
166
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
167
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
168
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
169
|
+
*/const tt=9e4,ze=188,Nc=i=>{let e="video/MP2T";const t=[...new Set(i.filter(Boolean))];return t.length>0&&(e+=`; codecs="${t.join(", ")}"`),e};/*!
|
|
170
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
171
|
+
*
|
|
172
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
173
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
174
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
175
|
+
*/const Vc="PES packet is missing PTS where it was expected. PES packets without PTS are not currently supported. If you think this file should be supported, please report it.",Va=new Set;class wd extends vt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5*1024*1024,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{const e=ze+16+1;let t=this.reader.requestSlice(0,e);t instanceof Promise&&(t=await t),m(t);const r=K(t,e);if(r[0]===71&&r[ze]===71)this.packetOffset=0,this.packetStride=ze;else if(r[0]===71&&r[ze+16]===71)this.packetOffset=0,this.packetStride=ze+16;else if(r[4]===71&&r[4+ze+4]===71)this.packetOffset=4,this.packetStride=ze+4;else throw new Error("Unreachable.");const s=256;this.minReferencePointByteDistance=s*this.packetStride;let n=this.packetOffset,a=null,o=!1,c=!1;for(;;){const u=await this.readPacketHeader(n);if(!u)break;if(u.payloadUnitStartIndicator===0){n+=this.packetStride;continue}const l=await this.readSection(n,!0,!c);if(!l)break;const d=3,h=32;let p=!1;if(!c&&l.pid!==0&&!(l.payload[0]===0&&l.payload[1]===0&&l.payload[2]===1)){const w=new re(l.payload),g=w.readAlignedByte();w.skipBits(8*g),p=w.readBits(8)===2}if(l.pid===0&&!o){const f=new re(l.payload),w=f.readAlignedByte();f.skipBits(8*w),f.skipBits(14);const g=f.readBits(10);for(f.skipBits(40);8*(g+d)-f.pos>h;){const b=f.readBits(16);f.skipBits(3);const k=f.readBits(13);if(b!==0){if(a!==null)throw new Error("Only files with a single program are supported.");a=k}}if(a===null)throw new Error("Program Association Table must link to a Program Map Table.");o=!0}else if((l.pid===a||p)&&!c){const f=new re(l.payload),w=f.readAlignedByte();f.skipBits(8*w),f.skipBits(12);const g=f.readBits(12);f.skipBits(43),f.readBits(13),f.skipBits(6);const b=f.readBits(10);for(f.skipBits(8*b);8*(g+d)-f.pos>h;){const k=f.readBits(8);f.skipBits(3);const S=f.readBits(13);f.skipBits(6);const A=f.readBits(10),_=f.pos+8*A;let I=!1,C=!1;for(;f.pos<_;){const v=f.readBits(8),M=f.readBits(8);v===106?I=!0:(v===122||v===204)&&(C=!0),f.skipBits(8*M)}let P=null;switch(k){case 27:case 36:P={type:"video",codec:k===27?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let v;if(k===3||k===4)v="mp3";else if(k===15)v="aac";else if(k===129)v="ac3";else if(k===135)v="eac3";else throw new Error("Unreachable.");P={type:"audio",codec:v,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:C?P={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:I&&(P={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:Va.has(k)||(console.warn(`Note: MPEG-TS streams with stream_type 0x${k.toString(16)} are not currently supported.`),Va.add(k))}P&&this.elementaryStreams.push({demuxer:this,pid:S,streamType:k,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:P,referencePesPackets:[]})}c=!0}else{const f=this.elementaryStreams.find(w=>w.pid===l.pid);e:if(f&&!f.initialized){const w=kr(l,!0);if(!w)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${f.pid}`);if(f.firstSection=l,f.canBeTrustedWithKeyPackets=l.randomAccessIndicator===1,this.input._initInput){const k=(await this.input._initInput._getDemuxer()).elementaryStreams.find(S=>S.pid===l.pid&&S.info.codec===f.info.codec);if(k){f.info=k.info,f.initialized=!0;break e}}const g=new hi(f,w);if(f.info.type==="video"){for(;;){const b=g;if(b.suppliedPacket=null,await g.markNextPacket(),f.info.codec==="avc"){if(!g.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(f.info.avcCodecInfo=Gn(g.suppliedPacket.data),!f.info.avcCodecInfo)continue;const k=f.info.avcCodecInfo.sequenceParameterSets[0];m(k);const S=Qn(k);f.info.width=S.displayWidth,f.info.height=S.displayHeight;const A=S.pixelAspectRatio.num,_=S.pixelAspectRatio.den;A>0&&_>0&&(A>_?(f.info.squarePixelWidth=Math.round(f.info.width*A/_),f.info.squarePixelHeight=f.info.height):(f.info.squarePixelWidth=f.info.width,f.info.squarePixelHeight=Math.round(f.info.height*_/A))),f.info.colorSpace={primaries:Qi[S.colourPrimaries],transfer:Xi[S.transferCharacteristics],matrix:$i[S.matrixCoefficients],fullRange:!!S.fullRangeFlag},f.info.reorderSize=S.maxDecFrameBuffering;break}else if(f.info.codec==="hevc"){if(!g.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(f.info.hevcCodecInfo=Xn(g.suppliedPacket.data),!f.info.hevcCodecInfo)continue;const S=f.info.hevcCodecInfo.arrays.find(_=>_.nalUnitType===Te.SPS_NUT).nalUnits[0];m(S);const A=sc(S);f.info.width=A.displayWidth,f.info.height=A.displayHeight,A.pixelAspectRatio.num>A.pixelAspectRatio.den?(f.info.squarePixelWidth=Math.round(f.info.width*A.pixelAspectRatio.num/A.pixelAspectRatio.den),f.info.squarePixelHeight=f.info.height):(f.info.squarePixelWidth=f.info.width,f.info.squarePixelHeight=Math.round(f.info.height*A.pixelAspectRatio.den/A.pixelAspectRatio.num)),f.info.colorSpace={primaries:Qi[A.colourPrimaries],transfer:Xi[A.transferCharacteristics],matrix:$i[A.matrixCoefficients],fullRange:!!A.fullRangeFlag},f.info.reorderSize=A.maxDecFrameBuffering;break}else throw new Error("Unhandled.")}f.info.decoderConfig={codec:Ln({width:f.info.width,height:f.info.height,codec:f.info.codec,codecDescription:null,colorSpace:f.info.colorSpace,avcType:1,avcCodecInfo:f.info.avcCodecInfo,hevcCodecInfo:f.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null}),codedWidth:f.info.width,codedHeight:f.info.height,colorSpace:f.info.colorSpace},(f.info.width!==f.info.squarePixelWidth||f.info.height!==f.info.squarePixelHeight)&&(f.info.decoderConfig.displayAspectWidth=f.info.squarePixelWidth,f.info.decoderConfig.displayAspectHeight=f.info.squarePixelHeight),f.initialized=!0}else{if(await g.markNextPacket(),!g.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${f.pid}`);if(f.info.codec==="aac"){const b=Me.tempFromBytes(g.suppliedPacket.data),k=_t(b);if(!k)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");f.info.aacCodecInfo={isMpeg2:!1,objectType:k.objectType},f.info.numberOfChannels=Dr[k.channelConfiguration],f.info.sampleRate=Lt[k.samplingFrequencyIndex]}else if(f.info.codec==="mp3"){const b=U(Me.tempFromBytes(g.suppliedPacket.data)),k=ws(b,g.suppliedPacket.data.byteLength);if(!k.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");f.info.numberOfChannels=k.header.channel===3?1:2,f.info.sampleRate=k.header.sampleRate}else if(f.info.codec==="ac3"){const b=lc(g.suppliedPacket.data);if(!b)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(b.fscod===3)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");f.info.numberOfChannels=$n[b.acmod]+b.lfeon,f.info.sampleRate=ys[b.fscod]}else if(f.info.codec==="eac3"){const b=dc(g.suppliedPacket.data);if(!b)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const k=hc(b);if(k===null)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");f.info.numberOfChannels=fc(b),f.info.sampleRate=k}else throw new Error("Unhandled.");f.info.decoderConfig={codec:Hn({codec:f.info.codec,codecDescription:null,aacCodecInfo:f.info.aacCodecInfo}),numberOfChannels:f.info.numberOfChannels,sampleRate:f.info.sampleRate},f.initialized=!0}}}if(c&&this.elementaryStreams.every(f=>f.initialized))break;n+=this.packetStride}if(!c)throw o?new Error("No Program Map Table found in the file."):new Error("No Program Association Table found in the file.");for(const u of this.elementaryStreams)u.info.type==="video"?this.trackBackingEntries.push(new yd(u)):this.trackBackingEntries.push(new bd(u))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();const e=await Promise.all(this.trackBackingEntries.map(t=>t.getDecoderConfig().then(r=>(r==null?void 0:r.codec)??null)));return Nc(e)}async readSection(e,t,r=!1){let s=e,n=e;const a=[];let o=0,c=null,u=!0,l=0;for(;;){const h=await this.readPacket(n);if(n+=this.packetStride,!h)break;if(c){if(h.pid!==c.pid){if(r)break;continue}if(h.payloadUnitStartIndicator===1)break}else{if(h.payloadUnitStartIndicator===0)break;c=h}const p=!!(h.adaptationFieldControl&2),y=!!(h.adaptationFieldControl&1);let f=0;if(p&&(f=1+h.body[0],h===c&&f>1&&(l=h.body[1]>>6&1)),y&&(f===0?(a.push(h.body),o+=h.body.byteLength):(a.push(h.body.subarray(f)),o+=h.body.byteLength-f)),s=n,!t&&o>=64){u=!1;break}if(vi(this.sectionEndPositions,s,g=>g)!==-1){u=!1;break}}if(u){const h=ne(this.sectionEndPositions,s,p=>p);this.sectionEndPositions.splice(h+1,0,s)}if(!c)return null;let d;if(a.length===1)d=a[0];else{const h=a.reduce((y,f)=>y+f.length,0);d=new Uint8Array(h);let p=0;for(const y of a)d.set(y,p),p+=y.length}return{startPos:e,endPos:t?s:null,pid:c.pid,payload:d,randomAccessIndicator:l}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(j(t)!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const s=ke(t),n=s>>14&1,a=s&8191,c=j(t)>>4&3;return{payloadUnitStartIndicator:n,pid:a,adaptationFieldControl:c}}async readPacket(e){let t=this.reader.requestSlice(e,ze);if(t instanceof Promise&&(t=await t),!t)return null;const r=K(t,ze);if(r[0]!==71)throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const n=(r[1]<<8)+r[2],a=n>>14&1,o=n&8191,u=r[3]>>4&3;return{payloadUnitStartIndicator:a,pid:o,adaptationFieldControl:u,body:r.subarray(4)}}}const Qt=(i,e)=>{if(i.payload.byteLength<3)return null;const t=new re(i.payload);if(t.readBits(24)!==1)return null;const s=t.readBits(8);if(t.skipBits(16),s===188||s===190||s===191||s===240||s===241||s===255||s===242||s===248)return null;t.skipBits(8);const n=t.readBits(2);t.skipBits(14);let a=null;if(n===2||n===3)a=0,t.skipBits(4),a+=t.readBits(3)*(1<<30),t.skipBits(1),a+=t.readBits(15)*32768,t.skipBits(1),a+=t.readBits(15);else if(e)throw new Error(Vc);return{sectionStartPos:i.startPos,sectionEndPos:i.endPos,pts:a,randomAccessIndicator:i.randomAccessIndicator}},kr=(i,e)=>{m(i.endPos!==null);const t=Qt(i,e);if(!t)return null;const r=new re(i.payload);r.skipBits(32);const s=r.readBits(16),n=6;r.skipBits(16);const a=r.readBits(8),o=r.pos+8*a;r.pos=o;const c=o/8;m(Number.isInteger(c));const u=i.payload.subarray(c,s>0?n+s:i.payload.byteLength);return{...t,data:u}};class Ss{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let r=0;for(const s of e.trackBackingEntries)if(s.getType()===t&&r++,m(s instanceof Ss),s.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return ve}getDisposition(){return{...Et,primary:!1}}getTimeResolution(){return tt}isRelativeToUnixEpoch(){return!1}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,r){let s;return this.allPacketsAreKeyPackets()?s="key":s=e.randomAccessIndicator===1?"key":"delta",new de(r.metadataOnly?je:e.data,s,e.pts/tt,Math.max(t/tt,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;m(t);const r=kr(t,!0);m(r);const s=new hi(this.elementaryStream,r),n=new Ls(this,s),a=await n.readNext();if(!a)return null;const o=this.createEncodedPacket(a.packet,a.duration,e);return this.packetBuffers.set(o,n),this.packetSectionStarts.set(o,a.packet.sectionStartPos),o}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){const l=await r.readNext();if(!l)return null;this.packetBuffers.delete(e);const d=this.createEncodedPacket(l.packet,l.duration,t);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}const s=this.packetSectionStarts.get(e);if(s===void 0)throw new Error("Packet was not created from this track.");const a=await this.elementaryStream.demuxer.readSection(s,!0);m(a);const o=kr(a,!0);m(o);const c=new hi(this.elementaryStream,o);r=new Ls(this,c);const u=e.sequenceNumber;for(;;){const l=await r.readNext();if(!l)return null;if(l.packet.sequenceNumber>u){const d=this.createEncodedPacket(l.packet,l.duration,t);return this.packetBuffers.set(d,r),this.packetSectionStarts.set(d,l.packet.sectionStartPos),d}}}async getNextKeyPacket(e,t){let r=e;for(;;){if(r=await this.getNextPacket(r,t),!r)return null;if(r.type==="key")return r}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,r){var S;const s=yi(e*tt),n=this.elementaryStream.demuxer,{reader:a,seekChunkSize:o}=n,c=this.elementaryStream.pid,u=async(A,_,I)=>{let C=A;for(;C<_;){const P=await n.readPacketHeader(C);if(!P)return null;if(P.pid===c&&P.payloadUnitStartIndicator===1){const v=await n.readSection(C,I);if(!v)return null;const M=Qt(v,!1);if(M&&M.pts!==null)return{pesPacketHeader:M,section:v}}C+=n.packetStride}return null},l=this.elementaryStream.firstSection;m(l);const d=Qt(l,!0);if(m(d),s<d.pts)return null;let h;const p=this.elementaryStream.referencePesPackets,y=ne(p,s,A=>A.pts),f=y!==-1?p[y]:null;if(f&&s-f.pts<tt/2)h=f.sectionStartPos;else{let A=0;if(a.fileSize!==null){const _=Math.ceil(a.fileSize/o);if(_>1){let I=0,C=_-1;for(A=I;I<=C;){const P=Math.floor((I+C)/2),v=Bs(P*o,n.packetStride)+d.sectionStartPos,M=v+o,R=await u(v,M,!1);if(!R){C=P-1;continue}R.pesPacketHeader.pts<=s?(A=P,I=P+1):C=P-1}}}h=Bs(A*o,n.packetStride)+d.sectionStartPos}const w=await u(h,a.fileSize??1/0,!1);let g=(w==null?void 0:w.pesPacketHeader)??null;g||(g=d);const b=this.getReorderSize(),k=async(A,_)=>{var O;const I=await n.readSection(A,!0);m(I);const C=kr(I,!0);m(C);const P=new hi(this.elementaryStream,C),v=new Ls(this,P);for(;!((((O=we(v.presentationOrderPackets))==null?void 0:O.pts)??-1/0)>=s||!await v.readNextPacket()););const M=us(v.presentationOrderPackets,_);if(M===-1)return null;const R=v.presentationOrderPackets[M],L=M===0?0:R.pts-v.presentationOrderPackets[M-1].pts;for(;v.decodeOrderPackets[0]!==R;)v.decodeOrderPackets.shift();v.lastDuration=L;const H=await v.readNext();m(H);const q=this.createEncodedPacket(H.packet,H.duration,r);return this.packetBuffers.set(q,v),this.packetSectionStarts.set(q,H.packet.sectionStartPos),q};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let A=g.sectionStartPos+n.packetStride;for(;;){const _=await n.readPacketHeader(A);if(!_)break e;if(_.pid===c&&_.payloadUnitStartIndicator===1){const I=await n.readSection(A,!1);if(I){const C=Qt(I,!1);if(C&&C.pts!==null){if(C.pts>s)break e;g=C,kn(this.elementaryStream,g);break}}}A+=n.packetStride}}e:for(let A=0;A<b+1;A++){let _=g.sectionStartPos-n.packetStride;for(;_>=n.packetOffset;){const I=await n.readPacketHeader(_);if(!I)break e;if(I.pid===c&&I.payloadUnitStartIndicator===1){const C=await n.readSection(_,!1);if(C){const P=Qt(C,!1);if(P&&P.pts!==null){g=P;break}}}_-=n.packetStride}}return k(g.sectionStartPos,A=>A.pts<=s)}else{let A=h,_=null;const I=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let C=null;const P=A<=d.sectionStartPos;let v,M=null;if(P)v=d,M=l;else{const H=await u(A,a.fileSize??1/0,I);v=(H==null?void 0:H.pesPacketHeader)??null,M=(H==null?void 0:H.section)??null}let R=!1,L=0;e:for(;v&&!(_!==null&&v.sectionStartPos>=_);){if(v.pts<=s){let q;if(this.elementaryStream.canBeTrustedWithKeyPackets)q=v.randomAccessIndicator===1;else{m(M);const O=kr(M,!0);m(O);const ee=new hi(this.elementaryStream,O);await ee.markNextPacket(),q=((S=ee.suppliedPacket)==null?void 0:S.randomAccessIndicator)===1}q&&(C=v)}if(v.pts>s&&(R=!0),R&&(L++,L>b))break;let H=v.sectionStartPos+n.packetStride;for(;;){const q=await n.readPacketHeader(H);if(!q)break e;if(q.pid===c&&q.payloadUnitStartIndicator===1){const O=await n.readSection(H,I);if(O){const ee=Qt(O,!1);if(ee&&ee.pts!==null){v=ee,M=O,kn(this.elementaryStream,v);break}}}H+=n.packetStride}}if(C){let H=C;if(L===0)e:for(let O=0;O<b;O++){let ee=H.sectionStartPos-n.packetStride;for(;ee>=n.packetOffset;){const ue=await n.readPacketHeader(ee);if(!ue)break e;if(ue.pid===c&&ue.payloadUnitStartIndicator===1){const xe=await n.readSection(ee,I);if(xe){const Ue=Qt(xe,!1);if(Ue&&Ue.pts!==null){H=Ue;break}}}ee-=n.packetStride}}const q=await k(H.sectionStartPos,O=>O.pts<=s&&O.randomAccessIndicator===1);return m(q),q}if(P)return null;_=A,A=Math.max(Bs(A-d.sectionStartPos-o,n.packetStride)+d.sectionStartPos,d.sectionStartPos)}}}}class yd extends Ss{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return m(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class bd extends Ss{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return m(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const kn=(i,e)=>{const t=i.referencePesPackets,r=ne(t,e.sectionStartPos,s=>s.sectionStartPos);if(r>=0){const s=t[r];if(e.pts<=s.pts)return!1;const n=i.demuxer.minReferencePointByteDistance;if(e.sectionStartPos-s.sectionStartPos<n)return!1;if(r<t.length-1){const a=t[r+1];if(a.pts<e.pts||a.sectionStartPos-e.sectionStartPos<n)return!1}}return t.splice(r+1,0,e),!0};class hi{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){const t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return m(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let r;if(this.pesPackets.length===0)r=this.startingPesPacket;else{let s=we(this.pesPackets).sectionEndPos;for(m(s!==null);;){const n=await this.demuxer.readPacketHeader(s);if(!n)return;if(n.pid===this.pid){const a=await this.demuxer.readSection(s,!0);if(!a)return;const o=kr(a,!1);if(o){r=o;break}}s+=this.demuxer.packetStride}}this.pesPackets.push(r),this.endPos+=r.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos,s=r+e;if(this.currentPos+=e,s<=t.data.byteLength)return t.data.subarray(r,s);const n=new Uint8Array(e);n.set(t.data.subarray(r));let a=t.data.byteLength-r;for(;;){this.advanceCurrentPacket();const o=this.getCurrentPesPacket(),c=e-a;if(c<=o.data.byteLength){n.set(o.data.subarray(0,c),a);break}n.set(o.data,a),a+=o.data.byteLength}return n}readU8(){let e=this.getCurrentPesPacket();const t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const t=this.getCurrentPesPacket();this.currentPesPacketPos-=t.data.byteLength}else for(;;){const t=this.getCurrentPesPacket(),r=this.currentPesPacketPos+t.data.byteLength;if(e<r)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){m(!this.suppliedPacket);const e=this.elementaryStream;if(e.info.type==="video"){const t=e.info.codec,r=1024;if(t!=="avc"&&t!=="hevc")throw new Error("Unhandled.");let s=null;for(;;){let n=this.ensureBuffered(r);if(n instanceof Promise&&(n=await n),n===0)break;const a=this.currentPos,o=this.readBytes(n),c=o.byteLength;let u=0;for(;u<c;){const l=o.indexOf(0,u);if(l===-1||l>=c)break;u=l;const d=a+u;if(u+4>=c){this.seekTo(d);break}const h=o[u+1],p=o[u+2],y=o[u+3];let f=0,w=null;if(h===0&&p===0&&y===1?(f=4,w=o[u+4]):h===0&&p===1&&(f=3,w=y),f===0){u++;continue}const g=d;if(s===null){s=g,u+=f;continue}if(w!==null){const b=t==="avc"?Br(w):Ht(w);if(t==="avc"?b===Xe.AUD:b===Te.AUD_NUT){const S=g-s;return this.seekTo(s),this.supplyPacket(S,0)}}u+=f}if(n<r)break}if(s!==null){const n=this.endPos-s;return this.seekTo(s),this.supplyPacket(n,0)}}else{const t=e.info.codec,r=128;for(;;){let s=this.ensureBuffered(r);s instanceof Promise&&(s=await s);const n=this.currentPos;for(;this.currentPos-n<s;){const a=this.readU8();if(t==="aac"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(Ot);if(c instanceof Promise&&(c=await c),c<Ot)return;const u=this.readBytes(Ot),l=_t(Me.tempFromBytes(u));if(l){this.seekTo(o);let d=this.ensureBuffered(l.frameLength);return d instanceof Promise&&(d=await d),this.supplyPacket(d,Math.round(ss*tt/e.info.sampleRate))}else this.seekTo(o+1)}else if(t==="mp3"){if(a!==255)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(ir);if(c instanceof Promise&&(c=await c),c<ir)return;const u=this.readBytes(ir),l=Z(u).getUint32(0),d=ws(l,null);if(d.header){this.seekTo(o);let h=this.ensureBuffered(d.header.totalSize);h instanceof Promise&&(h=await h);const p=d.header.audioSamplesInFrame*tt/e.info.sampleRate;return this.supplyPacket(h,Math.round(p))}else this.seekTo(o+1)}else if(t==="ac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;const u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}const l=u[4]>>6,d=u[4]&63;if(l===3||d>37){this.seekTo(o+1);continue}const h=Uu[3*d+l];m(h!==void 0),this.seekTo(o),c=this.ensureBuffered(h),c instanceof Promise&&(c=await c);const p=Math.round(Nu*tt/e.info.sampleRate);return this.supplyPacket(c,p)}else if(t==="eac3"){if(a!==11)continue;this.skip(-1);const o=this.currentPos;let c=this.ensureBuffered(5);if(c instanceof Promise&&(c=await c),c<5)return;const u=this.readBytes(5);if(u[0]!==11||u[1]!==119){this.seekTo(o+1);continue}const d=(((u[2]&7)<<8|u[3])+1)*2,p=u[4]>>6===3?3:u[4]>>4&3,y=uc[p];this.seekTo(o),c=this.ensureBuffered(d),c instanceof Promise&&(c=await c);const f=y*256,w=Math.round(f*tt/e.info.sampleRate);return this.supplyPacket(c,w)}else throw new Error("Unhandled.")}if(s<r)break}}}supplyPacket(e,t){const r=this.getCurrentPesPacket();let s;if(this.lastSuppliedPesPacket===r)m(this.nextPts!==null),s=this.nextPts;else{if(r.pts===null)throw new Error(Vc);s=r.pts,kn(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=s+t;const n=r.sectionStartPos,a=n+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e);let c=r.randomAccessIndicator;if(c===0&&!this.elementaryStream.canBeTrustedWithKeyPackets){if(this.elementaryStream.info.type==="audio")c=1;else if(this.elementaryStream.info.decoderConfig){const u=Ts(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)==="key";c=Number(u)}}this.suppliedPacket={pts:s,data:o,sequenceNumber:a,sectionStartPos:n,randomAccessIndicator:c},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class Ls{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),m(this.reorderSize>=0)}async readNext(){if(this.decodeOrderPackets.length===0&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);m(t!==-1);let r;for(t===this.presentationOrderPackets.length-1?r=this.lastDuration:(r=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=r),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const s=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(s))break;this.presentationOrderPackets.shift()}return{packet:e,duration:r}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket?e=this.context.suppliedPacket:(await this.context.markNextPacket(),e=this.context.suppliedPacket),this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(m(e);;){const t=this.presentationOrderPackets.indexOf(e);if(t!==-1&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let t=0;for(let s=1;s<this.reorderBuffer.length;s++)this.reorderBuffer[s].pts<this.reorderBuffer[t].pts&&(t=s);const r=this.reorderBuffer[t];this.presentationOrderPackets.push(r),this.reorderBuffer.splice(t,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}/*!
|
|
176
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
177
|
+
*
|
|
178
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
179
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
180
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
181
|
+
*/const Ir="application/vnd.apple.mpegurl",Oa="#EXT-X-STREAM-INF:",Wa="#EXT-X-I-FRAME-STREAM-INF:",La="#EXT-X-MEDIA:",Tn="#EXTINF:",Ha="#EXT-X-MAP:",qa="#EXT-X-KEY:",ja="#EXT-X-MEDIA-SEQUENCE:",Ka="#EXT-X-BYTERANGE:",Ga="#EXT-X-PROGRAM-DATE-TIME:",kd="#EXT-X-DISCONTINUITY",Qa="#EXT-X-TARGETDURATION:",Td="#EXT-X-ENDLIST",Xa="#EXT-X-PLAYLIST-TYPE:",Sd="#EXT-X-I-FRAMES-ONLY",Oc=i=>i.length===0||i.startsWith("#")&&!i.startsWith("#EXT");class gi{constructor(e){this._attributes={};let t="",r="",s=!1,n=!1;for(let a=0;a<e.length;a++){const o=e[a];o==='"'?n=!n:o==="="&&!s&&!n?s=!0:o===","&&!n?(t&&(this._attributes[t.trim().toLowerCase()]=r),t="",r="",s=!1):s?r+=o:t+=o}t&&(this._attributes[t.trim().toLowerCase()]=r)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(t===null)return null;const r=Number(t);return Number.isFinite(r)?r:null}merge(e){Object.assign(this._attributes,e._attributes)}}/*!
|
|
182
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
183
|
+
*
|
|
184
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
185
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
186
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
187
|
+
*/class Ad{constructor(e,t,r){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=r}async getDurationFromMetadata(e){const t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getTrackBackings(){return this.trackBackingsPromise??(this.trackBackingsPromise=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if(t.type==="video"){const r=ui(e,s=>s.getType()==="video")+1;e.push(new $a(this,t,r))}else if(t.type==="audio"){const r=ui(e,s=>s.getType()==="audio")+1;e.push(new Ya(this,t,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const r=await this.getInputForSegment(this.firstSegment).getTracks();for(const s of r)if(s.type==="video"){const n=ui(e,a=>a.getType()==="video")+1;e.push(new $a(this,{id:e.length+1,type:"video"},n))}else if(s.type==="audio"){const n=ui(e,a=>a.getType()==="audio")+1;e.push(new Ya(this,{id:e.length+1,type:"audio"},n))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(t!==void 0)return t;const r=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,r),r}async getMediaOffset(e,t){const r=e.firstSegment??e;let s;if(this.firstSegmentFirstTimestamps.has(r))s=this.firstSegmentFirstTimestamps.get(r);else{const u=this.getInputForSegment(r);s=await this.getFirstTimestampForInput(u),this.firstSegmentFirstTimestamps.set(r,s)}if(r===e)return r.timestamp-s;const n=await this.getFirstTimestampForInput(t),a=e.timestamp-r.timestamp,c=n-s-a;return Math.abs(c)<=Math.min(.25,a)?r.timestamp-s:e.timestamp-n}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class Wc{constructor(e,t,r){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=r}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var s;if((s=this.segmentedInput).firstSegment??(s.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const r=(await this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment).getTracks()).find(n=>n.type===this.decl.type&&n.number===this.number);if(!r)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=r})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t;return((t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??null})}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),m(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,r){m(e.sequenceNumber>=0),m(this.segmentedInput.firstSegment);const s=await this.segmentedInput.getMediaOffset(t,r.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,a=e.clone({timestamp:vr(e.timestamp+s,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(a,{segment:t,track:r,sourcePacket:e}),a}async getFirstPacket(e){await this.hydrate(),m(this.segmentedInput.firstSegment),m(this.firstInputTrack);const t=await this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,r){const s=this.packetInfos.get(e);if(!s)throw new Error("Packet was not created from this track.");const n=r?await s.track._backing.getNextKeyPacket(s.sourcePacket,t):await s.track._backing.getNextPacket(s.sourcePacket,t);if(n)return this.createAdjustedPacket(n,s.segment,s.track);let a=s.segment;for(;;){const o=await this.segmentedInput.getNextSegment(a,{skipLiveWait:t.skipLiveWait});if(!o)return null;const l=(await this.segmentedInput.getInputForSegment(o).getTracks()).find(h=>h.type===s.track.type&&h.number===s.track.number);if(!l){a=o;continue}const d=await l._backing.getFirstPacket(t);return d?this.createAdjustedPacket(d,o,l):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,r){let s=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!s)return null;for(await this.hydrate();s;){const n=this.segmentedInput.getInputForSegment(s),o=(await n.getTracks()).find(d=>d.type===this.firstInputTrack.type&&d.number===this.firstInputTrack.number);if(!o){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}const c=await this.segmentedInput.getMediaOffset(s,n),u=e-c,l=r?await o._backing.getKeyPacket(u,t):await o._backing.getPacket(u,t);if(!l){s=await this.segmentedInput.getPreviousSegment(s,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(l,s,o)}return null}}class $a extends Wc{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Ya extends Wc{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}const ns=Object.freeze(Object.defineProperty({__proto__:null},Symbol.toStringTag,{value:"Module"}));/*!
|
|
188
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
189
|
+
*
|
|
190
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
191
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
192
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
193
|
+
*/zn();const Za=typeof ns<"u"?ns:void 0,Lc=0,Hc=1/0;class $e extends fs{constructor(){super(...arguments),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._sizePromise=null,this.onread=null}async getSizeOrNull(){if(this._disposed)throw new We;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return e!==void 0||(await this._read(0,1,Lc,Hc),e=this._getFileSize(),m(e!==void 0)),e})())}async getSize(){if(this._disposed)throw new We;const e=await this.getSizeOrNull();if(e===null)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(t!==void 0&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Ed(this,e,t)}_dispatchRead(e,t){var r;(r=this.onread)==null||r.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new ea(this)}}class ea{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._refCount++,this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;m(e._refCount>0),e._refCount--,e._refCount===0&&(e._dispose(),e._disposed=!0),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Nr extends $e{constructor(e,t){if(typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),r=s=>{var a;if(!(s instanceof $e||s instanceof ea))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const n=s instanceof $e?s.ref():s;return(a=n.source)._usedForHls||(a._usedForHls=this._usedForHls),n};return t instanceof Promise?t.then(r):r(t)}}const Ja=(i,e)=>i.path===e.path;class xd extends Nr{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,s){if(!this._root){if(!this._rootRequest){const n=this._resolveRequest({path:this.rootPath,isRoot:!0}),a=o=>{const c=o instanceof $e?o.ref():o;return this._root=c,this._rootRequest=null,c};n instanceof Promise?this._rootRequest=n.then(a):(a(n),m(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,r,s))}return this._root.source._read(e,t,r,s)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class Bm extends $e{constructor(e){if(!(e instanceof ArrayBuffer)&&!(typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw new TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=he(e),this._view=Z(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class Fm extends $e{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Mr(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.useStreamReader!==void 0&&typeof t.useStreamReader!="boolean")throw new TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new ra({maxCacheSize:t.maxCacheSize??8*2**20,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:ta.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,r,s){return this._orchestrator.read(e,t,r,s)}async _runWorker(e){m(e.strictTarget);let t=this._readers.get(e);for(t===void 0&&("stream"in this._blob&&!fi()&&this._options.useStreamReader!==!1?t=this._blob.slice(e.currentPos).stream().getReader():t=null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:r,value:s}=await t.read();if(r)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}else{const r=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+r.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(r))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await(t==null?void 0:t.cancel())}_dispose(){this._orchestrator.dispose()}}const Pd=.5*2**20,Cd=((i,e,t)=>{if(e instanceof Error&&(e.message.includes("Failed to fetch")||e.message.includes("Load failed")||e.message.includes("NetworkError when attempting to fetch resource"))&&typeof window<"u"){let s=null;try{typeof window<"u"&&typeof window.location<"u"&&(s=new URL(t instanceof Request?t.url:t,window.location.href).origin)}catch{}if((typeof navigator<"u"&&typeof navigator.onLine=="boolean"?navigator.onLine:!0)&&s!==null&&s!==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**(i-2),16)}),eo=new Set;class qc extends Nr{constructor(e,t={}){if(typeof e!="string"&&!(e instanceof URL)&&!(typeof Request<"u"&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.requestInit!==void 0&&(!t.requestInit||typeof t.requestInit!="object"))throw new TypeError("options.requestInit, when provided, must be an object.");if(t.getRetryDelay!==void 0&&typeof t.getRetryDelay!="function")throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(t.maxCacheSize!==void 0&&(!Mr(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(t.parallelism!==void 0&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(t.fetchFn!==void 0&&typeof t.fetchFn!="function")throw new TypeError("options.fetchFn, when provided, must be a function.");const r=e instanceof Request?e.url:e instanceof URL?e.href:e;super(r,n=>new qc(n.path,this._options)),this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Cd;const s=2;this._orchestrator=new ra({maxCacheSize:t.maxCacheSize??64*2**20,maxWorkerCount:t.parallelism??s,runWorker:this._runWorker.bind(this),prefetchProfile:ta.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,r,s){return this._orchestrator.read(e,t,r,s)}async _runWorker(e){for(;;){const t=new AbortController,r=await Zl(this._options.fetchFn??fetch,this._url,Yl(this._options.requestInit??{},{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);e:if(this._orchestrator.fileSize===null){const n=r.headers.get("Content-Range");if(n){const o=/\/(\d+)/.exec(n);if(o){this._orchestrator.supplyFileSize(Number(o[1]));break e}}const a=r.headers.get("Content-Length");a&&this._orchestrator.supplyFileSize(e.currentPos+Number(a))}if(this._fileSizeDetermined=!0,r.status!==206){if(!this._usedForHls){const n=new URL(this._url instanceof Request?this._url.url:this._url,typeof window<"u"?window.location.href:void 0);n.origin!=="null"&&!(n.pathname.endsWith(".m3u8")||n.pathname.endsWith(".m3u"))&&(eo.has(n.origin)||(console.log(this._usedForHls,this._url,n.pathname),console.warn(`HTTP server (origin ${n.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),eo.add(n.origin)))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,this._orchestrator.fileSize!==null?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const s=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}let n;try{n=await s.read()}catch(c){if(this._disposed)throw c;const u=this._getRetryDelay(1,c,this._url);if(u!==null){console.error("Error while reading response stream. Attempting to resume.",c),await Vn(1e3*u);break}else throw c}if(e.aborted)continue;const{done:a,value:o}=n;if(a){if(e.currentPos>=e.targetPos){this._orchestrator.onWorkerFinished(e);return}if(e.strictTarget)break;this._orchestrator.onWorkerFinished(e);return}this._dispatchRead(e.currentPos,e.currentPos+o.length),this._orchestrator.supplyWorkerData(e,o)}}}_dispose(){this._orchestrator.dispose()}}class jc extends Nr{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Mr(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!Za.fs)throw new Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,r=>new jc(r.path,t)),this._fileHandle=null,this._streamSource=new _d({getSize:async()=>(this._fileHandle=await Za.fs.open(e,"r"),(await this._fileHandle.stat()).size),read:async(r,s)=>{m(this._fileHandle);const n=new Uint8Array(s-r);return await this._fileHandle.read(n,0,s-r,r),n},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,t,r,s){return this._streamSource._read(e,t,r,s)}_getFileSize(){return this._streamSource._getFileSize()}_dispose(){var e;this._streamSource._dispose(),(e=this._fileHandle)==null||e.close(),this._fileHandle=null}}class _d extends $e{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(typeof e.getSize!="function")throw new TypeError("options.getSize must be a function.");if(typeof e.read!="function")throw new TypeError("options.read must be a function.");if(e.dispose!==void 0&&typeof e.dispose!="function")throw new TypeError("options.dispose, when provided, must be a function.");if(e.maxCacheSize!==void 0&&(!Mr(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 ra({maxCacheSize:e.maxCacheSize??8*2**20,maxWorkerCount:2,prefetchProfile:ta[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,r,s){if(this._orchestrator.fileSize!==null)return this._orchestrator.read(e,t,r,s);const n=this._options.getSize();if(n instanceof Promise)return n.then(a=>{if(!Number.isInteger(a)||a<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=a,this._orchestrator.read(e,t,r,s)});if(!Number.isInteger(n)||n<0)throw new TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=n,this._orchestrator.read(e,t,r,s)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){const t=e.currentPos,r=e.targetPos;let s=this._options.read(e.currentPos,r);if(s instanceof Promise&&(s=await s),e.aborted)break;if(s instanceof Uint8Array){if(s=he(s),s.length!==r-e.currentPos)throw new Error(`options.read returned a Uint8Array with unexpected length: Requested ${r-e.currentPos} bytes, but got ${s.length}.`);this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}else if(s instanceof ReadableStream){const n=s.getReader();for(;e.currentPos<r&&!e.aborted;){const{done:a,value:o}=await n.read();if(a){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(!(o instanceof Uint8Array))throw new TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;const c=he(o);this._dispatchRead(e.currentPos,e.currentPos+c.length),this._orchestrator.supplyWorkerData(e,c)}}else throw new TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){var e,t;this._orchestrator.dispose(),(t=(e=this._options).dispose)==null||t.call(e)}}class Id extends $e{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(t.maxCacheSize!==void 0&&(!Mr(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??32*2**20}_getFileSize(){return this._endIndex}_read(e,t){if(this._endIndex!==null&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const r=ne(this._cache,e,l=>l.start),s=r!==-1?this._cache[r]:null;if(s&&s.start<=e&&t<=s.end)return{bytes:s.bytes,view:s.view,offset:s.start};let n=e;const a=new Uint8Array(t-e);if(r!==-1)for(let l=r;l<this._cache.length;l++){const d=this._cache[l];if(d.start>=t)break;const h=Math.max(e,d.start);h>n&&this._throwDueToCacheMiss();const p=Math.min(t,d.end);h<p&&(a.set(d.bytes.subarray(h-d.start,p-d.start),h-e),n=p)}if(n===t)return{bytes:a,view:Z(a),offset:e};this._currentIndex>n&&this._throwDueToCacheMiss();const{promise:o,resolve:c,reject:u}=ge();return this._pendingSlices.push({start:e,end:t,bytes:a,resolve:c,reject:u}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(l=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(d=>d.reject(l)),this._pendingSlices.length=0;else throw l})),o}_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._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const n of this._pendingSlices)n.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const r=this._currentIndex,s=this._currentIndex+t.byteLength;this._dispatchRead(r,s);for(let n=0;n<this._pendingSlices.length;n++){const a=this._pendingSlices[n],o=Math.max(r,a.start),c=Math.min(s,a.end);o<c&&(a.bytes.set(t.subarray(o-r,c-r),o-a.start),c===a.end&&(a.resolve({bytes:a.bytes,view:Z(a.bytes),offset:a.start}),this._pendingSlices.splice(n,1),n--))}for(this._cache.push({start:r,end:s,bytes:t,view:Z(t),age:0});this._cache.length>0;){const n=this._cache[0];if(this._maxRequestedIndex-n.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){var e;this._pendingSlices.length=0,this._cache.length=0,(e=this._reader)==null||e.cancel()}}const ta={none:(i,e)=>({start:i,end:e}),fileSystem:(i,e)=>(i=Math.floor((i-65536)/65536)*65536,e=Math.ceil((e+65536)/65536)*65536,{start:i,end:e}),network:(i,e,t)=>{i=Math.max(0,Math.floor((i-65536)/65536)*65536);for(const s of t){const a=Math.max((s.startPos+s.targetPos)/2,s.targetPos-8388608);if(on(i,e,a,s.targetPos)){const o=s.targetPos-s.startPos,c=Math.ceil((o+1)/8388608)*8388608,u=2**Math.ceil(Math.log2(o+1)),l=Math.min(u,c);e=Math.max(e,s.startPos+l)}}return e=Math.max(e,i+Pd),{start:i,end:e}}};class ra{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,r,s){m(!this.disposed);const n=this.options.prefetchProfile(e,t,this.workers),a=Math.max(n.start,r),o=Math.min(n.end,this.fileSize??1/0,s);m(a<=e&&t<=o);let c=null;const u=ne(this.cache,e,A=>A.start),l=u!==-1?this.cache[u]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,c={bytes:l.bytes,view:l.view,offset:l.start});const d=ne(this.cache,a,A=>A.start),h=c?null:new Uint8Array(t-e);let p=0,y=a;const f=[];if(d!==-1){for(let A=d;A<this.cache.length;A++){const _=this.cache[A];if(_.start>=o)break;if(_.end<=a)continue;const I=Math.max(a,_.start),C=Math.min(o,_.end);if(m(I<=C),y<I&&f.push({start:y,end:I}),y=C,h){const P=Math.max(e,_.start),v=Math.min(t,_.end);if(P<v){const M=P-e;h.set(_.bytes.subarray(P-_.start,v-_.start),M),M===p&&(p=v-e)}}_.age=this.nextAge++}y<o&&f.push({start:y,end:o})}else f.push({start:a,end:o});if(h&&p>=h.length&&(c={bytes:h,view:Z(h),offset:e}),f.length===0)return m(c),c;const{promise:w,resolve:g,reject:b}=ge(),k=[];for(const A of f){const _=Math.max(e,A.start),I=Math.min(t,A.end);_===A.start&&I===A.end?k.push(A):_<I&&k.push({start:_,end:I})}const S=h&&{start:e,bytes:h,holes:k,resolve:g,reject:b};e:for(const A of f){for(const C of this.workers)if(this.checkHoleAgainstWorker(C,A,S?[S]:[])){this.checkQueuedReadsAgainstWorker(C);continue e}const _=A.end<o||this.fileSize!==null,I=this.createWorker(A.start,A.end,_);if(I)S&&(I.pendingSlices=[S]),this.runWorker(I);else{let C=ne(this.queuedReads,A.start,v=>v.hole.start),P=C!==-1?this.queuedReads[C]:null;for(P&&A.start<=P.hole.end?(P.hole.end=Math.max(P.hole.end,A.end),P.strictTarget&&(P.strictTarget=_),S&&P.pendingSlices.push(S)):(C++,P={hole:{start:A.start,end:A.end},strictTarget:_,pendingSlices:S?[S]:[],age:this.nextAge++},this.queuedReads.splice(C,0,P));C+1<this.queuedReads.length;){const v=this.queuedReads[C+1];if(v.hole.start>P.hole.end)break;P.hole.end=Math.max(P.hole.end,v.hole.end),P.pendingSlices.push(...v.pendingSlices),P.strictTarget&&(P.strictTarget=v.strictTarget),P.age=Math.min(P.age,v.age),this.queuedReads.splice(C+1,1)}}}return c||(m(h),c=w.then(A=>A&&{bytes:A,view:Z(A),offset:e})),c}checkHoleAgainstWorker(e,t,r){if(on(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let n=0;n<r.length;n++){const a=r[n];e.pendingSlices.includes(a)||e.pendingSlices.push(a)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let r=0;r<this.queuedReads.length;r++){const s=this.queuedReads[r];if(this.checkHoleAgainstWorker(e,s.hole,s.pendingSlices))this.queuedReads.splice(r,1),r--,t=!0;else if(t)break}}createWorker(e,t,r){if(this.workers.length>=this.options.maxWorkerCount){let n=null,a=null;for(let o=0;o<this.workers.length;o++){const c=this.workers[o];!c.running&&c.pendingSlices.length===0&&(!n||c.age<n.age)&&(a=o,n=c)}if(n)m(a!==null),m(n.pendingSlices.length===0),this.workers.splice(a,1);else return null}const s={startPos:e,currentPos:e,targetPos:t,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(s),s}runWorker(e){m(!e.running),m(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(r=>r.reject(t)),e.pendingSlices.length=0;else throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let t=0;for(let n=1;n<this.queuedReads.length;n++)this.queuedReads[n].age<this.queuedReads[t].age&&(t=n);const r=this.queuedReads[t];this.queuedReads.splice(t,1);const s=this.createWorker(r.hole.start,r.hole.end,r.strictTarget);m(s),s.pendingSlices=r.pendingSlices,this.runWorker(s)}})}consolidateEverythingIntoOneWorker(e){const t=new Set(e.pendingSlices);for(let r=0;r<this.workers.length;r++){const s=this.workers[r];if(s!==e){for(const n of s.pendingSlices)t.add(n);s.aborted=!0,s.pendingSlices.length=0,this.workers.splice(r,1),r--}}for(let r=0;r<this.queuedReads.length;r++){const s=this.queuedReads[r];for(const n of s.pendingSlices)t.add(n)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){m(!e.aborted);const r=e.currentPos,s=r+t.length;this.insertIntoCache({start:r,end:s,bytes:t,view:Z(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;n<e.pendingSlices.length;n++){const a=e.pendingSlices[n],o=Math.max(r,a.start),c=Math.min(s,a.start+a.bytes.length);o<c&&a.bytes.set(t.subarray(o-r,c-r),o-a.start);for(let u=0;u<a.holes.length;u++){const l=a.holes[u];r<=l.start&&s>l.start&&(l.start=s),l.end<=l.start&&(a.holes.splice(u,1),u--)}a.holes.length===0&&(a.resolve(a.bytes),e.pendingSlices.splice(n,1),n--)}for(let n=0;n<this.workers.length;n++){const a=this.workers[n];e===a||a.running||on(r,s,a.currentPos,a.targetPos)&&(this.workers.splice(n,1),n--)}}supplyFileSize(e){m(this.fileSize===null),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let r=0;r<t.pendingSlices.length;r++){const s=t.pendingSlices[r];for(const n of s.holes)if(n.end>e){s.resolve(null),t.pendingSlices.splice(r,1),r--;break}}}for(let t=0;t<this.queuedReads.length;t++){const r=this.queuedReads[t];if(r.hole.start>=e){for(const s of r.pendingSlices)s.resolve(null);this.queuedReads.splice(t,1),t--}else if(r.hole.end>e){r.hole.end=e,r.strictTarget=!0;for(let s=0;s<r.pendingSlices.length;s++){const n=r.pendingSlices[s];n.start>=e&&(n.resolve(null),r.pendingSlices.splice(s,1),s--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);m(t!==-1),e.running=!1,this.workers.splice(t,1),this.fileSize===null&&this.supplyFileSize(e.currentPos);for(const r of e.pendingSlices)r.resolve(null)}insertIntoCache(e){if(this.options.maxCacheSize===0)return;let t=ne(this.cache,e.start,r=>r.start)+1;if(t>0){const r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){const s=new Uint8Array(e.end-r.start);s.set(r.bytes,0),s.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=s,r.view=Z(s),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 s=this.cache[r];if(e.end<=s.start)break;if(e.end>=s.end){this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length,r--;continue}const n=new Uint8Array(s.end-e.start);n.set(e.bytes,0),n.set(s.bytes,s.start-e.start),this.currentCacheSize-=e.end-s.start,e.bytes=n,e.view=Z(n),e.end=s.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let r=0,s=this.cache[0];for(let n=1;n<this.cache.length;n++){const a=this.cache[n];a.age<s.age&&(r=n,s=a)}if(this.currentCacheSize-s.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(r,1),this.currentCacheSize-=s.bytes.length}}dispose(){for(const e of this.workers)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}class Ed extends $e{constructor(e,t,r){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=r??null}_getFileSize(){const e=this._baseSource._getFileSize();return e===void 0?this._length!==null?this._length:void 0:e===null?this._length!==null?this._length:null:Ie(e-this._offset,0,this._length??1/0)}_read(e,t,r,s){if(this._length!==null&&t>this._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+r,this._offset+s);return n instanceof Promise?n.then(a=>a?(a.offset-=this._offset,a):null):n?(n.offset-=this._offset,n):null}_dispose(){var e;(e=this._ref)==null||e.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}/*!
|
|
194
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
195
|
+
*
|
|
196
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
197
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
198
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
199
|
+
*/var to=function(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),i.stack.push({value:e,dispose:r,async:t})}else t&&i.stack.push({async:!0});return e},ro=(function(i){return function(e){function t(a){e.error=e.hasError?new i(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,s=0;function n(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(n);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=i,r.suppressed=e,r});const vd=/^0[xX][0-9a-fA-F]+$/,Bd=/^data:.*;base64,/i;class io extends Ad{constructor(e,t,r,s){super(e.input,t,r),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.demuxer=e,this.nextLines=s}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await Vn(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const g={stack:[],error:void 0,hasError:!1};try{const b=to(g,await this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),S=await new Ki(b.source).requestEntireFile();m(S),e=gl(S,S.length,{ignore:Oc})}catch(b){g.error=b,g.hasError=!0}finally{ro(g)}}let t=!1,r=0,s=null,n=null,a=0,o=null,c=null,u=null,l=null,d=null,h=null,p=!1,y=we(this.segments)??null;const f=g=>{const b=g.indexOf("@"),k=Number(b===-1?g:g.slice(0,b));if(!Number.isInteger(k)||k<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${g}'.`);let S=null;if(b!==-1&&(S=Number(g.slice(b+1)),!Number.isInteger(S)||S<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${g}'.`);return{length:k,offset:S}},w=g=>{a=g,y&&(m(y.sequenceNumber!==null),y.sequenceNumber<g&&(r=y.timestamp+y.duration,o=y.firstSegment,c=y.initSegment,d=y.lastProgramDateTimeSeconds,y=null))};for(let g=0;g<e.length;g++){const b=e[g];if(!t){if(b!=="#EXTM3U")throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");t=!0;continue}if(!b.startsWith("#")){if(!y){if(s===null)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let k=n;if(k&&k.method==="AES-128"&&!k.iv){const I=new Uint8Array(ut),C=Z(I);C.setUint32(8,Math.floor(a/2**32)),C.setUint32(12,a),k={...k,iv:I}}const A={path:Fe(this.path,b),offset:(l==null?void 0:l.offset)??0,length:(l==null?void 0:l.length)??null},_={timestamp:r,relativeToUnixEpoch:d!==null,firstSegment:o,sequenceNumber:a,location:A,duration:s,encryption:k,initSegment:c,lastProgramDateTimeSeconds:d};o??(o=_),r+=s,this.segments.push(_)}s=null,l===null?u=null:l=null,w(a+1)}if(b.startsWith(Tn)){if(y){p=!0;continue}p||(d===null&&a>0&&h!==null&&(r=a*h),p=!0);const k=b.slice(Tn.length),S=k.indexOf(","),A=S===-1?k:k.slice(0,S),_=Number(A);if(!Number.isFinite(_)||_<0)throw new Error(`Invalid #EXTINF tag duration '${A}'.`);s=_}else if(b.startsWith(Ha)){const k=new gi(b.slice(Ha.length)),S=k.get("uri");if(!S)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const A=k.get("byterange");let _=null;if(A!==null&&(_=f(A)),_&&_.offset===null)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){const C={path:Fe(this.path,S),offset:(_==null?void 0:_.offset)??0,length:(_==null?void 0:_.length)??null};if((n==null?void 0:n.method)==="AES-128"&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");c={timestamp:r,relativeToUnixEpoch:d!==null,firstSegment:null,sequenceNumber:null,location:C,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:d}}s=null,l===null?u=null:l=null}else if(b.startsWith(qa)){const k=new gi(b.slice(qa.length)),S=k.get("method");if(S==="NONE")n=null;else if(S==="AES-128"){const A=k.get("uri");if(!A)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let _=null;const I=k.get("iv");if(I){if(!vd.test(I))throw new Error(`Unsupported IV format '${I}'.`);let P=I.slice(2);P=P.padStart(ut*2,"0"),_=new Uint8Array(ut);for(let v=0;v<ut;v++){const M=-ut*2+v;_[v]=parseInt(P.slice(M,M+2),16)}}const C=k.get("keyformat")??"identity";if(C!=="identity")throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");n={method:"AES-128",keyUri:Fe(this.path,A),iv:_,keyFormat:C}}else if(S==="SAMPLE-AES"||S==="SAMPLE-AES-CTR"){const A=k.get("uri");if(!A)throw new Error(`Invalid #EXT-X-KEY: ${S} requires a URI attribute.`);if((k.get("keyformat")??"identity")==="identity")throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let I=null;if(Bd.test(A)){const C=A.indexOf(","),P=Ji(A.slice(C+1));if(P.length>=8&&P[4]===112&&P[5]===115&&P[6]===115&&P[7]===104){const v=Z(P).getUint32(0);I=pc(P.subarray(8,Math.min(v,P.length)))}}n={method:S,psshBox:I}}else throw new Error(`Unsupported encryption method '${S}'. If you think this method should be supported, please raise an issue.`)}else if(b.startsWith(ja)){const k=b.slice(ja.length),S=Number(k);if(!Number.isInteger(S)||S<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${k}'.`);w(S)}else if(b.startsWith(Ka)){const k=f(b.slice(Ka.length));if(k.offset===null){if(u===null)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");k.offset=u}l=k,u=k.offset+k.length}else if(b.startsWith(Ga)){if(y)continue;const k=b.slice(Ga.length),S=Date.parse(k);if(!Number.isFinite(S))continue;const A=S/1e3;if(d===A)continue;if(d===null&&this.segments.length>0){const _=we(this.segments),I=_.timestamp+_.duration,C=A-I;for(const P of this.segments)P.timestamp+=C,P.relativeToUnixEpoch=!0;r+=C}d=A,r=A}else if(b===kd)o=null;else if(b.startsWith(Qa)){const k=b.slice(Qa.length),S=Number(k);if(!Number.isFinite(S)||S<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${k}'.`);this.refreshInterval=S,h=S}else if(b===Td){this.streamHasEnded=!0;break}else b.startsWith(Xa)&&b.slice(Xa.length).toLowerCase()==="vod"&&(this.streamHasEnded=!0)}if(!t)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return this.segments.length===0&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){this.segments.length===0&&await this.runUpdateSegments();let r=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const s=ne(this.segments,e,a=>a.timestamp);if(s===-1)return null;if(s<this.segments.length-1||this.streamHasEnded||r)return this.segments[s];const n=this.segments[s];if(e<n.timestamp+n.duration)return n;await this.runUpdateSegments(),t.skipLiveWait&&(r=!0)}}async getNextSegment(e,t){const r=this.segments.indexOf(e);m(r!==-1);const s=r+1;let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(s<this.segments.length)return this.segments[s];if(this.streamHasEnded||n)return null;await this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}}async getPreviousSegment(e){const t=this.segments.indexOf(e);return m(t!==-1),this.segments[t-1]??null}getInputForSegment(e){var c;const t=e,r=this.inputCache.find(u=>u.segment===t);if(r)return r.age=this.nextInputCacheAge++,r.input;let s=null;(t.initSegment||t.firstSegment)&&(s=this.getInputForSegment(t.initSegment??t.firstSegment));const n={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:((c=this.input._formatOptions.isobmff)==null?void 0:c.resolveKeyId)&&(u=>{if(!t.encryption||!(t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR")||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(u);let l=u.psshBoxes;const{psshBox:d}=t.encryption;return(d.keyIds===null||d.keyIds.includes(u.keyId))&&!l.some(h=>gc(h,d))&&(l=[...l,d]),this.input._formatOptions.isobmff.resolveKeyId({...u,psshBoxes:l})})}},a=new _s({source:new xd(t.location.path,async u=>{m(u.isRoot);const l={...u,isRoot:!1};let d;const h=t.location.offset>0||t.location.length!==null;if(!t.encryption||t.encryption.method==="SAMPLE-AES"||t.encryption.method==="SAMPLE-AES-CTR"){if(d=await this.input._getSourceCached(l),h){const y=d.source.slice(t.location.offset,t.location.length??void 0).ref();d.free(),d=y}}else if(t.encryption.method==="AES-128"){const p=t.encryption;m(p.iv);let y=await this.input._getSourceCached(l);if(h){const b=y.source.slice(t.location.offset,t.location.length??void 0).ref();y.free(),y=b}const f=new Ki(y.source),w=Lu(f,async()=>{const g={stack:[],error:void 0,hasError:!1};try{const b=to(g,await this.input._getSourceCached({path:p.keyUri,isRoot:!1},Ah),!1),S=await new Ki(b.source).requestSlice(0,ut);if(!S)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:K(S,ut),iv:p.iv}}catch(b){g.error=b,g.hasError=!0}finally{ro(g)}},()=>{y.free()});d=new Id(w).ref()}else m(!1);return d}),formats:this.input._formats.filter(u=>!(u instanceof Yc)),initInput:s??void 0,formatOptions:n});if(a._onFormatDetermined=u=>{var l,d;if((((l=t.encryption)==null?void 0:l.method)==="SAMPLE-AES"||((d=t.encryption)==null?void 0:d.method)==="SAMPLE-AES-CTR")&&!u._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:a,age:this.nextInputCacheAge++}),this.inputCache.length>4){const u=Un(this.inputCache,l=>l.age);m(u!==-1),this.inputCache.splice(u,1)}return a}async getLiveRefreshInterval(){return this.getRemainingWaitTimeMs()===0&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}/*!
|
|
200
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
201
|
+
*
|
|
202
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
203
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
204
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
205
|
+
*/class Fd extends vt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{m(this.input._rootSource instanceof Nr);const{rootPath:e}=this.input._rootSource,t=await this.input._reader.requestEntireFile();m(t);const r=gl(t,t.length,{ignore:Oc}),s=[],n=[];for(let d=1;d<r.length;d++){const h=r[d];if(h.startsWith(Oa)){const p=d,y=r[++d];if(y===void 0)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const f=Fe(e,y),w=new gi(h.slice(Oa.length));if(w.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");s.push({fullPath:f,attributes:w,lineNumber:p,hasOnlyKeyPackets:!1})}else if(h.startsWith(Wa)){const p=new gi(h.slice(Wa.length)),y=p.get("uri");if(y===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(p.getAsNumber("bandwidth")===null)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const w=Fe(e,y);s.push({fullPath:w,attributes:p,lineNumber:d,hasOnlyKeyPackets:!0})}else if(h.startsWith(La)){const p=new gi(h.slice(La.length));if(p.get("type")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(p.get("group-id")===null)throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let w=null;const g=p.get("uri");g!==null&&(w=Fe(e,g)),n.push({fullPath:w,attributes:p,lineNumber:d})}else if(h!==Sd){if(h.startsWith(Tn)){const p=new io(this,e,null,r);this.segmentedInputs=[p],this.hasMasterPlaylist=!1,this.trackBackings=await p.getTrackBackings();return}}}const a=[...new Set(n.filter(d=>d.attributes.get("type").toLowerCase()==="video").map(d=>d.attributes.get("group-id")))],o=[...new Set(n.filter(d=>d.attributes.get("type").toLowerCase()==="audio").map(d=>d.attributes.get("group-id")))],c=await Promise.all(s.map(async(d,h)=>{const p=[],y=d.attributes.get("codecs");let f;if(y)f=y.split(",").map(P=>P.trim());else{const v=await this.getSegmentedInputForPath(d.fullPath).getTrackBackings(),M=await Promise.all(v.map(async R=>({track:R,codec:await R.getCodec()})));f=await Promise.all(M.filter(R=>R.codec!==null).map(R=>R.track.getDecoderConfig().then(L=>L.codec)))}const w=d.attributes.get("video"),g=d.attributes.get("audio"),b=f.some(P=>Se.includes(xt(P))),k=f.some(P=>Ce.includes(xt(P)));if(w!==null&&!b){if(!a.includes(w))throw new Error(`Invalid M3U8 file; variant stream references video group "${w}" which is not defined in any #EXT-X-MEDIA tags.`);const P=n.find(v=>{const M=v.attributes.get("group-id"),R=v.attributes.get("type");return M===w&&R.toLowerCase()==="video"});e:if(P){const v=P.attributes.get("uri");if(v===null)break e;const M=Fe(e,v),H=(await this.getSegmentedInputForPath(M).getTrackBackings()).find(O=>O.getType()==="video");if(!H||await H.getCodec()===null)break e;const q=await H.getDecoderConfig().then(O=>(O==null?void 0:O.codec)??null);m(q!==null),f.push(q)}}if(g!==null&&!k){if(!o.includes(g))throw new Error(`Invalid M3U8 file; variant stream references audio group "${g}" which is not defined in any #EXT-X-MEDIA tags.`);const P=n.find(v=>{const M=v.attributes.get("group-id"),R=v.attributes.get("type");return M===g&&R.toLowerCase()==="audio"});e:if(P){const v=P.attributes.get("uri");if(v===null)break e;const M=Fe(e,v),H=(await this.getSegmentedInputForPath(M).getTrackBackings()).find(O=>O.getType()==="audio");if(!H||await H.getCodec()===null)break e;const q=await H.getDecoderConfig().then(O=>(O==null?void 0:O.codec)??null);m(q!==null),f.push(q)}}f=[...new Set(f)];let S=null,A=null;const _=d.attributes.getAsNumber("bandwidth");m(_!==null);const I=d.attributes.getAsNumber("average-bandwidth"),C=d.attributes.get("name");for(const P of f){const v=xt(P);if(v!==null){if(Se.includes(v)){if(S!==null)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");S=P;const M=d.attributes.get("video");if(M===null){const R=d.attributes.get("resolution");let L=null,H=null;if(R){const q=R.match(/^(\d+)x(\d+)$/);q&&(L=Number(q[1]),H=Number(q[2]))}p.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ve,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(h),peakBitrate:_,averageBitrate:I,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:L,height:H}})}else{if(!a.includes(M))throw new Error(`Invalid M3U8 file; variant stream references video group "${M}" which is not defined in any #EXT-X-MEDIA tags.`);for(const R of n){const L=R.attributes.get("group-id"),H=R.attributes.get("type");if(L!==M||H.toLowerCase()!=="video")continue;const q=R.attributes.get("resolution")??d.attributes.get("resolution");let O=null,ee=null;if(q){const ue=q.match(/^(\d+)x(\d+)$/);ue&&(O=Number(ue[1]),ee=Number(ue[2]))}p.push({id:-1,demuxer:this,backingTrack:null,default:Ni(R.attributes),autoselect:Ni(R.attributes)||so(R.attributes),languageCode:no(R.attributes.get("language")),lineNumber:R.lineNumber,fullPath:R.fullPath??d.fullPath,fullCodecString:S,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:R.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"video",width:O,height:ee}})}}}else if(Ce.includes(v)){if(A!==null)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");A=P;const M=d.attributes.get("audio");if(M===null){const R=d.attributes.get("channels"),L=R!==null?Number(R.split("/")[0]):null;p.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ve,lineNumber:d.lineNumber,fullPath:d.fullPath,fullCodecString:A,pairingMask:1n<<BigInt(h),peakBitrate:_,averageBitrate:I,name:C,hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:L!==null&&Number.isInteger(L)&&L>0?L:null}})}else{if(!o.includes(M))throw new Error(`Invalid M3U8 file; variant stream references audio group "${M}" which is not defined in any #EXT-X-MEDIA tags.`);for(const R of n){const L=R.attributes.get("group-id"),H=R.attributes.get("type");if(L!==M||H.toLowerCase()!=="audio")continue;const q=R.attributes.get("channels")??d.attributes.get("channels"),O=q!==null?Number(q.split("/")[0]):null;p.push({id:-1,demuxer:this,backingTrack:null,default:Ni(R.attributes),autoselect:Ni(R.attributes)||so(R.attributes),languageCode:no(R.attributes.get("language")),lineNumber:R.lineNumber,fullPath:R.fullPath??d.fullPath,fullCodecString:A,pairingMask:1n<<BigInt(h),peakBitrate:null,averageBitrate:null,name:R.attributes.get("name"),hasOnlyKeyPackets:d.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:O!==null&&Number.isInteger(O)&&O>0?O:null}})}}}}}return p})),u=[],l=d=>{const h=u.find(p=>p.fullPath===d.fullPath&&p.info.type===d.info.type);h?(h.pairingMask|=d.pairingMask,h.default||(h.default=d.default),h.autoselect||(h.autoselect=d.autoselect),h.lineNumber=Math.min(h.lineNumber,d.lineNumber),d.peakBitrate!==null&&(h.peakBitrate=Math.max(h.peakBitrate??-1/0,d.peakBitrate)),d.averageBitrate!==null&&(h.averageBitrate=Math.max(h.averageBitrate??-1/0,d.averageBitrate)),h.languageCode===ve&&(h.languageCode=d.languageCode)):(d.id=u.length+1,u.push(d))};for(const d of c)for(const h of d)l(h);u.sort((d,h)=>d.lineNumber-h.lineNumber),this.trackBackings=[];for(const d of u)d.info.type==="video"?this.trackBackings.push(new Gc(d)):this.trackBackings.push(new Qc(d));this.internalTracks=u})())}async getTrackBackings(){return await this.readMetadata(),m(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(s=>s.path===e);if(t)return t;let r=null;return this.internalTracks&&(r=this.internalTracks.filter(n=>n.fullPath===e).map(n=>({id:n.id,type:n.info.type}))),t=new io(this,e,r,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return Ir}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Kc{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const s=(await e.getTrackBackings()).filter(n=>n.getType()===this.getType());if(s.length===1)t=s[0];else if(this instanceof Gc){for(const n of s)if(await n.getCodec()===this.getCodec()){t=n;break}}else{m(this instanceof Qc);for(const n of s)if(await n.getCodec()===this.getCodec()){t=n;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...Et,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){m(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const r of this.internalTrack.demuxer.internalTracks)if(r.info.type===e&&t++,r===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class Gc extends Kc{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return xt(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class Qc extends Kc{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return xt(this.internalTrack.fullCodecString)}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels!==null?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const Ni=i=>{const e=i.get("default");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${e}".`)},so=i=>{const e=i.get("autoselect");if(e===null)return!1;const t=e.toUpperCase();if(t==="YES")return!0;if(t==="NO")return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${e}".`)},no=i=>{if(i===null)return ve;const e=i.split("-")[0];return e||ve};/*!
|
|
206
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
207
|
+
*
|
|
208
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
209
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
210
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
211
|
+
*/class ft{constructor(){this._isIsobmff=!1}}class Xc extends ft{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return null;t.skip(4);const r=ye(t,4);return r!=="ftyp"&&r!=="styp"?null:ye(t,4)}_createDemuxer(e){return new Yn(e)}}class Rd extends Xc{async _canReadInput(e){const t=await this._getMajorBrand(e);if(t!==null)return t!=="qt ";let r=e._reader.requestSlice(4,4);if(r instanceof Promise&&(r=await r),!r)return!1;const s=ye(r,4);return s==="moof"||s==="sidx"}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Md extends Xc{async _canReadInput(e){return await this._getMajorBrand(e)==="qt "}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class $c extends ft{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,Tt);if(r instanceof Promise&&(r=await r),!r)return!1;const s=xc(r);if(s===null||s<1||s>8||ie(r,s)!==x.EBML)return!1;const a=Pc(r);if(typeof a!="number")return!1;let o=e._reader.requestSlice(r.filePos,a);if(o instanceof Promise&&(o=await o),!o)return!1;const c=r.filePos;for(;o.filePos<=c+a-Qe;){const u=bt(o);if(!u)break;const{id:l,size:d}=u,h=o.filePos;if(d===void 0)return!1;switch(l){case x.EBMLVersion:if(ie(o,d)!==1)return!1;break;case x.EBMLReadVersion:if(ie(o,d)!==1)return!1;break;case x.DocType:if(br(o,d)!==t)return!1;break;case x.DocTypeVersion:if(ie(o,d)>4)return!1;break}o.filePos=h+d}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Ju(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Dd extends $c{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class zd extends ft{async _canReadInput(e){let t=0;for(;;){let d=e._reader.requestSlice(t,It);if(d instanceof Promise&&(d=await d),!d)break;const h=nr(d);if(!h)break;t=d.filePos+h.size}const r=await bn(e._reader,t,t+4096);if(!r)return!1;const s=r.header,n=gs(s.mpegVersionId,s.channel);let a=e._reader.requestSlice(r.startPos+n,4);if(a instanceof Promise&&(a=await a),!a)return!1;const o=U(a);if(o===ps||o===qn)return!0;t=r.startPos+r.header.totalSize;const u=await bn(e._reader,t,t+ir);if(!u)return!1;const l=u.header;return!(s.channel!==l.channel||s.sampleRate!==l.sampleRate)}_createDemuxer(e){return new rd(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Ud extends ft{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;const r=ye(t,4);return r!=="RIFF"&&r!=="RIFX"&&r!=="RF64"?!1:(t.skip(4),ye(t,4)==="WAVE")}_createDemuxer(e){return new cd(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Nd extends ft{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?ye(t,4)==="OggS":!1}_createDemuxer(e){return new ad(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Vd extends ft{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),t?ye(t,4)==="fLaC":!1}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new pd(e)}}class Od extends ft{async _canReadInput(e){let t=0;for(;;){let a=e._reader.requestSlice(t,It);if(a instanceof Promise&&(a=await a),!a)break;const o=nr(a);if(!o)break;t=a.filePos+o.size}let r=e._reader.requestSliceRange(t,xi,Ot);if(r instanceof Promise&&(r=await r),!r)return!1;const s=_t(r);if(!s||(t+=s.frameLength,r=e._reader.requestSliceRange(t,xi,Ot),r instanceof Promise&&(r=await r),!r))return!1;const n=_t(r);return n?s.objectType===n.objectType&&s.samplingFrequencyIndex===n.samplingFrequencyIndex&&s.channelConfiguration===n.channelConfiguration:!1}_createDemuxer(e){return new ud(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Wd extends ft{async _canReadInput(e){const t=ze+16+1;let r=e._reader.requestSlice(0,t);if(r instanceof Promise&&(r=await r),!r)return!1;const s=K(r,t);return s[0]===71&&s[ze]===71||s[0]===71&&s[ze+16]===71?!0:s[4]===71&&s[4+ze+4]===71}_createDemuxer(e){return new wd(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Yc extends ft{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||!(ye(t,7)==="#EXTM3U"))return!1;if(!(e._rootSource instanceof Nr))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Fd(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Ir}}const Zc=new Rd,Jc=new Md,Ld=new $c,Hd=new Dd,el=new zd,qd=new Ud,jd=new Nd,tl=new Od,Kd=new Vd,rl=new Wd,il=new Yc,Rm=[il,Zc,Jc,Ld,Hd,qd,jd,Kd,el,tl,rl],Mm=[il,Zc,Jc,el,tl,rl],Gd=(i,e)=>{if(!i||typeof i!="object")throw new TypeError(`${e}, when provided, must be an object.`);if(i.isobmff!==void 0){if(!i.isobmff||typeof i.isobmff!="object")throw new TypeError(`${e}.isobmff, when provided, must be an object.`);if(i.isobmff.resolveKeyId!==void 0&&typeof i.isobmff.resolveKeyId!="function")throw new TypeError(`${e}.isobmff.resolveKeyId, when provided, must be a function.`)}};/*!
|
|
212
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
213
|
+
*
|
|
214
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
215
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
216
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
217
|
+
*/const Sn=new Map,An=new Map,Qd=(i,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&xt(e.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(e.codedWidth!==void 0&&(!Number.isInteger(e.codedWidth)||e.codedWidth<=0))throw new TypeError("options.codedWidth, when provided, must be a positive integer.");if(e.codedHeight!==void 0&&(!Number.isInteger(e.codedHeight)||e.codedHeight<=0))throw new TypeError("options.codedHeight, when provided, must be a positive integer.");if(e.displayAspectWidth!==void 0&&(!Number.isInteger(e.displayAspectWidth)||e.displayAspectWidth<=0))throw new TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(e.displayAspectHeight!==void 0&&(!Number.isInteger(e.displayAspectHeight)||e.displayAspectHeight<=0))throw new TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(e.description!==void 0&&!Fr(e.description))throw new TypeError("options.description, when provided, must be a buffer source.");if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.optimizeForLatency!==void 0&&typeof e.optimizeForLatency!="boolean")throw new TypeError("options.optimizeForLatency, when provided, must be a boolean.")},Xd=(i,e)=>{if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.codec!==void 0&&typeof e.codec!="string")throw new TypeError("options.codec, when provided, must be a string.");if(e.codec!==void 0&&xt(e.codec)!==i)throw new TypeError(`options.codec, when provided, must match the specified codec (${i}).`);if(e.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw new TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(e.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw new TypeError("options.sampleRate, when provided, must be a positive integer.");if(e.description!==void 0&&!Fr(e.description))throw new TypeError("options.description, when provided, must be a buffer source.")},Dm=i=>Se.includes(i)?sl(i):Ce.includes(i)?nl(i):!1,sl=async(i,e={})=>{if(!Se.includes(i))return!1;Qd(i,e);const t={...e,codedWidth:e.codedWidth??1280,codedHeight:e.codedHeight??720,codec:e.codec??Xo(i,1280,720,1e6)};t.description??(t.description=uu());const r=JSON.stringify(t),s=Sn.get(r);if(s)return s;const n=(async()=>Ci.some(o=>o.supports(i,t))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(t)).supported===!0)();return Sn.set(r,n),n},nl=async(i,e={})=>{if(!Ce.includes(i))return!1;Xd(i,e);const t={...e,numberOfChannels:e.numberOfChannels??2,sampleRate:e.sampleRate??48e3,codec:e.codec??Yo(i,2,48e3)};if(t.description===void 0){const a=du(t);if(a===!1)return!1;t.description=a}const r=JSON.stringify(t),s=An.get(r);if(s)return s;const n=(async()=>_i.some(o=>o.supports(i,t))||Pe.includes(i)?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(t)).supported===!0)();return An.set(r,n),n},zm=async()=>{const[i,e]=await Promise.all([$d(),Yd()]);return[...i,...e]},$d=async(i=Se,e)=>{const t=await Promise.all(i.map(r=>sl(r,e)));return i.filter((r,s)=>t[s])},Yd=async(i=Ce,e)=>{const t=await Promise.all(i.map(r=>nl(r,e)));return i.filter((r,s)=>t[s])};/*!
|
|
218
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
219
|
+
*
|
|
220
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
221
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
222
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
223
|
+
*/var Zd=function(i,e,t){if(e!=null){if(typeof e!="object"&&typeof e!="function")throw new TypeError("Object expected.");var r,s;if(t){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=e[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=e[Symbol.dispose],t&&(s=r)}if(typeof r!="function")throw new TypeError("Object not disposable.");s&&(r=function(){try{s.call(this)}catch(n){return Promise.reject(n)}}),i.stack.push({value:e,dispose:r,async:t})}else t&&i.stack.push({async:!0});return e},Jd=(function(i){return function(e){function t(a){e.error=e.hasError?new i(a,e.error,"An error was suppressed during disposal."):a,e.hasError=!0}var r,s=0;function n(){for(;r=e.stack.pop();)try{if(!r.async&&s===1)return s=0,e.stack.push(r),Promise.resolve().then(n);if(r.dispose){var a=r.dispose.call(r.value);if(r.async)return s|=2,Promise.resolve(a).then(n,function(o){return t(o),n()})}else s|=1}catch(o){t(o)}if(s===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return n()}})(typeof SuppressedError=="function"?SuppressedError:function(i,e,t){var r=new Error(t);return r.name="SuppressedError",r.error=i,r.suppressed=e,r});zn();let ao=-1/0,oo=-1/0,He=null;typeof FinalizationRegistry<"u"&&(He=new FinalizationRegistry(i=>{const e=performance.now();i.type==="video"?(e-ao>=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."),ao=e),typeof VideoFrame<"u"&&i.data instanceof VideoFrame&&i.data.close()):(e-oo>=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."),oo=e),typeof AudioData<"u"&&i.data instanceof AudioData&&i.data.close())}));class Kt{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const xn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],eh=new Set(xn);class Ae{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180===0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180===0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Ut*this.timestamp)}get microsecondDuration(){return Math.trunc(Ut*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var r,s,n,a,o,c,u,l;if(this._closed=!1,e instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.format===void 0||!eh.has(t.format))throw new TypeError("init.format must be one of: "+xn.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(t.layout!==void 0){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const h of t.layout){if(!h||typeof h!="object"||Array.isArray(h))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(h.offset)||h.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(h.stride)||h.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(t.visibleRect!==void 0&&Ta(t.visibleRect,"init.visibleRect"),t.displayWidth!==void 0&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(t.displayHeight!==void 0&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(t.displayWidth!==void 0!=(t.displayHeight!==void 0))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this._data=he(e).slice(),this._layout=t.layout??rh(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;let d=t.colorSpace??null;d===null&&(this.format==="RGBA"||this.format==="RGBX"||this.format==="BGRA"||this.format==="BGRX"?d={primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:d={primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.colorSpace=new Hs(d),this.visibleRect={left:((r=t.visibleRect)==null?void 0:r.left)??0,top:((s=t.visibleRect)==null?void 0:s.top)??0,width:((n=t.visibleRect)==null?void 0:n.width)??t.codedWidth,height:((a=t.visibleRect)==null?void 0:a.height)??t.codedHeight},t.displayWidth!==void 0?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height)}else if(typeof VideoFrame<"u"&&e instanceof VideoFrame){if((t==null?void 0:t.rotation)!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if((t==null?void 0:t.timestamp)!==void 0&&!Number.isFinite(t==null?void 0:t.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if((t==null?void 0:t.duration)!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");(t==null?void 0:t.visibleRect)!==void 0&&Ta(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:((o=e.visibleRect)==null?void 0:o.x)??0,top:((c=e.visibleRect)==null?void 0:c.y)??0,width:((u=e.visibleRect)==null?void 0:u.width)??e.codedWidth,height:((l=e.visibleRect)==null?void 0:l.height)??e.codedHeight},this.rotation=(t==null?void 0:t.rotation)??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=(t==null?void 0:t.timestamp)??e.timestamp/1e6,this.duration=(t==null?void 0:t.duration)??(e.duration??0)/1e6,this.colorSpace=new Hs(e.colorSpace)}else if(typeof HTMLImageElement<"u"&&e instanceof HTMLImageElement||typeof SVGImageElement<"u"&&e instanceof SVGImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||typeof HTMLVideoElement<"u"&&e instanceof HTMLVideoElement||typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(typeof VideoFrame<"u")return new Ae(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Ut),duration:Math.trunc((t.duration??0)*Ut)||void 0}),t);let d=0,h=0;if("naturalWidth"in e?(d=e.naturalWidth,h=e.naturalHeight):"videoWidth"in e?(d=e.videoWidth,h=e.videoHeight):"width"in e&&(d=Number(e.width),h=Number(e.height)),!d||!h)throw new TypeError("Could not determine dimensions.");const p=new OffscreenCanvas(d,h),y=p.getContext("2d",{alpha:Zi(),willReadFrequently:!0});m(y),y.drawImage(e,0,0),this._data=p,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:d,height:h},this.squarePixelWidth=d,this.squarePixelHeight=h,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Hs({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof Kt){if(!t||typeof t!="object")throw new TypeError("init must be an object.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(t.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),this.format!==null&&!xn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}else throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.pixelAspectRatio=Ti({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),He==null||He.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return m(this._data!==null),this._data instanceof Kt?new Ae(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):ri(this._data)?new Ae(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(m(this._layout),new Ae(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new Ae(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(He==null||He.unregister(this),this._data instanceof Kt?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):ri(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(lo(e),this._closed)throw new Error("VideoSample is closed.");if((e.format??this.format)==null)throw new Error("Cannot get allocation size when format is null.");return ri(this._data)?this._data.allocationSize(e):uo(this,e).allocationSize}async copyTo(e,t={}){if(!Fr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(lo(t),this._closed)throw new Error("VideoSample is closed.");if((t.format??this.format)==null)throw new Error("Cannot copy video sample data when format is null.");if(m(this._data!==null),ri(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format))if(this._data instanceof Kt){const u={stack:[],error:void 0,hasError:!1};try{const l=Zd(u,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(l instanceof Ae))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(l.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${l.format}' instead.`);return await l.copyTo(e,t)}catch(l){u.error=l,u.hasError=!0}finally{Jd(u)}}else{if(typeof VideoFrame>"u")throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const u=this.toVideoFrame(),l=await u.copyTo(e,t);return u.close(),l}const r=uo(this,t);m(this.format);const s=he(e);if(s.byteLength<r.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${s.byteLength}`);const n=As(this.format);let a;if(this._data instanceof Kt){let u=this._data.getDataPlanes();if(u instanceof Promise&&(u=await u),!Array.isArray(u)||u.some(l=>!(l.data instanceof Uint8Array)||!Number.isInteger(l.stride)||l.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');a=u}else if(this._data instanceof Uint8Array)m(this._layout),m(this._layout.length===n.length),a=this._layout.map((u,l)=>{const d=Math.ceil(this.codedHeight/n[l].heightDivisor);return{data:this._data.subarray(u.offset,u.offset+u.stride*d),stride:u.stride}});else{const l=this._data.getContext("2d");m(l);const d=l.getImageData(0,0,this.codedWidth,this.codedHeight);a=[{data:he(d.data),stride:4*this.codedWidth}]}const o=[],c=n.length;for(let u=0;u<c;u++){const l=r.computedLayouts[u],d=a[u].stride,h=a[u].data;let p=l.sourceTop*d;p+=l.sourceLeftBytes;let y=l.destinationOffset;const f=l.sourceWidthBytes,w={offset:y,stride:l.destinationStride};for(let g=0;g<l.sourceHeight;g++){if(p+f>h.byteLength)throw new Error("Source buffer OOB read.");if(y+f>s.byteLength)throw new Error("Destination buffer OOB write.");const b=h.subarray(p,p+f);s.set(b,y),p+=d,y+=l.destinationStride}o.push(w)}if(t.format!==void 0){const u=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),l=this.format.includes("X")&&t.format.includes("A");if(u||l)for(let d=0;d<r.allocationSize;d+=4){if(u){const h=s[d],p=s[d+2];s[d]=p,s[d+2]=h}l&&(s[d+3]=255)}}return o}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),this._data instanceof Kt){if(this.format===null)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(e instanceof Promise)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((a,o)=>a+o.data.byteLength,0),r=new Uint8Array(t);let s=0;const n=[];for(const a of e)r.set(a.data,s),n.push(s),s+=a.data.byteLength;return new VideoFrame(r,{format:this.format,layout:e.map((a,o)=>({offset:n[o],stride:a.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}else return ri(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,r,s,n,a,o,c,u){let l=0,d=0,h=this.displayWidth,p=this.displayHeight,y=0,f=0,w=this.displayWidth,g=this.displayHeight;if(a!==void 0?(l=t,d=r,h=s,p=n,y=a,f=o,c!==void 0?(w=c,g=u):(w=h,g=p)):(y=t,f=r,s!==void 0&&(w=s,g=n)),!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(d))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(p)||p<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(y))throw new TypeError("dx must be a number.");if(!Number.isFinite(f))throw new TypeError("dy must be a number.");if(!Number.isFinite(w)||w<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:d,sWidth:h,sHeight:p}=this._rotateSourceRegion(l,d,h,p,this.rotation));const b=this.toCanvasImageSource();e.save();const k=y+w/2,S=f+g/2;e.translate(k,S),e.rotate(this.rotation*Math.PI/180);const A=this.rotation%180===0?1:w/g;e.scale(1/A,A),e.drawImage(b,l,d,h,p,-w/2,-g/2,w,g),e.restore()}drawWithFit(e,t){var b,k,S,A;if(!(typeof CanvasRenderingContext2D<"u"&&e instanceof CanvasRenderingContext2D||typeof OffscreenCanvasRenderingContext2D<"u"&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");t.crop!==void 0&&Pi(t.crop,"options.");const r=e.canvas.width,s=e.canvas.height,n=t.rotation??this.rotation,[a,o]=n%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=t.crop;c&&(c=as(c,a,o));let u,l,d,h;const{sx:p,sy:y,sWidth:f,sHeight:w}=this._rotateSourceRegion(((b=t.crop)==null?void 0:b.left)??0,((k=t.crop)==null?void 0:k.top)??0,((S=t.crop)==null?void 0:S.width)??a,((A=t.crop)==null?void 0:A.height)??o,n);if(t.fit==="fill")u=0,l=0,d=r,h=s;else{const[_,I]=t.crop?[t.crop.width,t.crop.height]:[a,o],C=t.fit==="contain"?Math.min(r/_,s/I):Math.max(r/_,s/I);d=_*C,h=I*C,u=(r-d)/2,l=(s-h)/2}e.save();const g=n%180===0?1:d/h;e.translate(r/2,s/2),e.rotate(n*Math.PI/180),e.scale(1/g,g),e.translate(-r/2,-s/2),e.drawImage(this.toCanvasImageSource(),p,y,f,w,u,l,d,h),e.restore()}_rotateSourceRegion(e,t,r,s,n){return n===90?[e,t,r,s]=[t,this.squarePixelHeight-e-r,s,r]:n===180?[e,t]=[this.squarePixelWidth-e-r,this.squarePixelHeight-t-s]:n===270&&([e,t,r,s]=[this.squarePixelWidth-t-s,e,s,r]),{sx:e,sy:t,sWidth:r,sHeight:s}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(m(this._data!==null),this._data instanceof Kt||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}else return this._data}async transform(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(e.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(e.roundDimensionsTo!==void 0&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(e.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(e.width!==void 0&&e.height!==void 0&&e.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(e.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(e.crop!==void 0&&Pi(e.crop,"options."),e.alpha!==void 0&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=Er(this.rotation+(e.rotate??0)),[r,s]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let n=e.crop;n&&(n=as(n,r,s));const a=n?n.width:r,o=n?n.height:s,c=a/o;let u,l;e.width!==void 0&&e.height===void 0?(u=e.width,l=u/c):e.width===void 0&&e.height!==void 0?(l=e.height,u=l*c):e.width!==void 0&&e.height!==void 0?(u=e.width,l=e.height):(u=a,l=o),u=nn(u,e.roundDimensionsTo??1),l=nn(l,e.roundDimensionsTo??1);const d={width:u,height:l,fit:e.fit??"fill",rotation:t,crop:n??{left:0,top:0,width:r,height:s},alpha:e.alpha??"keep"};for(const f of Pn){let w=f(this,d);if(w instanceof Promise&&(w=await w),w!==null)return w}let h=null,p=!1;for(const f of ti)if(f.canvas.width===d.width&&f.canvas.height===d.height){h=f.canvas,f.age=co++;break}if(h===null){if(typeof OffscreenCanvas<"u")h=new OffscreenCanvas(d.width,d.height);else{if(typeof window>"u"||typeof document>"u")throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");h=document.createElement("canvas"),h.width=d.width,h.height=d.height}p=!0,ti.length>=th&&ti.splice(Un(ti,f=>f.age),1),ti.push({canvas:h,age:co++})}const y=h.getContext("2d",{alpha:!0});return m(y),d.alpha==="discard"?(y.fillStyle="black",y.fillRect(0,0,d.width,d.height)):p||y.clearRect(0,0,d.width,d.height),this.drawWithFit(y,{fit:d.fit,rotation:d.rotation,crop:d.crop}),new Ae(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}const Pn=[],Um=i=>{Pn.includes(i)||Pn.push(i)},th=3,ti=[];let co=0;class Hs{constructor(e){if(e!==void 0){if(!e||typeof e!="object")throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(ar);if(e.primaries!=null&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const r=Object.keys(or);if(e.transfer!=null&&!r.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);const s=Object.keys(cr);if(e.matrix!=null&&!s.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${s.join(", ")}.`);if(e.fullRange!=null&&typeof e.fullRange!="boolean")throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=(e==null?void 0:e.primaries)??null,this.transfer=(e==null?void 0:e.transfer)??null,this.matrix=(e==null?void 0:e.matrix)??null,this.fullRange=(e==null?void 0:e.fullRange)??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const ri=i=>typeof VideoFrame<"u"&&i instanceof VideoFrame,as=(i,e,t)=>{const r=Math.min(i.left,e),s=Math.min(i.top,t),n=Math.min(i.width,e-r),a=Math.min(i.height,t-s);return m(n>=0),m(a>=0),{left:r,top:s,width:n,height:a}},Pi=(i,e)=>{if(!i||typeof i!="object")throw new TypeError(e+"crop, when provided, must be an object.");if(!Number.isInteger(i.left)||i.left<0)throw new TypeError(e+"crop.left must be a non-negative integer.");if(!Number.isInteger(i.top)||i.top<0)throw new TypeError(e+"crop.top must be a non-negative integer.");if(!Number.isInteger(i.width)||i.width<0)throw new TypeError(e+"crop.width must be a non-negative integer.");if(!Number.isInteger(i.height)||i.height<0)throw new TypeError(e+"crop.height must be a non-negative integer.")},lo=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.colorSpace!==void 0&&!["display-p3","srgb"].includes(i.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(i.format!==void 0&&typeof i.format!="string")throw new TypeError("options.format, when provided, must be a string.");if(i.layout!==void 0){if(!Array.isArray(i.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const e of i.layout){if(!e||typeof e!="object")throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(i.rect!==void 0){if(!i.rect||typeof i.rect!="object")throw new TypeError("options.rect, when provided, must be an object.");if(i.rect.x!==void 0&&(!Number.isInteger(i.rect.x)||i.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(i.rect.y!==void 0&&(!Number.isInteger(i.rect.y)||i.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(i.rect.width!==void 0&&(!Number.isInteger(i.rect.width)||i.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(i.rect.height!==void 0&&(!Number.isInteger(i.rect.height)||i.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},rh=(i,e,t)=>{const r=As(i),s=[];let n=0;for(const a of r){const o=Math.ceil(e/a.widthDivisor),c=Math.ceil(t/a.heightDivisor),u=o*a.sampleBytes,l=u*c;s.push({offset:n,stride:u}),n+=l}return s},As=i=>{const e=(t,r,s,n,a)=>{const o=[{sampleBytes:t,widthDivisor:1,heightDivisor:1},{sampleBytes:r,widthDivisor:s,heightDivisor:n},{sampleBytes:r,widthDivisor:s,heightDivisor:n}];return a&&o.push({sampleBytes:t,widthDivisor:1,heightDivisor:1}),o};switch(i){case"I420":return e(1,1,2,2,!1);case"I420P10":case"I420P12":return e(2,2,2,2,!1);case"I420A":return e(1,1,2,2,!0);case"I420AP10":case"I420AP12":return e(2,2,2,2,!0);case"I422":return e(1,1,2,1,!1);case"I422P10":case"I422P12":return e(2,2,2,1,!1);case"I422A":return e(1,1,2,1,!0);case"I422AP10":case"I422AP12":return e(2,2,2,1,!0);case"I444":return e(1,1,1,1,!1);case"I444P10":case"I444P12":return e(2,2,1,1,!1);case"I444A":return e(1,1,1,1,!0);case"I444AP10":case"I444AP12":return e(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:De(i),m(!1)}},uo=(i,e)=>{const t={left:0,top:0,width:i.codedWidth,height:i.codedHeight},r=e.rect,s=ih(t,r,i.codedWidth,i.codedHeight,i.format),n=e.layout;let a;if(!e.format||e.format===i.format)a=i.format;else if(["RGBA","RGBX","BGRA","BGRX"].includes(e.format))a=e.format;else throw new Error("NotSupportedError: Invalid destination format.");return nh(s,a,n)},ih=(i,e,t,r,s)=>{const n={...i};if(e!==void 0){if(e.width===0||e.height===0)throw new TypeError("visibleRect dimensions cannot be zero.");if((e.x||0)+(e.width||0)>t)throw new TypeError("visibleRect exceeds codedWidth.");if((e.y||0)+(e.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");n.x=e.x||0,n.y=e.y||0,n.width=e.width||0,n.height=e.height||0}if(!sh(s,n))throw new TypeError("visibleRect alignment is invalid for the format.");return n},sh=(i,e)=>{if(i===null)return!0;const t=As(i);for(let r=0;r<t.length;r++){const s=t[r],n=s.widthDivisor,a=s.heightDivisor;if((e.x||0)%n!==0||(e.y||0)%a!==0)return!1}return!0},nh=(i,e,t)=>{const r=As(e),s=r.length;if(t!==void 0&&t.length!==s)throw new TypeError(`Layout must have ${s} planes.`);let n=0;const a=[],o=[];for(let c=0;c<s;c++){const u=r[c],l=u.sampleBytes,d=u.widthDivisor,h=u.heightDivisor,p={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(p.sourceTop=Math.ceil(Math.trunc(i.y||0)/h),p.sourceHeight=Math.ceil(Math.trunc(i.height||0)/h),p.sourceLeftBytes=Math.floor(Math.trunc(i.x||0)/d)*l,p.sourceWidthBytes=Math.floor(Math.trunc(i.width||0)/d)*l,t!==void 0){const w=t[c];if(w.stride<p.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);p.destinationOffset=w.offset,p.destinationStride=w.stride}else p.destinationOffset=n,p.destinationStride=p.sourceWidthBytes;const f=p.destinationStride*p.sourceHeight+p.destinationOffset;if(f>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(f),n=Math.max(n,f);for(let w=0;w<c;w++){const g=a[w];if(!(o[c]<=g.destinationOffset||o[w]<=p.destinationOffset))throw new TypeError("Planes overlap.")}a.push(p)}return{allocationSize:n,computedLayouts:a}},Vi=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class ii{constructor(){this._referenceCount=0}}class Ee{get microsecondTimestamp(){return Math.trunc(Ut*this.timestamp)}get microsecondDuration(){return Math.trunc(Ut*this.duration)}constructor(e){if(this._closed=!1,si(e)){if(e.format===null)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof ii){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!Vi.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||typeof e!="object")throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Vi.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels===0)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e==null?void 0:e.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(Yt(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate;let r;if(e.data instanceof ArrayBuffer)r=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))r=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");const s=this.numberOfFrames*this.numberOfChannels*Yt(this.format);if(r.byteLength<s)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=r}He==null||He.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(e.format!==void 0&&!Vi.has(e.format))throw new TypeError("Invalid format.");if(e.frameOffset!==void 0&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(e.frameCount!==void 0&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=e.frameCount!==void 0?e.frameCount:this.numberOfFrames-r;if(s>this.numberOfFrames-r)throw new RangeError("frameCount out of range");const n=Yt(t),a=Tr(t);if(a&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!a&&e.planeIndex!==0)throw new RangeError("planeIndex out of range");return(a?s:s*this.numberOfChannels)*n}copyTo(e,t){if(!Fr(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(t.format!==void 0&&!Vi.has(t.format))throw new TypeError("Invalid format.");if(t.frameOffset!==void 0&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(t.frameCount!==void 0&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:r,frameCount:s,frameOffset:n}=t;let{planeIndex:a}=t;const o=this.format,c=r??this.format;if(!c)throw new Error("Destination format not determined");const u=this.numberOfFrames,l=this.numberOfChannels,d=n??0;if(d>=u)throw new RangeError("frameOffset out of range");const h=s!==void 0?s:u-d;if(h>u-d)throw new RangeError("frameCount out of range");const p=Yt(c),y=Tr(c);if(y&&a>=l)throw new RangeError("planeIndex out of range");if(!y&&a!==0)throw new RangeError("planeIndex out of range");const w=(y?h:h*l)*p;if(e.byteLength<w)throw new RangeError("Destination buffer is too small");const g=Z(e),b=ol(c);if(si(this._data))fi()&&l>2&&c!==o?ah(this._data,g,o,c,l,a,d,h):this._data.copyTo(e,{planeIndex:a,frameOffset:d,frameCount:h,format:c});else{const k=al(o),S=Yt(o),A=Tr(o);let _;if(this._data instanceof ii){const C=P=>{const v=this._data.getDataPlane(P);if(!(v instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const M=u*S*(A?1:l);if(v.byteLength!==M)throw new TypeError(`Data plane ${P} has invalid size. Expected exactly ${M} bytes, got ${v.byteLength} bytes.`);return v};if(A)if(y)_=C(a),a=0;else{_=new Uint8Array(u*S*l);for(let P=0;P<l;P++){const v=C(P);_.set(v,P*u*S)}}else _=C(0)}else _=this._data;const I=Z(_);for(let C=0;C<h;C++)if(y){const P=C*p;let v;A?v=(a*u+(C+d))*S:v=((C+d)*l+a)*S;const M=k(I,v);b(g,P,M)}else for(let P=0;P<l;P++){const M=(C*l+P)*p;let R;A?R=(P*u+(C+d))*S:R=((C+d)*l+P)*S;const L=k(I,R);b(g,M,L)}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof ii){const e=new Ee(this._data);return e.setTimestamp(this.timestamp),e}else if(si(this._data)){const e=new Ee(this._data.clone());return e.setTimestamp(this.timestamp),e}else return new Ee({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(He==null||He.unregister(this),this._data instanceof ii?(this._data._referenceCount--,this._data._referenceCount===0&&this._data.close()):si(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof ii?this._createAudioDataFromData():si(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(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})}else{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let 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=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(r/s);let c=0,u=a;for(;u>0;){const l=Math.min(o,u),d=new Float32Array(s*l);for(let h=0;h<s;h++)e.copyFromChannel(d.subarray(h*l,(h+1)*l),h,c);yield new Ee({format:"f32-planar",sampleRate:n,numberOfFrames:l,numberOfChannels:s,timestamp:t+c/n,data:d}),c+=l,u-=l}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const r=48e3*5,s=e.numberOfChannels,n=e.sampleRate,a=e.length,o=Math.floor(r/s);let c=0,u=a;const l=[];for(;u>0;){const d=Math.min(o,u),h=new Float32Array(s*d);for(let y=0;y<s;y++)e.copyFromChannel(h.subarray(y*d,(y+1)*d),y,c);const p=new Ee({format:"f32-planar",sampleRate:n,numberOfFrames:d,numberOfChannels:s,timestamp:t+c/n,data:h});l.push(p),c+=d,u-=d}return l}}const Yt=i=>{switch(i){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":return 4;case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Tr=i=>{switch(i){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},al=i=>{switch(i){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)}},ol=i=>{switch(i){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,Ie((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,Ie(Math.round(r*32767),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,Ie(Math.round(r*2147483647),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},si=i=>typeof AudioData<"u"&&i instanceof AudioData,cl=i=>{switch(i){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return i}},ah=(i,e,t,r,s,n,a,o)=>{const c=al(t),u=ol(r),l=Yt(t),d=Yt(r),h=Tr(t);if(Tr(r))if(h){const y=new ArrayBuffer(o*l),f=Z(y);i.copyTo(y,{planeIndex:n,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const g=w*l,b=w*d,k=c(f,g);u(e,b,k)}}else{const y=new ArrayBuffer(o*s*l),f=Z(y);i.copyTo(y,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++){const g=(w*s+n)*l,b=w*d,k=c(f,g);u(e,b,k)}}else if(h){const y=o*l,f=new ArrayBuffer(y),w=Z(f);for(let g=0;g<s;g++){i.copyTo(f,{planeIndex:g,frameOffset:a,frameCount:o,format:t});for(let b=0;b<o;b++){const k=b*l,S=(b*s+g)*d,A=c(w,k);u(e,S,A)}}}else{const y=new ArrayBuffer(o*s*l),f=Z(y);i.copyTo(y,{planeIndex:0,frameOffset:a,frameCount:o,format:t});for(let w=0;w<o;w++)for(let g=0;g<s;g++){const b=w*s+g,k=b*l,S=b*d,A=c(f,k);u(e,S,A)}}},ll=(i,e)=>{const t=i.allocationSize({format:e,planeIndex:0}),r=new ArrayBuffer(t);return i.copyTo(r,{format:e,planeIndex:0}),new Ee({data:r,format:e,numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,timestamp:i.timestamp,duration:i.duration})};/*!
|
|
224
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
225
|
+
*
|
|
226
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
227
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
228
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
229
|
+
*/const Cn=new Map,_n=new Map,ia=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!Se.includes(i.codec))throw new TypeError(`Invalid video codec '${i.codec}'. Must be one of: ${Se.join(", ")}.`);if(!(i.bitrate instanceof Ke)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate must be a positive integer or a quality.");if(i.keyFrameInterval!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(i.sizeChangeBehavior!==void 0&&!["deny","passThrough","fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.width!==void 0&&(!Number.isInteger(i.transform.width)||i.transform.width<=0))throw new TypeError("config.transform.width, when provided, must be a positive integer.");if(i.transform.height!==void 0&&(!Number.isInteger(i.transform.height)||i.transform.height<=0))throw new TypeError("config.transform.height, when provided, must be a positive integer.");if(i.transform.fit!==void 0&&!["fill","contain","cover"].includes(i.transform.fit))throw new TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(i.transform.width!==void 0&&i.transform.height!==void 0&&i.transform.fit===void 0&&!["fill","contain","cover"].includes(i.sizeChangeBehavior))throw new TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(i.transform.fit!==void 0&&["fill","contain","cover"].includes(i.sizeChangeBehavior)&&i.transform.fit!==i.sizeChangeBehavior)throw new TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(i.transform.rotate!==void 0&&![0,90,180,270].includes(i.transform.rotate))throw new TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(i.transform.crop!==void 0&&Pi(i.transform.crop,"config.transform."),i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.");if(i.transform.frameRate!==void 0&&(!Number.isFinite(i.transform.frameRate)||i.transform.frameRate<=0))throw new TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(i.transform.force!==void 0&&typeof i.transform.force!="boolean")throw new TypeError("config.transform.force, when provided, must be a boolean.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");ul(i.codec,i)},ul=(i,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.latencyMode!==void 0&&!["quality","realtime"].includes(e.latencyMode))throw new TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&xt(e.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`);if(e.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e.scalabilityMode!==void 0&&typeof e.scalabilityMode!="string")throw new TypeError("scalabilityMode, when provided, must be a string.");if(e.contentHint!==void 0&&typeof e.contentHint!="string")throw new TypeError("contentHint, when provided, must be a string.")},dl=i=>{const e=i.bitrate instanceof Ke?i.bitrate._toVideoBitrate(i.codec,i.width,i.height):i.bitrate;return{codec:i.fullCodecString??Xo(i.codec,i.width,i.height,e),width:i.width,height:i.height,displayWidth:i.squarePixelWidth,displayHeight:i.squarePixelHeight,bitrate:e,bitrateMode:i.bitrateMode,alpha:i.alpha??"discard",framerate:i.framerate,latencyMode:i.latencyMode,hardwareAcceleration:i.hardwareAcceleration,scalabilityMode:i.scalabilityMode,contentHint:i.contentHint,...hu(i.codec)}},sa=i=>{if(!i||typeof i!="object")throw new TypeError("Encoding config must be an object.");if(!Ce.includes(i.codec))throw new TypeError(`Invalid audio codec '${i.codec}'. Must be one of: ${Ce.join(", ")}.`);if(i.bitrate===void 0&&!(Pe.includes(i.codec)||i.codec==="flac"))throw new TypeError("config.bitrate must be provided for compressed audio codecs.");if(i.bitrate!==void 0&&!(i.bitrate instanceof Ke)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(i.transform!==void 0){if(typeof i.transform!="object"||!i.transform)throw new TypeError("config.transform, when provided, must be an object.");if(i.transform.numberOfChannels!==void 0&&(!Number.isInteger(i.transform.numberOfChannels)||i.transform.numberOfChannels<=0))throw new TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(i.transform.sampleRate!==void 0&&(!Number.isInteger(i.transform.sampleRate)||i.transform.sampleRate<=0))throw new TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(i.transform.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(i.transform.sampleFormat))throw new TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(i.transform.process!==void 0&&typeof i.transform.process!="function")throw new TypeError("config.transform.process, when provided, must be a function.")}if(i.onEncodedPacket!==void 0&&typeof i.onEncodedPacket!="function")throw new TypeError("config.onEncodedPacket, when provided, must be a function.");if(i.onEncoderConfig!==void 0&&typeof i.onEncoderConfig!="function")throw new TypeError("config.onEncoderConfig, when provided, must be a function.");hl(i.codec,i)},hl=(i,e)=>{if(!e||typeof e!="object")throw new TypeError("Encoding options must be an object.");if(e.bitrateMode!==void 0&&!["constant","variable"].includes(e.bitrateMode))throw new TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(e.fullCodecString!==void 0&&typeof e.fullCodecString!="string")throw new TypeError("fullCodecString, when provided, must be a string.");if(e.fullCodecString!==void 0&&xt(e.fullCodecString)!==i)throw new TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${i}).`)},fl=i=>{const e=i.bitrate instanceof Ke?i.bitrate._toAudioBitrate(i.codec):i.bitrate;return{codec:i.fullCodecString??Yo(i.codec,i.numberOfChannels,i.sampleRate),numberOfChannels:i.numberOfChannels,sampleRate:i.sampleRate,bitrate:e,bitrateMode:i.bitrateMode,...fu(i.codec)}};class Ke{constructor(e){this._factor=e}_toVideoBitrate(e,t,r){const s=t*r,n={avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2},a=1920*1080,o=3e6,c=Math.pow(s/a,.95),d=o*c*n[e]*this._factor;return Math.ceil(d/1e3)*1e3}_toAudioBitrate(e){if(Pe.includes(e)||e==="flac")return;const r={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!r)throw new Error(`Unhandled codec: ${e}`);let s=r*this._factor;return e==="aac"?s=[96e3,128e3,16e4,192e3].reduce((a,o)=>Math.abs(o-s)<Math.abs(a-s)?o:a):e==="opus"||e==="vorbis"?s=Math.max(6e3,s):e==="mp3"&&(s=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((a,o)=>Math.abs(o-s)<Math.abs(a-s)?o:a)),Math.round(s/1e3)*1e3}}const Nm=new Ke(.3),Vm=new Ke(.6),Om=new Ke(1),ho=new Ke(2),Wm=new Ke(4),Lm=i=>{if(Se.includes(i))return na(i);if(Ce.includes(i))return aa(i);if(dt.includes(i))return oa(i);throw new TypeError(`Unknown codec '${i}'.`)},na=async(i,e={})=>{const{width:t=1280,height:r=720,bitrate:s=1e6,...n}=e;if(!Se.includes(i))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("width must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("height must be a positive integer.");if(!(s instanceof Ke)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer or a quality.");ul(i,n);const a=dl({codec:i,width:t,height:r,bitrate:s,framerate:void 0,...n,alpha:"discard"}),o=JSON.stringify(a),c=Cn.get(o);if(c)return c;const u=(async()=>os.some(h=>h.supports(i,a))?!0:typeof VideoEncoder>"u"||(t%2===1||r%2===1)&&(i==="avc"||i==="hevc")||!(await VideoEncoder.isConfigSupported(a)).supported?!1:Zi()?new Promise(async h=>{try{const p=new VideoEncoder({output:()=>{},error:()=>h(!1)});p.configure(a);const y=new Uint8Array(t*r*4),f=new VideoFrame(y,{format:"RGBA",codedWidth:t,codedHeight:r,timestamp:0});p.encode(f),f.close(),await p.flush(),h(!0)}catch{h(!1)}}):!0)();return Cn.set(o,u),u},aa=async(i,e={})=>{const{numberOfChannels:t=2,sampleRate:r=48e3,bitrate:s=128e3,...n}=e;if(!Ce.includes(i))return!1;if(!Number.isInteger(t)||t<=0)throw new TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw new TypeError("sampleRate must be a positive integer.");if(!(s instanceof Ke)&&(!Number.isInteger(s)||s<=0))throw new TypeError("bitrate must be a positive integer.");hl(i,n);const a=fl({codec:i,numberOfChannels:t,sampleRate:r,bitrate:s,...n}),o=JSON.stringify(a),c=_n.get(o);if(c)return c;const u=(async()=>cs.some(d=>d.supports(i,a))||Pe.includes(i)?!0:typeof AudioEncoder>"u"?!1:(await AudioEncoder.isConfigSupported(a)).supported===!0)();return _n.set(o,u),u},oa=async i=>!!dt.includes(i),Hm=async()=>{const[i,e,t]=await Promise.all([oh(),In(),ch()]);return[...i,...e,...t]},oh=async(i=Se,e)=>{const t=await Promise.all(i.map(r=>na(r,e)));return i.filter((r,s)=>t[s])},In=async(i=Ce,e)=>{const t=await Promise.all(i.map(r=>aa(r,e)));return i.filter((r,s)=>t[s])},ch=async(i=dt)=>{const e=await Promise.all(i.map(oa));return i.filter((t,r)=>e[r])},lh=async(i,e)=>{for(const t of i)if(await na(t,e))return t;return null},qm=async(i,e)=>{for(const t of i)if(await aa(t,e))return t;return null},jm=async i=>{for(const e of i)if(await oa(e))return e;return null};/*!
|
|
230
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
231
|
+
*
|
|
232
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
233
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
234
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
235
|
+
*/class uh{static supports(e,t){return!1}}class dh{static supports(e,t){return!1}}class hh{static supports(e,t){return!1}}class fh{static supports(e,t){return!1}}const Ci=[],_i=[],os=[],cs=[],Km=i=>{if(i.prototype instanceof uh){const e=i;if(Ci.includes(e)){console.warn("Video decoder already registered.");return}Ci.push(e),Sn.clear()}else if(i.prototype instanceof dh){const e=i;if(_i.includes(e)){console.warn("Audio decoder already registered.");return}_i.push(e),An.clear()}else throw new TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},Gm=i=>{if(i.prototype instanceof hh){const e=i;if(os.includes(e)){console.warn("Video encoder already registered.");return}os.push(e),Cn.clear()}else if(i.prototype instanceof fh){const e=i;if(cs.includes(e)){console.warn("Audio encoder already registered.");return}cs.push(e),_n.clear()}else throw new TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")};/*!
|
|
236
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
237
|
+
*
|
|
238
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
239
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
240
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
241
|
+
*/const mh=i=>{let r=i,s=4096,n=0,a=12,o=0;for(r<0&&(r=-r,n=128),r+=33,r>8191&&(r=8191);(r&s)!==s&&a>=5;)s>>=1,a--;return o=r>>a-4&15,~(n|a-5<<4|o)&255},ph=i=>{let t=0,r=0,s=~i;s&128&&(s&=-129,t=-1),r=((s&240)>>4)+5;const n=(1<<r|(s&15)<<r-4|1<<r-5)-33;return t===0?n:-n},gh=i=>{let t=2048,r=0,s=11,n=0,a=i;for(a<0&&(a=-a,r=128),a>4095&&(a=4095);(a&t)!==t&&s>=5;)t>>=1,s--;return n=a>>(s===4?1:s-4)&15,(r|s-4<<4|n)^85},wh=i=>{let e=0,t=0,r=i^85;r&128&&(r&=-129,e=-1),t=((r&240)>>4)+4;let s=0;return t!==4?s=1<<t|(r&15)<<t-4|1<<t-5:s=r<<1|1,e===0?s:-s};/*!
|
|
242
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
243
|
+
*
|
|
244
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
245
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
246
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
247
|
+
*/const Gt=i=>{if(!i||typeof i!="object")throw new TypeError("options must be an object.");if(i.metadataOnly!==void 0&&typeof i.metadataOnly!="boolean")throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(i.verifyKeyPackets!==void 0&&typeof i.verifyKeyPackets!="boolean")throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(i.verifyKeyPackets&&i.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(i.skipLiveWait!==void 0&&typeof i.skipLiveWait!="boolean")throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},Ct=i=>{if(!Mr(i))throw new TypeError("timestamp must be a number.")},qs=(i,e,t)=>t.verifyKeyPackets?e.then(async r=>{if(!r||r.type==="delta")return r;const s=await i.determinePacketType(r);return s&&(r.type=s),r}):e;class Ii{constructor(e){if(!(e instanceof Fi))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(Gt(e),this._track.input._disposed)throw new We;return qs(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){Gt(e);const t=await this.getFirstPacket(e);return t?t.type==="key"?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(Ct(e),Gt(t),this._track.input._disposed)throw new We;return qs(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof de))throw new TypeError("packet must be an EncodedPacket.");if(Gt(t),this._track.input._disposed)throw new We;return qs(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(Ct(e),Gt(t),this._track.input._disposed)throw new We;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const r=await this._track._backing.getKeyPacket(e,t);return r&&(m(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r)}async getNextKeyPacket(e,t={}){if(!(e instanceof de))throw new TypeError("packet must be an EncodedPacket.");if(Gt(t),this._track.input._disposed)throw new We;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const r=await this._track._backing.getNextKeyPacket(e,t);return r&&(m(r.type==="key"),await this._track.determinePacketType(r)==="delta"?this.getNextKeyPacket(r,t):r)}packets(e,t,r={}){if(e!==void 0&&!(e instanceof de))throw new TypeError("startPacket must be an EncodedPacket.");if(e!==void 0&&e.isMetadataOnly&&!(r!=null&&r.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(t!==void 0&&!(t instanceof de))throw new TypeError("endPacket must be an EncodedPacket.");if(Gt(r),this._track.input._disposed)throw new We;const s=[];let{promise:n,resolve:a}=ge(),{promise:o,resolve:c}=ge(),u=!1,l=!1,d=null;const h=[],p=()=>Math.max(2,h.length);(async()=>{let f=e??await this.getFirstPacket(r);for(;f&&!l&&!this._track.input._disposed&&!(t&&f.sequenceNumber>=(t==null?void 0:t.sequenceNumber));){if(s.length>p()){({promise:o,resolve:c}=ge()),await o;continue}s.push(f),a(),{promise:n,resolve:a}=ge(),f=await this.getNextPacket(f,r)}u=!0,a()})().catch(f=>{d||(d=f,a())});const y=this._track;return{async next(){for(;;){if(y.input._disposed)throw new We;if(l)return{value:void 0,done:!0};if(d)throw d;if(s.length>0){const f=s.shift(),w=performance.now();for(h.push(w);h.length>0&&w-h[0]>=1e3;)h.shift();return c(),{value:f,done:!1}}else{if(u)return{value:void 0,done:!0};await n}}},async return(){return l=!0,c(),a(),{value:void 0,done:!0}},async throw(f){throw f},[Symbol.asyncIterator](){return this}}}}class ca{constructor(e,t){this.onSample=e,this.onError=t}}class ml{mediaSamplesInRange(e=-1/0,t=1/0,r){Ct(e),Ct(t);const s=[];let n=!1,a=null,{promise:o,resolve:c}=ge(),{promise:u,resolve:l}=ge(),d=!1,h=!1,p=!1,y=null;const f={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const b=await this._createDecoder(C=>{if(l(),C.timestamp>=t&&(h=!0),h){C.close();return}a&&(C.timestamp>e?(s.push(a),n=!0):a.close()),C.timestamp>=e&&(s.push(C),n=!0),a=n?null:C,s.length>0&&(c(),{promise:o,resolve:c}=ge())},C=>{y||(y=C,c())}),k=this._createPacketSink(),S=await k.getKeyPacket(e,f)??await k.getFirstKeyPacket(f);let A=S;const I=k.packets(S??void 0,void 0,f);for(await I.next();A&&!h&&!this._track.input._disposed;){const C=fo(s.length);if(s.length+b.getDecodeQueueSize()>C){({promise:u,resolve:l}=ge()),await u;continue}b.decode(A);const P=await I.next();if(P.done)break;A=P.value}await I.return(),!p&&!this._track.input._disposed&&await b.flush(),b.close(),!n&&a&&s.push(a),d=!0,c()})().catch(b=>{y||(y=b,c())});const w=this._track,g=()=>{a==null||a.close();for(const b of s)b.close()};return{async next(){for(;;){if(w.input._disposed)throw g(),new We;if(p)return{value:void 0,done:!0};if(y)throw g(),y;if(s.length>0){const b=s.shift();return l(),{value:b,done:!1}}else if(!d)await o;else return{value:void 0,done:!0}}},async return(){return p=!0,h=!0,l(),c(),g(),{value:void 0,done:!0}},async throw(b){throw b},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){jl(e);const r=ql(e),s=[],n=[];let{promise:a,resolve:o}=ge(),{promise:c,resolve:u}=ge(),l=!1,d=!1,h=null;const p=g=>{n.push(g),o(),{promise:a,resolve:o}=ge()},y={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{const g=await this._createDecoder(C=>{if(u(),d){C.close();return}let P=0;for(;s.length>0&&C.timestamp-s[0]>-1e-10;)P++,s.shift();if(P>0)for(let v=0;v<P;v++)p(v<P-1?C.clone():C);else C.close()},C=>{h||(h=C,o())}),b=this._createPacketSink();let k=null,S=null,A=-1;const _=async()=>{m(S);let C=S;for(g.decode(C);C.sequenceNumber<A;){const P=fo(n.length);for(;n.length+g.getDecodeQueueSize()>P&&!d;)({promise:c,resolve:u}=ge()),await c;if(d)break;const v=await b.getNextPacket(C,y);m(v),g.decode(v),C=v}A=-1},I=async()=>{await g.flush();for(let C=0;C<s.length;C++)p(null);s.length=0};for await(const C of r){if(Ct(C),d||this._track.input._disposed)break;const P=await b.getPacket(C,y),v=P&&await b.getKeyPacket(C,y);if(!v){A!==-1&&(await _(),await I()),p(null),k=null;continue}k&&(v.sequenceNumber!==S.sequenceNumber||P.timestamp<k.timestamp)&&(await _(),await I()),s.push(P.timestamp),A=Math.max(P.sequenceNumber,A),k=P,S=v}!d&&!this._track.input._disposed&&(A!==-1&&await _(),await I()),g.close(),l=!0,o()})().catch(g=>{h||(h=g,o())});const f=this._track,w=()=>{for(const g of n)g==null||g.close()};return{async next(){for(;;){if(f.input._disposed)throw w(),new We;if(d)return{value:void 0,done:!0};if(h)throw w(),h;if(n.length>0){const g=n.shift();return m(g!==void 0),u(),{value:g,done:!1}}else if(!l)await a;else return{value:void 0,done:!0}}},async return(){return d=!0,u(),o(),w(),{value:void 0,done:!0}},async throw(g){throw g},[Symbol.asyncIterator](){return this}}}}const fo=i=>i===0?40:8;class yh extends ca{constructor(e,t,r,s,n,a){super(e,t),this.codec=r,this.decoderConfig=s,this.rotation=n,this.timeResolution=a,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ki,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.frameHandlerSerializer=new ki;const o=Ci.find(c=>c.supports(r,s));if(o)this.customDecoder=new o,this.customDecoder.codec=r,this.customDecoder.config=s,this.customDecoder.onSample=c=>{if(!(c instanceof Ae))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(c)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const c=l=>{this.frameHandlerSerializer.call(async()=>{if(this.alphaQueue.length>0){const d=this.alphaQueue.shift();m(d!==void 0),await this.mergeAlpha(l,d)}else this.colorQueue.push(l)}).catch(d=>this.onError(d))};if(r==="avc"&&this.decoderConfig.description&&an()){const l=rc(he(this.decoderConfig.description));if(l&&l.sequenceParameterSets.length>0){const d=Qn(l.sequenceParameterSets[0]);d&&d.frameMbsOnlyFlag===0&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}const u=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:l=>{try{c(l)}catch(d){this.onError(d)}},error:l=>{l.stack=u,this.onError(l)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){var e;return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),Math.max(this.decoder.decodeQueueSize,((e=this.alphaDecoder)==null?void 0:e.decodeQueueSize)??0))}decode(e){if(this.codec==="hevc"&&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(m(this.decoder),fi()||ya(this.inputTimestamps,e.timestamp,t=>t),an()&&this.currentPacketIndex===0){if(this.codec==="avc"){const t=[];for(const s of tc(e.data,this.decoderConfig)){const n=Br(e.data[s.offset]);n>=20&&n<=31||t.push(e.data.subarray(s.offset,s.offset+s.length))}const r=Au(t,this.decoderConfig);e=new de(r,e.type,e.timestamp,e.duration)}else if(this.codec==="hevc"){const t=Mu(e.data,this.decoderConfig);t&&(e=new de(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha){this.pushNullAlphaFrame();return}if(this.merger||(this.merger=new xs),!this.alphaDecoder){const r=n=>{this.frameHandlerSerializer.call(async()=>{if(this.colorQueue.length>0){const a=this.colorQueue.shift();m(a!==void 0),await this.mergeAlpha(a,n)}else this.alphaQueue.push(n);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){const a=this.colorQueue.shift();m(a!==void 0),await this.mergeAlpha(a,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--}).catch(a=>this.onError(a))},s=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:n=>{try{r(n)}catch(a){this.onError(a)}},error:n=>{n.stack=s,this.onError(n)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=Ts(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe=t==="key"),this.alphaHadKeyframe){if(this.codec==="hevc"&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha)){this.pushNullAlphaFrame();return}this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){this.alphaDecoderQueueSize===0?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of rs(e,this.decoderConfig)){const r=Ht(e[t.offset]);if(r===Te.RASL_N||r===Te.RASL_R)return!0}return!1}sampleHandler(e){if(fi()){if(this.sampleQueue.length>0&&e.timestamp>=we(this.sampleQueue).timestamp){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}ya(this.sampleQueue,e,t=>t.timestamp)}else{const t=this.inputTimestamps.shift();m(t!==void 0),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){if(!t){const n=new Ae(e);this.sampleHandler(n);return}m(this.merger);const r=await this.merger.update(e,t),s=new Ae(r);this.sampleHandler(s)}async flush(){var e;if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),await Promise.all([this.decoder.flush(),(e=this.alphaDecoder)==null?void 0:e.flush()]),await this.frameHandlerSerializer.currentPromise,this.colorQueue.forEach(t=>t.close()),this.colorQueue.length=0,this.alphaQueue.forEach(t=>t==null?void 0:t.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),fi()){for(const t of this.sampleQueue)this.finalizeAndEmitSample(t);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){var e,t;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close(),(e=this.alphaDecoder)==null||e.close(),this.colorQueue.forEach(r=>r.close()),this.colorQueue.length=0,this.alphaQueue.forEach(r=>r==null?void 0:r.close()),this.alphaQueue.length=0,(t=this.merger)==null||t.close());for(const r of this.sampleQueue)r.close();this.sampleQueue.length=0}}let mo=!1;class xs{constructor(){this.canvas=null,this.gl=null,this.program=null,this.vao=null,this.colorTexture=null,this.alphaTexture=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;const e=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!xs.forceCpu&&e&&!mo)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const t=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!t)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=t,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}catch(t){this.gl=null,this.canvas=null,mo=!0,console.warn("Falling back to CPU for color/alpha merging.",t)}}async update(e,t){return this.gl?this.updateGpu(e,t):this.updateCpu(e,t)}createProgram(){m(this.gl);const e=this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
248
|
+
in vec2 a_position;
|
|
249
|
+
in vec2 a_texCoord;
|
|
250
|
+
out vec2 v_texCoord;
|
|
251
|
+
|
|
252
|
+
void main() {
|
|
253
|
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
254
|
+
v_texCoord = a_texCoord;
|
|
255
|
+
}
|
|
256
|
+
`),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
257
|
+
precision highp float;
|
|
258
|
+
|
|
259
|
+
uniform sampler2D u_colorTexture;
|
|
260
|
+
uniform sampler2D u_alphaTexture;
|
|
261
|
+
in vec2 v_texCoord;
|
|
262
|
+
out vec4 fragColor;
|
|
263
|
+
|
|
264
|
+
void main() {
|
|
265
|
+
vec3 color = texture(u_colorTexture, v_texCoord).rgb;
|
|
266
|
+
float alpha = texture(u_alphaTexture, v_texCoord).r;
|
|
267
|
+
fragColor = vec4(color, alpha);
|
|
268
|
+
}
|
|
269
|
+
`),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){m(this.gl);const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),r}createVAO(){m(this.gl),m(this.program);const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const s=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){m(this.gl);const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}updateGpu(e,t){m(this.gl),m(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const r=new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0});return e.close(),t.close(),r}updateCpu(e,t){if(!this.worker){const n=new Blob([`(${bh.toString()})()`],{type:"application/javascript"}),a=URL.createObjectURL(n);this.worker=new Worker(a),URL.revokeObjectURL(a),this.worker.addEventListener("message",o=>{const c=o.data,u=this.pendingRequests.get(c.id);u&&(this.pendingRequests.delete(c.id),"error"in c?u.reject(new Error(c.error)):u.resolve(c.frame))}),this.worker.addEventListener("error",o=>{const c=new Error(o.message||"Color/alpha merge worker error.");for(const u of this.pendingRequests.values())u.reject(c);this.pendingRequests.clear()})}const r=this.nextRequestId++,s=ge();return this.pendingRequests.set(r,s),this.worker.postMessage({id:r,color:e,alpha:t},{transfer:[e,t]}),s.promise}close(){var t,r,s;(r=(t=this.gl)==null?void 0:t.getExtension("WEBGL_lose_context"))==null||r.loseContext(),this.gl=null,this.canvas=null,(s=this.worker)==null||s.terminate(),this.worker=null;const e=new Error("Color/alpha merger closed.");for(const n of this.pendingRequests.values())n.reject(e);this.pendingRequests.clear()}}xs.forceCpu=!0;const bh=()=>{let i=null,e=null,t=Promise.resolve();self.addEventListener("message",c=>{const{id:u,color:l,alpha:d}=c.data;t=t.then(async()=>{try{const h=await r(l,d);self.postMessage({id:u,frame:h},{transfer:[h]})}catch(h){self.postMessage({id:u,error:h.message})}finally{l.close(),d.close()}})});const r=async(c,u)=>{const l=c.format,d=u.format;if(!l||!d)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const h=l.includes("P10"),p=l.includes("P12"),y=d.includes("P10"),f=d.includes("P12");if(y!==h||f!==p)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${l}', alpha: '${d}').`);const w=c.codedWidth,g=c.codedHeight;if(l==="RGBX"||l==="RGBA"||l==="BGRX"||l==="BGRA")return await s(c,u,w,g,l);if(l==="I420"||l==="I420P10"||l==="I420P12"||l==="I422"||l==="I422P10"||l==="I422P12"||l==="I444"||l==="I444P10"||l==="I444P12")return await n(c,u,w,g,l);if(l==="NV12")return await a(c,u,w,g);throw new Error(`CPU color/alpha merging does not support format '${l}'.`)},s=async(c,u,l,d,h)=>{const p=l*d,y=new Uint8Array(p*4);await c.copyTo(y);const f=await o(u,l,d,1);for(let b=0,k=3;b<p;b++,k+=4)y[k]=f[b];const g={format:h==="RGBX"||h==="RGBA"?"RGBA":"BGRA",codedWidth:l,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[y.buffer]};return new VideoFrame(y,g)},n=async(c,u,l,d,h)=>{const p=h.includes("P10"),y=h.includes("P12"),f=p||y?2:1;let w,g;h.startsWith("I420")?(w=Math.ceil(l/2),g=Math.ceil(d/2)):h.startsWith("I422")?(w=Math.ceil(l/2),g=d):(w=l,g=d);const b=l*d,k=w*g,S=b*f,A=k*f,_=b*f,I=S+2*A+_,C=new Uint8Array(I);await c.copyTo(C);const P=await o(u,l,d,f),v=S+2*A;C.set(P,v);const R={format:h.slice(0,4)+"A"+h.slice(4),codedWidth:l,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[C.buffer]};return new VideoFrame(C,R)},a=async(c,u,l,d)=>{const h=l*d,p=Math.ceil(l/2),y=Math.ceil(d/2),f=p*y,w=c.allocationSize();(!e||e.byteLength!==w)&&(e=new Uint8Array(w)),await c.copyTo(e);const g=new Uint8Array(h+2*f+h);g.set(e.subarray(0,h),0);const b=h,k=h+f,S=h;for(let I=0;I<f;I++)g[b+I]=e[S+I*2],g[k+I]=e[S+I*2+1];const A=await o(u,l,d,1);g.set(A,h+2*f);const _={format:"I420A",codedWidth:l,codedHeight:d,timestamp:c.timestamp,duration:c.duration??void 0,transfer:[g.buffer]};return new VideoFrame(g,_)},o=async(c,u,l,d)=>{const h=c.allocationSize();(!i||i.byteLength!==h)&&(i=new Uint8Array(h)),await c.copyTo(i);const p=c.format;if(p==="RGBA"||p==="BGRA"||p==="RGBX"||p==="BGRX"){const y=p==="RGBA"||p==="RGBX"?0:2,f=u*l;for(let w=0;w<f;w++)i[w]=i[w*4+y];return i.subarray(0,f)}else return i.subarray(0,u*l*d)}};class En extends ml{constructor(e){if(!(e instanceof Ps))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),s=await this._track.getRotation(),n=await this._track.getDecoderConfig(),a=await this._track.getTimeResolution();return m(r&&n),new yh(e,t,r,n,s,a)}_createPacketSink(){return new Ii(this._track)}async getSample(e,t={}){Ct(e);for await(const r of this.mediaSamplesAtTimestamps([e],t))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,r={}){return this.mediaSamplesInRange(e,t,r)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Qm{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Ps))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&typeof t!="object")throw new TypeError("options must be an object.");if(t.alpha!==void 0&&typeof t.alpha!="boolean")throw new TypeError("options.alpha, when provided, must be a boolean.");if(t.width!==void 0&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(t.height!==void 0&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(t.fit!==void 0&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(t.width!==void 0&&t.height!==void 0&&t.fit===void 0)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(t.crop!==void 0&&Pi(t.crop,"options."),t.poolSize!==void 0&&(typeof t.poolSize!="number"||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new En(e),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,r=e.rotation??await t.getRotation(),s=await t.getSquarePixelWidth(),n=await t.getSquarePixelHeight(),[a,o]=r%180===0?[s,n]:[n,s];let c=e.crop;c&&(c=as(c,a,o));let[u,l]=c?[c.width,c.height]:[a,o];const d=u/l;e.width!==void 0&&e.height===void 0?(u=e.width,l=Math.round(u/d)):e.width===void 0&&e.height!==void 0?(l=e.height,u=Math.round(l*d)):e.width!==void 0&&e.height!==void 0&&(u=e.width,l=e.height),this._width=u,this._height=l,this._rotation=r,this._crop=c})())}_videoSampleToWrappedCanvas(e){const t=this._width,r=this._height;let s=this._canvasPool[this._nextCanvasIndex],n=!1;s||(typeof document<"u"?(s=document.createElement("canvas"),s.width=t,s.height=r):s=new OffscreenCanvas(t,r),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=s),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const a=s.getContext("2d",{alpha:this._alpha||Zi()});m(a),a.resetTransform(),n||(!this._alpha&&Zi()?(a.fillStyle="black",a.fillRect(0,0,t,r)):a.clearRect(0,0,t,r)),e.drawWithFit(a,{fit:this._fit,rotation:this._rotation,crop:this._crop});const o={canvas:s,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){Ct(e),await this._ensureInit();const r=await this._videoSampleSink.getSample(e,t);return r&&this._videoSampleToWrappedCanvas(r)}async*canvases(e,t,r){await this._ensureInit(),yield*Yi(this._videoSampleSink.samples(e,t,r),s=>this._videoSampleToWrappedCanvas(s))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Yi(this._videoSampleSink.samplesAtTimestamps(e,t),r=>r&&this._videoSampleToWrappedCanvas(r))}}class kh extends ca{constructor(e,t,r,s){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new ki,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=o=>{let c=o.timestamp;this.expectedFirstTimestamp&&this.currentTimestamp===null&&(this.timestampOffset=this.expectedFirstTimestamp-c),c+=this.timestampOffset,(this.currentTimestamp===null||Math.abs(c-this.currentTimestamp)>=o.duration)&&(this.currentTimestamp=c);const u=this.currentTimestamp;if(this.currentTimestamp+=o.duration,o.numberOfFrames===0){o.close();return}const l=s.sampleRate;o.setTimestamp(Math.round(u*l)/l),e(o)},a=_i.find(o=>o.supports(r,s));if(a)this.customDecoder=new a,this.customDecoder.codec=r,this.customDecoder.config=s,this.customDecoder.onSample=o=>{if(!(o instanceof Ee))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(o)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const o=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:c=>{try{n(new Ee(c))}catch(u){this.onError(u)}},error:c=>{c.stack=o,this.onError(c)}}),this.decoder.configure(s)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(m(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(m(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(m(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(m(this.decoder),this.decoder.close())}}class Th extends ca{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,m(Pe.includes(r.codec)),this.codec=r.codec;const{dataType:s,sampleSize:n,littleEndian:a}=st(this.codec);switch(this.inputSampleSize=n,n){case 1:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint8(c)-2**7:s==="signed"?this.readInputValue=(o,c)=>o.getInt8(c):s==="ulaw"?this.readInputValue=(o,c)=>ph(o.getUint8(c)):s==="alaw"?this.readInputValue=(o,c)=>wh(o.getUint8(c)):m(!1);break;case 2:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint16(c,a)-2**15:s==="signed"?this.readInputValue=(o,c)=>o.getInt16(c,a):m(!1);break;case 3:s==="unsigned"?this.readInputValue=(o,c)=>ds(o,c,a)-2**23:s==="signed"?this.readInputValue=(o,c)=>Kl(o,c,a):m(!1);break;case 4:s==="unsigned"?this.readInputValue=(o,c)=>o.getUint32(c,a)-2**31:s==="signed"?this.readInputValue=(o,c)=>o.getInt32(c,a):s==="float"?this.readInputValue=(o,c)=>o.getFloat32(c,a):m(!1);break;case 8:s==="float"?this.readInputValue=(o,c)=>o.getFloat64(c,a):m(!1);break;default:De(n),m(!1)}switch(n){case 1:s==="ulaw"||s==="alaw"?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,u)=>o.setInt16(c,u,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(o,c,u)=>o.setUint8(c,u+2**7));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(o,c,u)=>o.setInt16(c,u,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(o,c,u)=>o.setInt32(c,u<<8,!0);break;case 4:this.outputSampleSize=4,s==="float"?(this.outputFormat="f32",this.writeOutputValue=(o,c,u)=>o.setFloat32(c,u,!0)):(this.outputFormat="s32",this.writeOutputValue=(o,c,u)=>o.setInt32(c,u,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(o,c,u)=>o.setFloat32(c,u,!0);break;default:De(n),m(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=Z(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,s=r*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(s),a=new DataView(n);for(let l=0;l<r*this.decoderConfig.numberOfChannels;l++){const d=l*this.inputSampleSize,h=l*this.outputSampleSize,p=this.readInputValue(t,d);this.writeOutputValue(a,h,p)}const o=r/this.decoderConfig.sampleRate;(this.currentTimestamp===null||Math.abs(e.timestamp-this.currentTimestamp)>=o)&&(this.currentTimestamp=e.timestamp);const c=this.currentTimestamp;this.currentTimestamp+=o;const u=new Ee({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:c});this.onSample(u)}async flush(){}close(){}}class vn extends ml{constructor(e){if(!(e instanceof Cs))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const r=await this._track.getCodec(),s=await this._track.getDecoderConfig();return m(r&&s),Pe.includes(s.codec)?new Th(e,t,s):new kh(e,t,r,s)}_createPacketSink(){return new Ii(this._track)}async getSample(e,t={}){Ct(e);for await(const r of this.mediaSamplesAtTimestamps([e],t))return r;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,r={}){return this.mediaSamplesInRange(e,t,r)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Xm{constructor(e){if(!(e instanceof Cs))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new vn(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){Ct(e);const r=await this._audioSampleSink.getSample(e,t);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(e,t,r){return Yi(this._audioSampleSink.samples(e,t,r),s=>this._audioSampleToWrappedArrayBuffer(s))}buffersAtTimestamps(e,t){return Yi(this._audioSampleSink.samplesAtTimestamps(e,t),r=>r&&this._audioSampleToWrappedArrayBuffer(r))}}/*!
|
|
270
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
271
|
+
*
|
|
272
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
273
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
274
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
275
|
+
*/class Fi{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Ps}isAudioTrack(){return this instanceof Cs}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return me(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return me(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return me(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return me(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getDisposition(){return this._backing.getDisposition()}get disposition(){return me(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return(e==null?void 0:e.timestamp)??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e}),r=((t==null?void 0:t.timestamp)??0)+((t==null?void 0:t.duration)??0);return vr(r,await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const r=new Ii(this);let s=1/0,n=-1/0,a=0,o=0;for await(const c of r.packets(void 0,void 0,{metadataOnly:!0,...t})){if(a>=e&&c.timestamp>=n)break;s=Math.min(s,c.timestamp),n=Math.max(n,c.timestamp+c.duration),a++,o+=c.byteLength}return{packetCount:a,averagePacketRate:a?Number((a/(n-s)).toPrecision(16)):0,averageBitrate:a?Number((8*o/(n-s)).toPrecision(16)):0}}async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Fi))throw new TypeError("other must be an InputTrack.");return this.input!==e.input||this===e?!1:(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(Zt({filter:t=>t.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Zt({filter:t=>t.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Zt({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Zt({filter:t=>t.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Zt({filter:t=>t.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=js(e));const t=await this.input.getTracks();for(const r of t)if(this.canBePairedWith(r)&&(!e||await e(r)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=js(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=js(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const me=(i,e,t)=>{if(i instanceof Promise)throw new Error(`'${e}' is deprecated and not available synchronously for this track. Use the preferred '${t}()' instead.`);return i},js=i=>{if(i!==void 0&&typeof i!="function")throw new TypeError("predicate, when provided, must be a function.");return i?e=>{const t=s=>{if(typeof s!="boolean")throw new TypeError("predicate must return or resolve to a boolean value.");return s},r=i(e);return r instanceof Promise?r.then(t):t(r)}:void 0};class Ps extends Fi{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return me(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var e,t;return await((t=(e=this._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??!1}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return me(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return me(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return me(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return me(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return me(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=Ti({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=Ti({num:me(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*me(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:me(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*me(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){var r,s;const e=await((s=(r=this._backing).getMetadataDisplayWidth)==null?void 0:s.call(r));return e??(await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight())}get displayWidth(){var s,n;const e=(n=(s=this._backing).getMetadataDisplayWidth)==null?void 0:n.call(s);if(e!==void 0){const a=me(e,"displayWidth","getDisplayWidth");if(a!==null)return a}const r=me(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return me(r,"displayWidth","getDisplayWidth")}async getDisplayHeight(){var r,s;const e=await((s=(r=this._backing).getMetadataDisplayHeight)==null?void 0:s.call(r));return e??(await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth())}get displayHeight(){var s,n;const e=(n=(s=this._backing).getMetadataDisplayHeight)==null?void 0:n.call(s);if(e!==void 0){const a=me(e,"displayHeight","getDisplayHeight");if(a!==null)return a}const r=me(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return me(r,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return e.primaries==="bt2020"||e.primaries==="smpte432"||e.transfer==="pg"||e.transfer==="hlg"||e.matrix==="bt2020-ncl"}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var r,s;const e=await((s=(r=this._backing).getMetadataCodecParameterString)==null?void 0:s.call(r));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return m(t!==null),Ci.some(s=>s.supports(t,e))?!0:typeof VideoDecoder>"u"?!1:(await VideoDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof de))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(t===null)return null;const r=await this.getDecoderConfig();return m(r),Ts(t,r,e.data)}}class Cs extends Fi{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return me(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){var e,t;return await((t=(e=this._backing).getHasOnlyKeyPackets)==null?void 0:t.call(e))??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return me(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return me(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){var r,s;const e=await((s=(r=this._backing).getMetadataCodecParameterString)==null?void 0:s.call(r));if(e!=null)return e;const t=await this._backing.getDecoderConfig();return(t==null?void 0:t.codec)??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();return m(t!==null),_i.some(r=>r.supports(t,e))||e.codec.startsWith("pcm-")?!0:typeof AudioDecoder>"u"?!1:(await AudioDecoder.isConfigSupported(e)).supported===!0}catch(e){return console.error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof de))throw new TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}const $m=i=>i??1/0,po=i=>-(i??-1/0),ni=i=>-i,ai=i=>{if(typeof i!="object"||!i)throw new TypeError("query must be an object.");if(i.filter!==void 0&&typeof i.filter!="function")throw new TypeError("query.filter, when provided, must be a function.");if(i.sortBy!==void 0&&typeof i.sortBy!="function")throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:i.filter?e=>{const t=s=>{if(typeof s!="boolean")throw new TypeError("query.filter must return or resolve to a boolean.");return s},r=i.filter(e);return r instanceof Promise?r.then(t):t(r)}:void 0,sortBy:i.sortBy?e=>{const t=s=>{if(typeof s!="number"&&(!Array.isArray(s)||!s.every(n=>typeof n=="number")))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return s},r=i.sortBy(e);return r instanceof Promise?r.then(t):t(r)}:void 0}},Zt=(i,e)=>({filter:i!=null&&i.filter||e!=null&&e.filter?t=>{var n;const r=((n=i==null?void 0:i.filter)==null?void 0:n.call(i,t))??!0,s=a=>{var o;return a===!1?!1:((o=e==null?void 0:e.filter)==null?void 0:o.call(e,t))??!0};return r instanceof Promise?r.then(s):s(r)}:void 0,sortBy:i!=null&&i.sortBy||e!=null&&e.sortBy?t=>{var a,o;const r=((a=i==null?void 0:i.sortBy)==null?void 0:a.call(i,t))??[],s=((o=e==null?void 0:e.sortBy)==null?void 0:o.call(e,t))??[],n=(c,u)=>[...Array.isArray(c)?c:[c],...Array.isArray(u)?u:[u]];return r instanceof Promise||s instanceof Promise?Promise.all([r,s]).then(([c,u])=>n(c,u)):n(r,s)}:void 0}),Ks=async(i,e)=>{let t=i;if(e!=null&&e.filter){const a=i.map(c=>e.filter(c));if(a.some(c=>c instanceof Promise)){const c=await Promise.all(a);t=i.filter((u,l)=>c[l])}else t=i.filter((c,u)=>a[u])}if(!(e!=null&&e.sortBy))return t;const r=t.map(a=>e.sortBy(a)),n=r.some(a=>a instanceof Promise)?await Promise.all(r):r;return t.map((a,o)=>({track:a,sortValue:n[o]})).sort((a,o)=>{const c=Array.isArray(a.sortValue)?a.sortValue:[a.sortValue],u=Array.isArray(o.sortValue)?o.sortValue:[o.sortValue],l=Math.max(c.length,u.length);for(let d=0;d<l;d++){const h=c[d]??0,p=u[d]??0;if(h!==p)return h-p}return 0}).map(a=>a.track)};/*!
|
|
276
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
277
|
+
*
|
|
278
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
279
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
280
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
281
|
+
*/zn();const Sh=1,Ah=2;let Xt=null;typeof FinalizationRegistry<"u"&&(Xt=new FinalizationRegistry(i=>{for(const e of i)e.freed||e.free()}));class _s extends fs{get disposed(){return this._disposed}constructor(e){if(super(),this._demuxerPromise=null,this._format=null,this._trackBackingsCache=null,this._backingToTrack=new Map,this._disposed=!1,this._nextSourceCacheAge=0,this._sourceRefs=[],this._sourceCache=[],this._sourceCachePromises=[],this._onFormatDetermined=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(t=>!(t instanceof ft)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof $e||e.source instanceof ea))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof $e&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(e.initInput!==void 0&&!(e.initInput instanceof _s))throw new TypeError("options.initInput, when provided, must be an Input.");e.formatOptions!==void 0&&Gd(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof $e?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef),Xt==null||Xt.register(this,this._sourceRefs,this)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){m(this._rootSource instanceof Nr);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=Sh){const r=this._sourceCache.find(a=>a.cacheGroup===t&&Ja(a.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());const s=this._sourceCachePromises.find(a=>a.cacheGroup===t&&Ja(a.request,e));if(s)return s.promise.then(a=>a.sourceRef.source.ref());const n=(async()=>{const a=await this._getSourceUncached(e);if(ui(this._sourceCache,d=>d.cacheGroup===t&&d.sourceRef.source._refCount===1)>=4){const d=Un(this._sourceCache,p=>p.cacheGroup===t&&p.sourceRef.source._refCount===1?p.age:1/0);m(d!==-1);const h=this._sourceCache[d];this._sourceCache.splice(d,1),h.sourceRef.free(),Wo(this._sourceRefs,h.sourceRef)}this._sourceRefs.push(a);const u=this._sourceCachePromises.findIndex(d=>d.request===e);return m(u!==-1),this._sourceCachePromises.splice(u,1),{request:e,sourceRef:a,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:n}),n.then(a=>{const o=a.sourceRef.source.ref();return this._sourceCache.push(a),o})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{var e;this._reader=new Ki(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const t of this._formats)if(await t._canReadInput(this))return this._format=t,(e=this._onFormatDetermined)==null||e.call(this,t),t._createDemuxer(this);throw new go})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),m(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof go)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(s=>s!==null);if(t.length===0)return 0;const r=await Promise.all(t.map(s=>s.getFirstTimestamp()));return Math.min(...r)}async computeDuration(e,t){e??(e=await this.getTracks());const r=e.filter(n=>n!==null);if(r.length===0)return 0;const s=await Promise.all(r.map(n=>n.computeDuration(t)));return Math.max(...s)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const r=e.filter(a=>a!==null),n=(await Promise.all(r.map(a=>a.getDurationFromMetadata(t)))).filter(a=>a!==null);return n.length===0?null:Math.max(...n)}async getTracks(e){e&&(e=ai(e));const r=(await this._getTrackBackings()).map(s=>this._wrapBackingAsTrack(s));return Ks(r,e)}async getVideoTracks(e){e&&(e=ai(e));const r=(await this.getTracks()).filter(s=>s.isVideoTrack());return Ks(r,e)}async getAudioTracks(e){e&&(e=ai(e));const r=(await this.getTracks()).filter(s=>s.isAudioTrack());return Ks(r,e)}async getPrimaryVideoTrack(e){e&&(e=ai(e));const t=Zt(e,{sortBy:async s=>[ni((await s.getDisposition()).default),ni(await s.hasPairableAudioTrack()),ni(!await s.hasOnlyKeyPackets()),po(await s.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=ai(e));const t=await this.getPrimaryVideoTrack(),r=Zt(e,{sortBy:async n=>[ni(!t||n.canBePairedWith(t)),ni((await n.getDisposition()).default),po(await n.getBitrate())]});return(await this.getAudioTracks(r))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const s=e.getType()==="video"?new Ps(this,e):new Cs(this,e);return this._backingToTrack.set(e,s),s}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){var e;if(!this._disposed){this._disposed=!0;for(const t of this._sourceRefs)t.free();this._sourceRefs.length=0,Xt==null||Xt.unregister(this),(e=this._demuxerPromise)==null||e.then(t=>t.dispose())}}[Symbol.dispose](){this.dispose()}}class go extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class We extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}/*!
|
|
282
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
283
|
+
*
|
|
284
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
285
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
286
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
287
|
+
*/class Ki{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(e===void 0)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new We;if(e<0||this.fileSizeNonStrict!==null&&e+t>this.fileSizeNonStrict)return null;if(t===0){const n=new Uint8Array(0);return new Me(n,Z(n),0,e,e)}const r=e+t,s=this.source._read(e,r,Lc,Hc);return s instanceof Promise?s.then(n=>n?new Me(n.bytes,n.view,n.offset,e,r):null):s?new Me(s.bytes,s.view,s.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new We;if(e<0)return null;if(this.fileSizeNonStrict!==null)return this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,r));{const s=this.requestSlice(e,r),n=a=>a||(m(this.fileSizeNonStrict!==null),this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,r)));return s instanceof Promise?s.then(n):n(s)}}requestEntireFile(){if(this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const e=1024;return(async()=>{const t=[];let r=0;for(;;){if(t.length===1&&this.fileSizeNonStrict!==null)return this.requestSlice(0,this.fileSizeNonStrict);const a=t.length*e;let o=this.requestSliceRange(a,0,e);if(o instanceof Promise&&(o=await o),!o)break;t.push(K(o,o.length)),r+=o.length}const s=new Uint8Array(r);let n=0;for(const a of t)s.set(a,n),n+=a.length;return new Me(s,Z(s),0,0,r)})()}}class Me{constructor(e,t,r,s,n){this.bytes=e,this.view=t,this.offset=r,this.start=s,this.end=n,this.bufferPos=s-r}static tempFromBytes(e){return new Me(e,Z(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 Me(this.bytes,this.view,this.offset,e,e+t)}}const Ne=(i,e)=>{if(i.filePos<i.start||i.filePos+e>i.end)throw new RangeError(`Tried reading [${i.filePos}, ${i.filePos+e}), but slice is [${i.start}, ${i.end}). This is likely an internal error, please report it alongside the file that caused it.`)},K=(i,e)=>{Ne(i,e);const t=i.bytes.subarray(i.bufferPos,i.bufferPos+e);return i.bufferPos+=e,t},j=i=>(Ne(i,1),i.view.getUint8(i.bufferPos++)),oi=(i,e)=>{Ne(i,2);const t=i.view.getUint16(i.bufferPos,e);return i.bufferPos+=2,t},ke=i=>{Ne(i,2);const e=i.view.getUint16(i.bufferPos,!1);return i.bufferPos+=2,e},wt=i=>{Ne(i,3);const e=ds(i.view,i.bufferPos,!1);return i.bufferPos+=3,e},Bn=i=>{Ne(i,2);const e=i.view.getInt16(i.bufferPos,!1);return i.bufferPos+=2,e},Vt=(i,e)=>{Ne(i,4);const t=i.view.getUint32(i.bufferPos,e);return i.bufferPos+=4,t},U=i=>{Ne(i,4);const e=i.view.getUint32(i.bufferPos,!1);return i.bufferPos+=4,e},Sr=i=>{Ne(i,4);const e=i.view.getUint32(i.bufferPos,!0);return i.bufferPos+=4,e},tr=i=>{Ne(i,4);const e=i.view.getInt32(i.bufferPos,!1);return i.bufferPos+=4,e},xh=i=>{Ne(i,4);const e=i.view.getInt32(i.bufferPos,!0);return i.bufferPos+=4,e},wo=(i,e)=>{let t,r;return e?(t=Vt(i,!0),r=Vt(i,!0)):(r=Vt(i,!1),t=Vt(i,!1)),r*4294967296+t},Ge=i=>{const e=U(i),t=U(i);return e*4294967296+t},Ph=i=>{const e=tr(i),t=U(i);return e*4294967296+t},Ch=i=>{const e=Sr(i);return xh(i)*4294967296+e},_h=i=>{Ne(i,4);const e=i.view.getFloat32(i.bufferPos,!1);return i.bufferPos+=4,e},pl=i=>{Ne(i,8);const e=i.view.getFloat64(i.bufferPos,!1);return i.bufferPos+=8,e},ye=(i,e)=>{Ne(i,e);let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(i.bytes[i.bufferPos++]);return t},gl=(i,e,t)=>qe.decode(K(i,e)).split(`
|
|
288
|
+
`).map(n=>n.trim()).filter(n=>{var a;return n.length>0&&!((a=t==null?void 0:t.ignore)!=null&&a.call(t,n))});/*!
|
|
289
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
290
|
+
*
|
|
291
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
292
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
293
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
294
|
+
*/var Ar;(function(i){i[i.Unsynchronisation=128]="Unsynchronisation",i[i.ExtendedHeader=64]="ExtendedHeader",i[i.ExperimentalIndicator=32]="ExperimentalIndicator",i[i.Footer=16]="Footer"})(Ar||(Ar={}));var _e;(function(i){i[i.ISO_8859_1=0]="ISO_8859_1",i[i.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",i[i.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",i[i.UTF_8=3]="UTF_8"})(_e||(_e={}));const Gi=128,It=10,xr=["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"],Ih=(i,e)=>{var d;const t=i.filePos;e.raw??(e.raw={}),(d=e.raw).TAG??(d.TAG=K(i,Gi-3)),i.filePos=t;const r=fr(i,30);r&&(e.title??(e.title=r));const s=fr(i,30);s&&(e.artist??(e.artist=s));const n=fr(i,30);n&&(e.album??(e.album=n));const a=fr(i,4),o=Number.parseInt(a,10);Number.isInteger(o)&&o>0&&(e.date??(e.date=new Date(o,0,1)));const c=K(i,30);let u;if(c[28]===0&&c[29]!==0){const h=c[29];h>0&&(e.trackNumber??(e.trackNumber=h)),i.skip(-30),u=fr(i,28),i.skip(2)}else i.skip(-30),u=fr(i,30);u&&(e.comment??(e.comment=u));const l=j(i);l<xr.length&&(e.genre??(e.genre=xr[l]))},fr=(i,e)=>{const t=K(i,e),r=mr(t.indexOf(0),t.length),s=t.subarray(0,r);let n="";for(let a=0;a<s.length;a++)n+=String.fromCharCode(s[a]);return n.trimEnd()},nr=i=>{const e=i.filePos,t=ye(i,3),r=j(i),s=j(i),n=j(i),a=U(i);if(t!=="ID3"||r===255||s===255||(a&2155905152)!==0)return i.filePos=e,null;const o=dn(a);return{majorVersion:r,revision:s,flags:n,size:o}},la=(i,e,t)=>{var n,a,o,c,u;if(![2,3,4].includes(e.majorVersion)){console.warn(`Unsupported ID3v2 major version: ${e.majorVersion}`);return}const r=K(i,e.size),s=new Eh(e,r);if(e.flags&Ar.Footer&&s.removeFooter(),e.flags&Ar.Unsynchronisation&&e.majorVersion===3&&s.ununsynchronizeAll(),e.flags&Ar.ExtendedHeader){const l=s.readU32();e.majorVersion===3?s.pos+=l:s.pos+=l-4}for(;s.pos<=s.bytes.length-s.frameHeaderSize();){const l=s.readId3V2Frame();if(!l)break;const d=s.pos,h=s.pos+l.size;let p=!1,y=!1,f=!1;if(e.majorVersion===3?(p=!!(l.flags&64),y=!!(l.flags&128)):e.majorVersion===4&&(p=!!(l.flags&4),y=!!(l.flags&8),f=!!(l.flags&2)||!!(e.flags&Ar.Unsynchronisation)),p){console.warn(`Skipping encrypted ID3v2 frame ${l.id}`),s.pos=h;continue}if(y){console.warn(`Skipping compressed ID3v2 frame ${l.id}`),s.pos=h;continue}if(f&&s.ununsynchronizeRegion(s.pos,h),t.raw??(t.raw={}),l.id==="TXXX"){const w=(n=t.raw).TXXX??(n.TXXX={}),g=s.readId3V2TextEncoding(),b=s.readId3V2Text(g,h),k=s.readId3V2Text(g,h);w[b]??(w[b]=k)}else l.id[0]==="T"?(a=t.raw)[o=l.id]??(a[o]=s.readId3V2EncodingAndText(h)):(c=t.raw)[u=l.id]??(c[u]=s.readBytes(l.size));switch(s.pos=d,l.id){case"TIT2":case"TT2":t.title??(t.title=s.readId3V2EncodingAndText(h));break;case"TIT3":case"TT3":t.description??(t.description=s.readId3V2EncodingAndText(h));break;case"TPE1":case"TP1":t.artist??(t.artist=s.readId3V2EncodingAndText(h));break;case"TALB":case"TAL":t.album??(t.album=s.readId3V2EncodingAndText(h));break;case"TPE2":case"TP2":t.albumArtist??(t.albumArtist=s.readId3V2EncodingAndText(h));break;case"TRCK":case"TRK":{const g=s.readId3V2EncodingAndText(h).split("/"),b=Number.parseInt(g[0],10),k=g[1]&&Number.parseInt(g[1],10);Number.isInteger(b)&&b>0&&(t.trackNumber??(t.trackNumber=b)),k&&Number.isInteger(k)&&k>0&&(t.tracksTotal??(t.tracksTotal=k))}break;case"TPOS":case"TPA":{const g=s.readId3V2EncodingAndText(h).split("/"),b=Number.parseInt(g[0],10),k=g[1]&&Number.parseInt(g[1],10);Number.isInteger(b)&&b>0&&(t.discNumber??(t.discNumber=b)),k&&Number.isInteger(k)&&k>0&&(t.discsTotal??(t.discsTotal=k))}break;case"TCON":case"TCO":{const w=s.readId3V2EncodingAndText(h);let g=/^\((\d+)\)/.exec(w);if(g){const b=Number.parseInt(g[1]);if(xr[b]!==void 0){t.genre??(t.genre=xr[b]);break}}if(g=/^\d+$/.exec(w),g){const b=Number.parseInt(g[0]);if(xr[b]!==void 0){t.genre??(t.genre=xr[b]);break}}t.genre??(t.genre=w)}break;case"TDRC":case"TDAT":{const w=s.readId3V2EncodingAndText(h),g=new Date(w);Number.isNaN(g.getTime())||(t.date??(t.date=g))}break;case"TYER":case"TYE":{const w=s.readId3V2EncodingAndText(h),g=Number.parseInt(w,10);Number.isInteger(g)&&(t.date??(t.date=new Date(g,0,1)))}break;case"USLT":case"ULT":{const w=s.readU8();s.pos+=3,s.readId3V2Text(w,h),t.lyrics??(t.lyrics=s.readId3V2Text(w,h))}break;case"COMM":case"COM":{const w=s.readU8();s.pos+=3,s.readId3V2Text(w,h),t.comment??(t.comment=s.readId3V2Text(w,h))}break;case"APIC":case"PIC":{const w=s.readId3V2TextEncoding();let g;if(e.majorVersion===2){const A=s.readAscii(3);g=A==="PNG"?"image/png":A==="JPG"?"image/jpeg":"image/*"}else g=s.readId3V2Text(w,h);const b=s.readU8(),k=s.readId3V2Text(w,h).trimEnd(),S=h-s.pos;if(S>=0){const A=s.readBytes(S);t.images||(t.images=[]),t.images.push({data:A,mimeType:g,kind:b===3?"coverFront":b===4?"coverBack":"unknown",description:k})}}break;default:s.pos+=l.size;break}s.pos=h}};class Eh{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return this.header.majorVersion===2?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const r=this.bytes[t];e.push(r),r===255&&t!==this.bytes.length-1&&this.bytes[t]===0&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const r=[];for(let a=e;a<t;a++){const o=this.bytes[a];r.push(o),o===255&&a!==t-1&&this.bytes[a+1]===0&&a++}const s=this.bytes.subarray(0,e),n=this.bytes.subarray(t);this.bytes=new Uint8Array(s.length+r.length+n.length),this.bytes.set(s,0),this.bytes.set(r,s.length),this.bytes.set(n,s.length+r.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-It),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,e*256+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(this.header.majorVersion===2){const e=this.readAscii(3);if(e==="\0\0\0")return null;const t=this.readU24();return{id:e,size:t,flags:0}}else{const e=this.readAscii(4);if(e==="\0\0\0\0")return null;const t=this.readU32();let r=this.header.majorVersion===4?dn(t):t;const s=this.readU16(),n=this.pos,a=o=>{const c=this.pos+o;if(c>this.bytes.length)return!1;if(c<=this.bytes.length-this.frameHeaderSize()){this.pos+=o;const u=this.readAscii(4);if(u!=="\0\0\0\0"&&!/[0-9A-Z]{4}/.test(u))return!1}return!0};if(!a(r)){const o=this.header.majorVersion===4?t:dn(t);a(o)&&(r=o)}return this.pos=n,{id:e,size:r,flags:s}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const r=this.pos,s=this.readBytes(t-this.pos);switch(e){case _e.ISO_8859_1:{let n="";for(let a=0;a<s.length;a++){const o=s[a];if(o===0){this.pos=r+a+1;break}n+=String.fromCharCode(o)}return n}case _e.UTF_16_WITH_BOM:if(s[0]===255&&s[1]===254){const n=new TextDecoder("utf-16le"),a=mr(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else if(s[0]===254&&s[1]===255){const n=new TextDecoder("utf-16be"),a=mr(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(a+2,s.length),n.decode(s.subarray(2,a))}else{const n=mr(s.findIndex(a=>a===0),s.length);return this.pos=r+Math.min(n+1,s.length),qe.decode(s.subarray(0,n))}case _e.UTF_16_BE_NO_BOM:{const n=new TextDecoder("utf-16be"),a=mr(s.findIndex((o,c)=>o===0&&s[c+1]===0&&c%2===0),s.length);return this.pos=r+Math.min(a+2,s.length),n.decode(s.subarray(0,a))}case _e.UTF_8:{const n=mr(s.findIndex(a=>a===0),s.length);return this.pos=r+Math.min(n+1,s.length),qe.decode(s.subarray(0,n))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class ua{constructor(e){this.helper=new Uint8Array(8),this.helperView=Z(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(),s=new Set;for(const{key:o,value:c}of Rr(e))switch(o){case"title":this.writeId3V2TextFrame("TIT2",c),s.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",c),s.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",c),s.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",c),s.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",c),s.add("TPE2");break;case"trackNumber":{const u=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();this.writeId3V2TextFrame("TRCK",u),s.add("TRCK")}break;case"discNumber":{const u=e.discsTotal!==void 0?`${c}/${e.discsTotal}`:c.toString();this.writeId3V2TextFrame("TPOS",u),s.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",c),s.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",c.toISOString().slice(0,10)),s.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(c),s.add("USLT");break;case"comment":this.writeId3V2CommentFrame(c),s.add("COMM");break;case"images":{const u={coverFront:3,coverBack:4,unknown:0};for(const l of c){const d=u[l.kind]??0,h=l.description??"";this.writeId3V2ApicFrame(l.mimeType,d,h,l.data)}}break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:De(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];if(c==null||o.length!==4||s.has(o))continue;let u;if(typeof c=="string")if(pt(c)){u=new Uint8Array(c.length+2),u[0]=_e.ISO_8859_1;for(let d=0;d<c.length;d++)u[d+1]=c.charCodeAt(d)}else{const d=le.encode(c);u=new Uint8Array(d.byteLength+2),u[0]=_e.UTF_8,u.set(d,1)}else if(c instanceof Uint8Array)u=c;else if(o==="TXXX"&&Ko(c)){for(const l in c){const d=c[l],h=pt(l)&&pt(d),p=h?null:le.encode(l),y=h?null:le.encode(d),f=h?l.length:p.byteLength,w=h?d.length:y.byteLength,g=1+f+1+w+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(g),this.writeU16(0),this.writeU8(h?_e.ISO_8859_1:_e.UTF_8),h?(this.writeIsoString(l),this.writeIsoString(d)):(this.writer.write(p),this.writeU8(0),this.writer.write(y),this.writeU8(0))}continue}else continue;this.writeAscii(o),this.writeSynchsafeU32(u.byteLength),this.writeU16(0),this.writer.write(u)}const n=this.writer.getPos(),a=n-r;return this.writer.seek(t+6),this.writeSynchsafeU32(a),this.writer.seek(n),a+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32(Su(e))}writeIsoString(e){const t=new Uint8Array(e.length+1);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);this.writer.write(t)}writeUtf8String(e){const t=le.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){const r=pt(t),n=1+(r?t.length:le.encode(t).byteLength)+1;this.writeAscii(e),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(r?_e.ISO_8859_1:_e.UTF_8),r?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){const t=pt(e),r="",s=4+r.length+1+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(s),this.writeU16(0),this.writeU8(t?_e.ISO_8859_1:_e.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(r),this.writeIsoString(e)):(this.writeUtf8String(r),this.writeUtf8String(e))}writeId3V2CommentFrame(e){const t=pt(e),r=t?e.length:le.encode(e).byteLength,s="",n=4+s.length+1+r+1;this.writeAscii("COMM"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(t?_e.ISO_8859_1:_e.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(s),this.writeIsoString(e)):(this.writeUtf8String(s),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,r,s){const n=pt(e)&&pt(r),a=n?r.length:le.encode(r).byteLength,o=1+e.length+1+1+a+1+s.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(o),this.writeU16(0),this.writeU8(n?_e.ISO_8859_1:_e.UTF_8),n?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),n?this.writeIsoString(r):this.writeUtf8String(r),this.writer.write(s)}}/*!
|
|
295
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
296
|
+
*
|
|
297
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
298
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
299
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
300
|
+
*/class Bt{constructor(e){this.mutex=new lr,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,r){if(t<0)throw new Error(`Timestamps must be non-negative (got ${t}s).`);let s=this.trackTimestampInfo.get(e);if(s){if(r&&(s.maxTimestampBeforeLastKeyPacket=s.maxTimestamp),s.maxTimestampBeforeLastKeyPacket!==null&&t<s.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 ${s.maxTimestampBeforeLastKeyPacket}s.`);s.maxTimestamp=Math.max(s.maxTimestamp,t)}else{if(!r)throw new Error("First packet must be a key packet.");s={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,s)}}}/*!
|
|
301
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
302
|
+
*
|
|
303
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
304
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
305
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
306
|
+
*/class vh extends Bt{constructor(e,t){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),Si(this.output._metadataTags)||new ua(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw new Error("ADTS does not support video.")}async addEncodedAudioPacket(e,t,r){var n;const s=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.inputIsAdts===null){qt(r);const a=(n=r==null?void 0:r.decoderConfig)==null?void 0:n.description;if(this.inputIsAdts=!a,!this.inputIsAdts){const o=Bi(he(a)),c=Go(o);this.header=c.header,this.headerBitstream=c.bitstream}}if(this.inputIsAdts){const a=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,a)}else{m(this.header);const a=t.data.byteLength+this.header.byteLength;Qo(this.headerBitstream,a);const o=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){const c=new Uint8Array(a);c.set(this.header,0),c.set(t.data,this.header.byteLength),this.format._options.onFrame(c,o)}}await this.writer.flush()}finally{s()}}async addSubtitleCue(){throw new Error("ADTS does not support subtitles.")}async finalize(){(await this.mutex.acquire())()}}/*!
|
|
307
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
308
|
+
*
|
|
309
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
310
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
311
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
312
|
+
*/const yo=new Uint8Array([102,76,97,67]),Bh=38,Fh=34;class Rh extends Bt{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(yo),e()}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:r,minimumFrameSize:s,maximumFrameSize:n,sampleRate:a,channels:o,totalSamples:c}){m(this.writer.getPos()===4);const u=!Si(this.output._metadataTags),l=new re(new Uint8Array(4));l.writeBits(1,+!u),l.writeBits(7,Pt.STREAMINFO),l.writeBits(24,Fh),this.writer.write(l.bytes);const d=new re(new Uint8Array(18));if(d.writeBits(16,t),d.writeBits(16,r),d.writeBits(24,s),d.writeBits(24,n),d.writeBits(20,a),d.writeBits(3,o-1),d.writeBits(5,e-1),c>=2**32)throw new Error("This muxer only supports writing up to 2 ** 32 samples");d.writeBits(4,0),d.writeBits(32,c),this.writer.write(d.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){var o,c,u;const t=32+e.mimeType.length+(((o=e.description)==null?void 0:o.length)??0)+e.data.length,r=new Uint8Array(t);let s=0;const n=Z(r);n.setUint32(s,e.kind==="coverFront"?3:e.kind==="coverBack"?4:0),s+=4,n.setUint32(s,e.mimeType.length),s+=4,r.set(le.encode(e.mimeType),8),s+=e.mimeType.length,n.setUint32(s,((c=e.description)==null?void 0:c.length)??0),s+=4,r.set(le.encode(e.description??""),s),s+=((u=e.description)==null?void 0:u.length)??0,s+=16,n.setUint32(s,e.data.length),s+=4,r.set(e.data,s),s+=e.data.length,m(s===t);const a=new re(new Uint8Array(4));a.writeBits(1,0),a.writeBits(7,Pt.PICTURE),a.writeBits(24,t),this.writer.write(a.bytes),this.writer.write(r)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(Bh+yo.byteLength),Si(this.output._metadataTags)){this.metadataWritten=!0;return}const e=this.output._metadataTags.images??[];for(const s of e)this.writePictureBlock(s);const t=fn(new Uint8Array(0),this.output._metadataTags,!1),r=new re(new Uint8Array(4));r.writeBits(1,1),r.writeBits(7,Pt.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,t,r){const s=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,t.type==="key"),this.sampleRate===null){qt(r),m(r),m(r.decoderConfig),m(r.decoderConfig.description),this.sampleRate=r.decoderConfig.sampleRate,this.channels=r.decoderConfig.numberOfChannels;const d=new re(he(r.decoderConfig.description));d.skipBits(167);const h=d.readBits(5)+1;this.bitsPerSample=h,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}this.metadataWritten||this.writeVorbisCommentAndPictureBlock();const n=Me.tempFromBytes(t.data);n.skip(2);const a=K(n,2),o=new re(a),c=Dc(o.readBits(4));if(c===null)throw new Error("Invalid FLAC frame: Invalid block size.");zc(n);const u=Uc(n,c);this.format._options.appendOnly||(this.blockSizes.push(u),this.frameSizes.push(t.data.length));const l=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,l),await this.writer.flush()}finally{s()}}addSubtitleCue(){throw new Error("FLAC does not support subtitles.")}async finalize(){const e=await this.mutex.acquire();if(!this.format._options.appendOnly){let t=1/0,r=0,s=1/0,n=0,a=0;for(let o=0;o<this.blockSizes.length;o++)s=Math.min(s,this.frameSizes[o]),n=Math.max(n,this.frameSizes[o]),r=Math.max(r,this.blockSizes[o]),a+=this.blockSizes[o],o!==this.blockSizes.length-1&&(t=Math.min(t,this.blockSizes[o]));m(this.sampleRate!==null),m(this.channels!==null),m(this.bitsPerSample!==null),this.writer.seek(4),this.writeHeader({minimumBlockSize:t,maximumBlockSize:r,minimumFrameSize:s,maximumFrameSize:n,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:a})}e()}}/*!
|
|
313
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
314
|
+
*
|
|
315
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
316
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
317
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
318
|
+
*/const ci=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,Mh=/^WEBVTT(.|\n)*?\n{2}/,ls=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class Dh{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){e=e.replaceAll(`\r
|
|
319
|
+
`,`
|
|
320
|
+
`).replaceAll("\r",`
|
|
321
|
+
`),ci.lastIndex=0;let t;if(!this.preambleText){if(!Mh.test(e))throw new Error("WebVTT preamble incorrect.");t=ci.exec(e);const r=e.slice(0,(t==null?void 0:t.index)??e.length).trimEnd();if(!r)throw new Error("No WebVTT preamble provided.");this.preambleText=r,t&&(e=e.slice(t.index),ci.lastIndex=0)}for(;t=ci.exec(e);){const r=e.slice(0,t.index),s=t[1],n=t.index+t[0].length,a=e.indexOf(`
|
|
322
|
+
`,n)+1,o=e.slice(n,a).trim();let c=e.indexOf(`
|
|
323
|
+
|
|
324
|
+
`,n);c===-1&&(c=e.length);const u=Fn(t[2]),d=Fn(t[3])-u,h=e.slice(a,c).trim();e=e.slice(c).trimStart(),ci.lastIndex=0;const p={timestamp:u/1e3,duration:d/1e3,text:h,identifier:s,settings:o,notes:r},y={};this.preambleEmitted||(y.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(p,y)}}}const zh=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,Fn=i=>{const e=zh.exec(i);if(!e)throw new Error("Expected match.");return 3600*1e3*Number(e[1]||"0")+60*1e3*Number(e[2])+1e3*Number(e[3])+Number(e[4])},wl=i=>{const e=Math.floor(i/36e5),t=Math.floor(i%(3600*1e3)/(60*1e3)),r=Math.floor(i%(60*1e3)/1e3),s=i%1e3;return e.toString().padStart(2,"0")+":"+t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+s.toString().padStart(3,"0")};/*!
|
|
325
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
326
|
+
*
|
|
327
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
328
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
329
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
330
|
+
*/class Oi{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 n of e.children)n&&this.writeBox(n);const r=this.writer.getPos(),s=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,s),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 t=this.offsets.get(e);m(t!==void 0);const r=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(r)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(const r of e.children)r&&(t+=this.measureBox(r));return t}}}const te=new Uint8Array(8),Ze=new DataView(te.buffer),be=i=>[(i%256+256)%256],X=i=>(Ze.setUint16(0,i,!1),[te[0],te[1]]),da=i=>(Ze.setInt16(0,i,!1),[te[0],te[1]]),yl=i=>(Ze.setUint32(0,i,!1),[te[1],te[2],te[3]]),z=i=>(Ze.setUint32(0,i,!1),[te[0],te[1],te[2],te[3]]),St=i=>(Ze.setInt32(0,i,!1),[te[0],te[1],te[2],te[3]]),ht=i=>(Ze.setUint32(0,Math.floor(i/2**32),!1),Ze.setUint32(4,i,!1),[te[0],te[1],te[2],te[3],te[4],te[5],te[6],te[7]]),Uh=i=>(Ze.setInt32(0,Math.floor(i/2**32),!1),Ze.setUint32(4,i,!1),[te[0],te[1],te[2],te[3],te[4],te[5],te[6],te[7]]),bl=i=>(Ze.setInt16(0,2**8*i,!1),[te[0],te[1]]),et=i=>(Ze.setInt32(0,2**16*i,!1),[te[0],te[1],te[2],te[3]]),Gs=i=>(Ze.setInt32(0,2**30*i,!1),[te[0],te[1],te[2],te[3]]),Qs=(i,e)=>{const t=[];let r=i;do{let s=r&127;r>>=7,t.length>0&&(s|=128),t.push(s)}while(r>0||e);return t.reverse()},ce=(i,e=!1)=>{const t=Array(i.length).fill(null).map((r,s)=>i.charCodeAt(s));return e&&t.push(0),t},kl=i=>{const e=i*(Math.PI/180),t=Math.round(Math.cos(e)),r=Math.round(Math.sin(e));return[t,r,0,-r,t,0,0,0,1]},Tl=kl(0),Sl=i=>[et(i[0]),et(i[1]),Gs(i[2]),et(i[3]),et(i[4]),Gs(i[5]),et(i[6]),et(i[7]),Gs(i[8])],Q=(i,e,t)=>({type:i,contents:e&&new Uint8Array(e.flat(10)),children:t}),ae=(i,e,t,r,s)=>Q(i,[be(e),yl(t),r??[]],s),Nh=i=>i.isQuickTime?Q("ftyp",[ce("qt "),z(512),ce("qt ")]):i.fragmented?i.cmaf?Q("ftyp",[ce("iso5"),z(512),ce("iso5"),ce("iso6"),ce("mp41"),ce("cmfc"),ce("dash")]):Q("ftyp",[ce("iso5"),z(512),ce("iso5"),ce("iso6"),ce("mp41")]):Q("ftyp",[ce("isom"),z(512),ce("isom"),i.holdsAvc?ce("avc1"):[],ce("mp41")]),bo=()=>Q("styp",[ce("iso5"),z(0),ce("iso5"),ce("iso6"),ce("mp41"),ce("cmfc"),ce("dash")]),ko=(i,e)=>{let t=i.maxWrittenEndTimestamp-i.minWrittenTimestamp;return Number.isFinite(t)||(t=0),ae("sidx",1,0,[z(1),z(it),ht(pe(i.minWrittenTimestamp,it)),ht(0),X(0),X(1),z(e&2147483647),z(pe(t,it)),z(0)])},Wi=i=>({type:"mdat",largeSize:i}),Vh=i=>({type:"free",size:i}),li=i=>Q("moov",void 0,[Oh(i.creationTime,i.trackDatas),...i.trackDatas.map(e=>Wh(e,i.creationTime)),i.isFragmented?_f(i.trackDatas):null,Of(i)]),Oh=(i,e)=>{const t=Math.max(0,...e.map(a=>pe(Is(a),it)+pe(a.startTimestampOffset??0,it))),r=Math.max(0,...e.map(a=>a.track.id))+1,s=!Wt(i)||!Wt(t),n=s?ht:z;return ae("mvhd",+s,0,[n(i),n(i),z(it),n(t),et(1),bl(1),Array(10).fill(0),Sl(Tl),Array(24).fill(0),z(r)])},Is=i=>{if(i.samples.length===0)return 0;let e=1/0,t=-1/0;for(let r=0;r<i.samples.length;r++){const s=i.samples[r];s.timestamp<e&&(e=s.timestamp),s.timestamp+s.duration>t&&(t=s.timestamp+s.duration)}return e===1/0?0:t-e},Wh=(i,e)=>{const t=Jf(i),r=i.startTimestampOffset!==null&&i.startTimestampOffset>0;return Q("trak",void 0,[Lh(i,e),r?Hh(i,i.startTimestampOffset):null,qh(i,e),t.name!==void 0?Q("udta",void 0,[Q("name",[...le.encode(t.name)])]):null])},Lh=(i,e)=>{var o;const t=pe(Is(i),it)+pe(i.startTimestampOffset??0,it),r=!Wt(e)||!Wt(t),s=r?ht:z;let n;if(i.type==="video"){const c=i.track.metadata.rotation;n=kl(c??0)}else n=Tl;let a=2;return((o=i.track.metadata.disposition)==null?void 0:o.default)!==!1&&(a|=1),ae("tkhd",+r,a,[s(e),s(e),z(i.track.id),z(0),s(t),Array(8).fill(0),X(0),X(i.track.id),bl(i.type==="audio"?1:0),X(0),Sl(n),et(i.type==="video"?i.info.width:0),et(i.type==="video"?i.info.height:0)])},Hh=(i,e)=>{const t=pe(e,it),r=pe(Is(i),it),s=!Wt(t)||!Wt(r),n=s?ht:z,a=s?Uh:St;return Q("edts",void 0,[ae("elst",s?1:0,0,[z(2),n(t),a(-1),et(1),n(r),a(0),et(1)])])},qh=(i,e)=>Q("mdia",void 0,[jh(i,e),ha(!0,Kh[i.type],Gh[i.type]),Qh(i)]),jh=(i,e)=>{const t=pe(Is(i),i.timescale),r=!Wt(e)||!Wt(t),s=r?ht:z;return ae("mdhd",+r,0,[s(e),s(e),z(i.timescale),s(t),X(Cl(i.track.metadata.languageCode??ve)),X(0)])},Kh={video:"vide",audio:"soun",subtitle:"text"},Gh={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},ha=(i,e,t,r="\0\0\0\0")=>ae("hdlr",0,0,[i?ce("mhlr"):z(0),ce(e),ce(r),z(0),z(0),ce(t,!0)]),Qh=i=>Q("minf",void 0,[Zh[i.type](),Jh(),rf(i)]),Xh=()=>ae("vmhd",0,1,[X(0),X(0),X(0),X(0)]),$h=()=>ae("smhd",0,0,[X(0),X(0)]),Yh=()=>ae("nmhd",0,0),Zh={video:Xh,audio:$h,subtitle:Yh},Jh=()=>Q("dinf",void 0,[ef()]),ef=()=>ae("dref",0,0,[z(1)],[tf()]),tf=()=>ae("url ",0,1),rf=i=>{const e=i.compositionTimeOffsetTable.length>1||i.compositionTimeOffsetTable.some(t=>t.sampleCompositionTimeOffset!==0);return Q("stbl",void 0,[sf(i),kf(i),e?Pf(i):null,e?Cf(i):null,Sf(i),Af(i),xf(i),Tf(i)])},sf=i=>{let e;if(i.type==="video")e=nf(qf(i.track.source._codec,i.info.decoderConfig.codec),i);else if(i.type==="audio"){const t=Pl(i.track.source._codec,i.muxer.isQuickTime);m(t),e=df(t,i)}else i.type==="subtitle"&&(e=yf(Gf[i.track.source._codec],i));return m(e),ae("stsd",0,0,[z(1)],[e])},nf=(i,e)=>Q(i,[Array(6).fill(0),X(1),X(0),X(0),Array(12).fill(0),X(e.info.width),X(e.info.height),z(4718592),z(4718592),z(0),X(1),Array(32).fill(0),X(24),da(65535)],[jf[e.track.source._codec](e),af(e),Oo(e.info.decoderConfig.colorSpace)?of(e):null]),af=i=>i.info.pixelAspectRatio.num===i.info.pixelAspectRatio.den?null:Q("pasp",[z(i.info.pixelAspectRatio.num),z(i.info.pixelAspectRatio.den)]),of=i=>Q("colr",[ce("nclx"),X(ar[i.info.decoderConfig.colorSpace.primaries]),X(or[i.info.decoderConfig.colorSpace.transfer]),X(cr[i.info.decoderConfig.colorSpace.matrix]),be((i.info.decoderConfig.colorSpace.fullRange?1:0)<<7)]),cf=i=>i.info.decoderConfig&&Q("avcC",[...he(i.info.decoderConfig.description)]),lf=i=>i.info.decoderConfig&&Q("hvcC",[...he(i.info.decoderConfig.description)]),To=i=>{var h,p,y,f;if(!i.info.decoderConfig)return null;const e=i.info.decoderConfig,t=e.codec.split("."),r=Number(t[1]),s=Number(t[2]),n=Number(t[3]),a=t[4]?Number(t[4]):1,o=t[8]?Number(t[8]):Number(((h=e.colorSpace)==null?void 0:h.fullRange)??0),c=(n<<4)+(a<<1)+o,u=t[5]?Number(t[5]):(p=e.colorSpace)!=null&&p.primaries?ar[e.colorSpace.primaries]:2,l=t[6]?Number(t[6]):(y=e.colorSpace)!=null&&y.transfer?or[e.colorSpace.transfer]:2,d=t[7]?Number(t[7]):(f=e.colorSpace)!=null&&f.matrix?cr[e.colorSpace.matrix]:2;return ae("vpcC",1,0,[be(r),be(s),be(c),be(u),be(l),be(d),X(0)])},uf=i=>Q("av1C",$o(i.info.decoderConfig.codec)),df=(i,e)=>{var a;let t=0,r,s=16;const n=Pe.includes(e.track.source._codec);if(n){const o=e.track.source._codec,{sampleSize:c}=st(o);s=8*c,s>16&&(t=1)}if(e.muxer.isQuickTime&&(t=1),t===0)r=[Array(6).fill(0),X(1),X(t),X(0),z(0),X(e.info.numberOfChannels),X(s),X(0),X(0),X(e.info.sampleRate<2**16?e.info.sampleRate:0),X(0)];else{const o=n?0:-2;r=[Array(6).fill(0),X(1),X(t),X(0),z(0),X(e.info.numberOfChannels),X(Math.min(s,16)),da(o),X(0),X(e.info.sampleRate<2**16?e.info.sampleRate:0),X(0),n?[z(1),z(s/8),z(e.info.numberOfChannels*s/8)]:[z(0),z(0),z(0)],z(2)]}return Q(i,r,[((a=Kf(e.track.source._codec,e.muxer.isQuickTime))==null?void 0:a(e))??null])},Xs=i=>{let e;switch(i.track.source._codec){case"aac":e=64;break;case"mp3":e=107;break;case"vorbis":e=221;break;default:throw new Error(`Unhandled audio codec: ${i.track.source._codec}`)}let t=[...be(e),...be(21),...yl(0),...z(0),...z(0)];if(i.info.decoderConfig.description){const r=he(i.info.decoderConfig.description);t=[...t,...be(5),...Qs(r.byteLength),...r]}return t=[...X(1),...be(0),...be(4),...Qs(t.length),...t,...be(6),...be(1),...be(2)],t=[...be(3),...Qs(t.length),...t],ae("esds",0,0,t)},Ft=i=>Q("wave",void 0,[hf(i),ff(i),Q("\0\0\0\0")]),hf=i=>Q("frma",[ce(Pl(i.track.source._codec,i.muxer.isQuickTime))]),ff=i=>{const{littleEndian:e}=st(i.track.source._codec);return Q("enda",[X(+e)])},mf=i=>{var c;let e=i.info.numberOfChannels,t=3840,r=i.info.sampleRate,s=0,n=0,a=new Uint8Array(0);const o=(c=i.info.decoderConfig)==null?void 0:c.description;if(o){m(o.byteLength>=18);const u=he(o),l=ks(u);e=l.outputChannelCount,t=l.preSkip,r=l.inputSampleRate,s=l.outputGain,n=l.channelMappingFamily,l.channelMappingTable&&(a=l.channelMappingTable)}return Q("dOps",[be(0),be(e),X(t),z(r),da(s),be(n),...a])},pf=i=>{var r;const e=(r=i.info.decoderConfig)==null?void 0:r.description;m(e);const t=he(e);return ae("dfLa",0,0,[...t.subarray(4)])},ct=i=>{const{littleEndian:e,sampleSize:t}=st(i.track.source._codec),r=+e;return ae("pcmC",0,0,[be(r),be(8*t)])},gf=i=>{const e=lc(i.info.firstPacket.data);if(!e)throw new Error("Couldn't extract AC-3 frame info from the audio packet. Ensure the packets contain valid AC-3 sync frames (as specified in ETSI TS 102 366).");const t=new Uint8Array(3),r=new re(t);return r.writeBits(2,e.fscod),r.writeBits(5,e.bsid),r.writeBits(3,e.bsmod),r.writeBits(3,e.acmod),r.writeBits(1,e.lfeon),r.writeBits(5,e.bitRateCode),r.writeBits(5,0),Q("dac3",[...t])},wf=i=>{const e=dc(i.info.firstPacket.data);if(!e)throw new Error("Couldn't extract E-AC-3 frame info from the audio packet. Ensure the packets contain valid E-AC-3 sync frames (as specified in ETSI TS 102 366).");let t=16;for(const a of e.substreams)t+=23,a.numDepSub>0?t+=9:t+=1;const r=Math.ceil(t/8),s=new Uint8Array(r),n=new re(s);n.writeBits(13,e.dataRate),n.writeBits(3,e.substreams.length-1);for(const a of e.substreams)n.writeBits(2,a.fscod),n.writeBits(5,a.bsid),n.writeBits(1,0),n.writeBits(1,0),n.writeBits(3,a.bsmod),n.writeBits(3,a.acmod),n.writeBits(1,a.lfeon),n.writeBits(3,0),n.writeBits(4,a.numDepSub),a.numDepSub>0?n.writeBits(9,a.chanLoc):n.writeBits(1,0);return Q("dec3",[...s])},yf=(i,e)=>Q(i,[Array(6).fill(0),X(1)],[Qf[e.track.source._codec](e)]),bf=i=>Q("vttC",[...le.encode(i.info.config.description)]),kf=i=>ae("stts",0,0,[z(i.timeToSampleTable.length),i.timeToSampleTable.map(e=>[z(e.sampleCount),z(e.sampleDelta)])]),Tf=i=>{if(i.samples.every(t=>t.type==="key"))return null;const e=[...i.samples.entries()].filter(([,t])=>t.type==="key");return ae("stss",0,0,[z(e.length),e.map(([t])=>z(t+1))])},Sf=i=>ae("stsc",0,0,[z(i.compactlyCodedChunkTable.length),i.compactlyCodedChunkTable.map(e=>[z(e.firstChunk),z(e.samplesPerChunk),z(1)])]),Af=i=>{if(i.type==="audio"&&i.info.requiresPcmTransformation){const{sampleSize:e}=st(i.track.source._codec);return ae("stsz",0,0,[z(e*i.info.numberOfChannels),z(i.samples.reduce((t,r)=>t+pe(r.duration,i.timescale),0))])}return ae("stsz",0,0,[z(0),z(i.samples.length),i.samples.map(e=>z(e.size))])},xf=i=>i.finalizedChunks.length>0&&we(i.finalizedChunks).offset>=2**32?ae("co64",0,0,[z(i.finalizedChunks.length),i.finalizedChunks.map(e=>ht(e.offset))]):ae("stco",0,0,[z(i.finalizedChunks.length),i.finalizedChunks.map(e=>z(e.offset))]),Pf=i=>ae("ctts",1,0,[z(i.compositionTimeOffsetTable.length),i.compositionTimeOffsetTable.map(e=>[z(e.sampleCount),St(e.sampleCompositionTimeOffset)])]),Cf=i=>{let e=1/0,t=-1/0,r=1/0,s=-1/0;m(i.compositionTimeOffsetTable.length>0),m(i.samples.length>0);for(let a=0;a<i.compositionTimeOffsetTable.length;a++){const o=i.compositionTimeOffsetTable[a];e=Math.min(e,o.sampleCompositionTimeOffset),t=Math.max(t,o.sampleCompositionTimeOffset)}for(let a=0;a<i.samples.length;a++){const o=i.samples[a];r=Math.min(r,pe(o.timestamp,i.timescale)),s=Math.max(s,pe(o.timestamp+o.duration,i.timescale))}const n=Math.max(-e,0);return s>=2**31?null:ae("cslg",0,0,[St(n),St(e),St(t),St(r),St(s)])},_f=i=>Q("mvex",void 0,i.map(If)),If=i=>ae("trex",0,0,[z(i.track.id),z(1),z(0),z(0),z(0)]),So=(i,e)=>Q("moof",void 0,[Ef(i),...e.map(vf)]),Ef=i=>ae("mfhd",0,0,[z(i)]),Al=i=>{let e=0,t=0;const r=0,s=0,n=i.type==="delta";return t|=+n,n?e|=1:e|=2,e<<24|t<<16|r<<8|s},vf=i=>Q("traf",void 0,[Bf(i),Ff(i),Rf(i)]),Bf=i=>{m(i.currentChunk);let e=0;e|=8,e|=16,e|=32,e|=131072;const t=i.currentChunk.samples[1]??i.currentChunk.samples[0],r={duration:t.timescaleUnitsToNextSample,size:t.size,flags:Al(t)};return ae("tfhd",0,e,[z(i.track.id),z(r.duration),z(r.size),z(r.flags)])},Ff=i=>(m(i.currentChunk),ae("tfdt",1,0,[ht(pe(i.currentChunk.startTimestamp,i.timescale))])),Rf=i=>{m(i.currentChunk);const e=i.currentChunk.samples.map(f=>f.timescaleUnitsToNextSample),t=i.currentChunk.samples.map(f=>f.size),r=i.currentChunk.samples.map(Al),s=i.currentChunk.samples.map(f=>pe(f.timestamp-f.decodeTimestamp,i.timescale)),n=new Set(e),a=new Set(t),o=new Set(r),c=new Set(s),u=o.size===2&&r[0]!==r[1],l=n.size>1,d=a.size>1,h=!u&&o.size>1,p=c.size>1||[...c].some(f=>f!==0);let y=0;return y|=1,y|=4*+u,y|=256*+l,y|=512*+d,y|=1024*+h,y|=2048*+p,ae("trun",1,y,[z(i.currentChunk.samples.length),z(i.currentChunk.offset-i.currentChunk.moofOffset||0),u?z(r[0]):[],i.currentChunk.samples.map((f,w)=>[l?z(e[w]):[],d?z(t[w]):[],h?z(r[w]):[],p?St(s[w]):[]])])},Mf=i=>Q("mfra",void 0,[...i.map(Df),zf()]),Df=(i,e)=>ae("tfra",1,0,[z(i.track.id),z(63),z(i.finalizedChunks.length),i.finalizedChunks.map(r=>[ht(pe(r.samples[0].timestamp,i.timescale)),ht(r.moofOffset),z(e+1),z(1),z(1)])]),zf=()=>ae("mfro",0,0,[z(0)]),Uf=()=>Q("vtte"),Nf=(i,e,t,r,s)=>Q("vttc",void 0,[s!==null?Q("vsid",[St(s)]):null,t!==null?Q("iden",[...le.encode(t)]):null,e!==null?Q("ctim",[...le.encode(wl(e))]):null,r!==null?Q("sttg",[...le.encode(r)]):null,Q("payl",[...le.encode(i)])]),Vf=i=>Q("vtta",[...le.encode(i)]),Of=i=>{const e=[],t=i.format._options.metadataFormat??"auto",r=i.output._metadataTags;if(t==="mdir"||t==="auto"&&!i.isQuickTime){const s=Lf(r);s&&e.push(s)}else if(t==="mdta"){const s=Hf(r);s&&e.push(s)}else(t==="udta"||t==="auto"&&i.isQuickTime)&&Wf(e,i.output._metadataTags);return e.length===0?null:Q("udta",void 0,e)},Wf=(i,e)=>{for(const{key:t,value:r}of Rr(e))switch(t){case"title":i.push(lt("©nam",r));break;case"description":i.push(lt("©des",r));break;case"artist":i.push(lt("©ART",r));break;case"album":i.push(lt("©alb",r));break;case"albumArtist":i.push(lt("albr",r));break;case"genre":i.push(lt("©gen",r));break;case"date":i.push(lt("©day",r.toISOString().slice(0,10)));break;case"comment":i.push(lt("©cmt",r));break;case"lyrics":i.push(lt("©lyr",r));break;case"raw":break;case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:De(t)}if(e.raw)for(const t in e.raw){const r=e.raw[t];r==null||t.length!==4||i.some(s=>s.type===t)||(typeof r=="string"?i.push(lt(t,r)):r instanceof Uint8Array&&i.push(Q(t,Array.from(r))))}},lt=(i,e)=>{const t=le.encode(e);return Q(i,[X(t.length),X(Cl("und")),Array.from(t)])},Ao={"image/jpeg":13,"image/png":14,"image/bmp":27},xl=(i,e)=>{const t=[];for(const{key:r,value:s}of Rr(i))switch(r){case"title":t.push({key:e?"title":"©nam",value:Je(s)});break;case"description":t.push({key:e?"description":"©des",value:Je(s)});break;case"artist":t.push({key:e?"artist":"©ART",value:Je(s)});break;case"album":t.push({key:e?"album":"©alb",value:Je(s)});break;case"albumArtist":t.push({key:e?"album_artist":"aART",value:Je(s)});break;case"comment":t.push({key:e?"comment":"©cmt",value:Je(s)});break;case"genre":t.push({key:e?"genre":"©gen",value:Je(s)});break;case"lyrics":t.push({key:e?"lyrics":"©lyr",value:Je(s)});break;case"date":t.push({key:e?"date":"©day",value:Je(s.toISOString().slice(0,10))});break;case"images":for(const n of s)n.kind==="coverFront"&&t.push({key:"covr",value:Q("data",[z(Ao[n.mimeType]??0),z(0),Array.from(n.data)])});break;case"trackNumber":if(e){const n=i.tracksTotal!==void 0?`${s}/${i.tracksTotal}`:s.toString();t.push({key:"track",value:Je(n)})}else t.push({key:"trkn",value:Q("data",[z(0),z(0),X(0),X(s),X(i.tracksTotal??0),X(0)])});break;case"discNumber":e||t.push({key:"disc",value:Q("data",[z(0),z(0),X(0),X(s),X(i.discsTotal??0),X(0)])});break;case"tracksTotal":case"discsTotal":break;case"raw":break;default:De(r)}if(i.raw)for(const r in i.raw){const s=i.raw[r];s==null||!e&&r.length!==4||t.some(n=>n.key===r)||(typeof s=="string"?t.push({key:r,value:Je(s)}):s instanceof Uint8Array?t.push({key:r,value:Q("data",[z(0),z(0),Array.from(s)])}):s instanceof Cr&&t.push({key:r,value:Q("data",[z(Ao[s.mimeType]??0),z(0),Array.from(s.data)])}))}return t},Lf=i=>{const e=xl(i,!1);return e.length===0?null:ae("meta",0,0,void 0,[ha(!1,"mdir","","appl"),Q("ilst",void 0,e.map(t=>Q(t.key,void 0,[t.value])))])},Hf=i=>{const e=xl(i,!0);return e.length===0?null:Q("meta",void 0,[ha(!1,"mdta",""),ae("keys",0,0,[z(e.length)],e.map(t=>Q("mdta",[...le.encode(t.key)]))),Q("ilst",void 0,e.map((t,r)=>{const s=String.fromCharCode(...z(r+1));return Q(s,void 0,[t.value])}))])},Je=i=>Q("data",[z(1),z(0),...le.encode(i)]),qf=(i,e)=>{switch(i){case"avc":return e.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01"}},jf={avc:cf,hevc:lf,vp8:To,vp9:To,av1:uf},Pl=(i,e)=>{switch(i){case"aac":return"mp4a";case"mp3":return"mp4a";case"opus":return"Opus";case"vorbis":return"mp4a";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(e)switch(i){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":return"in24";case"pcm-s24be":return"in24";case"pcm-s32":return"in32";case"pcm-s32be":return"in32";case"pcm-f32":return"fl32";case"pcm-f32be":return"fl32";case"pcm-f64":return"fl64";case"pcm-f64be":return"fl64"}else switch(i){case"pcm-s16":return"ipcm";case"pcm-s16be":return"ipcm";case"pcm-s24":return"ipcm";case"pcm-s24be":return"ipcm";case"pcm-s32":return"ipcm";case"pcm-s32be":return"ipcm";case"pcm-f32":return"fpcm";case"pcm-f32be":return"fpcm";case"pcm-f64":return"fpcm";case"pcm-f64be":return"fpcm"}},Kf=(i,e)=>{switch(i){case"aac":return Xs;case"mp3":return Xs;case"opus":return mf;case"vorbis":return Xs;case"flac":return pf;case"ac3":return gf;case"eac3":return wf}if(e)switch(i){case"pcm-s24":return Ft;case"pcm-s24be":return Ft;case"pcm-s32":return Ft;case"pcm-s32be":return Ft;case"pcm-f32":return Ft;case"pcm-f32be":return Ft;case"pcm-f64":return Ft;case"pcm-f64be":return Ft}else switch(i){case"pcm-s16":return ct;case"pcm-s16be":return ct;case"pcm-s24":return ct;case"pcm-s24be":return ct;case"pcm-s32":return ct;case"pcm-s32be":return ct;case"pcm-f32":return ct;case"pcm-f32be":return ct;case"pcm-f64":return ct;case"pcm-f64be":return ct}return null},Gf={webvtt:"wvtt"},Qf={webvtt:bf},Cl=i=>{m(i.length===3);let e=0;for(let t=0;t<3;t++)e<<=5,e+=i.charCodeAt(t)-96;return e};/*!
|
|
331
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
332
|
+
*
|
|
333
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
334
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
335
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
336
|
+
*/class Ei{constructor(e,t){if(this.finalized=!1,this.started=!1,this.pos=0,this.trackedWrites=null,this.trackedStart=-1,this.trackedEnd=-1,e._writerAcquired)throw new Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){m(!this.started),this.target._start(),this.started=!0}write(e){m(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return m(this.started&&!this.finalized),this.target._flush()}async finalize(){m(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}const r=t+e.byteLength-this.trackedStart;let s=this.trackedWrites.byteLength;for(;s<r;)s*=2;if(s!==this.trackedWrites.byteLength){const n=new Uint8Array(s);n.set(this.trackedWrites,0),this.trackedWrites=n}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(2**10),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw new Error("Internal error: Can't get tracked writes since nothing was tracked.");const t={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,t}}/*!
|
|
337
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
338
|
+
*
|
|
339
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
340
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
341
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
342
|
+
*/const xo=typeof ns<"u"?ns:void 0;class Le extends fs{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){this._monotonicity!==!1&&(this._monotonicity=e)}_dispatchWrite(e,t){var r;(r=this.onwrite)==null||r.call(this,e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");return new Yf(this,e)}}const $s=2**16,Ys=2**32;class Zs extends Le{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||typeof e!="object")throw new TypeError("BufferTarget options, when provided, must be an object.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");if(this._options=e,this._supportsResize="resize"in new ArrayBuffer(0),this._supportsResize)try{this._buffer=new ArrayBuffer($s,{maxByteLength:Ys})}catch{this._buffer=new ArrayBuffer($s),this._supportsResize=!1}else this._buffer=new ArrayBuffer($s);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>Ys)throw new Error(`ArrayBuffer exceeded maximum size of ${Ys} bytes. Please consider using another target.`);if(this._supportsResize)this._buffer.resize(t);else{const r=new ArrayBuffer(t),s=new Uint8Array(r);s.set(this._bytes,0),this._buffer=r,this._bytes=s}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}}const Xf=2**24,$f=2;class _l extends Le{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw new TypeError("StreamTarget requires a WritableStream instance.");if(t!=null&&typeof t!="object")throw new TypeError("StreamTarget options, when provided, must be an object.");if(t.chunked!==void 0&&typeof t.chunked!="boolean")throw new TypeError("options.chunked, when provided, must be a boolean.");if(t.chunkSize!==void 0&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw new TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??Xf}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){const r=t-this._lastWriteEnd;this._write(new Uint8Array(r),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(this._writeError!==null)throw this._writeError;if(m(this._streamWriter),this._sections.length===0)return;const e=[],t=[...this._sections].sort((r,s)=>r.start-s.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let r=1;r<t.length;r++){const s=e[e.length-1],n=t[r];n.start<=s.start+s.size?s.size=Math.max(s.size,n.start+n.data.byteLength-s.start):e.push({start:n.start,size:n.data.byteLength})}for(const r of e){r.data=new Uint8Array(r.size);for(const s of this._sections)r.start<=s.start&&s.start<r.start+r.size&&r.data.set(s.data,s.start-r.start);if(this._streamWriter.desiredSize!==null&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(r.data,r.start),this._tryToFlushChunks();else{if(this._monotonicity===!0&&r.start!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:r.data,position:r.start}).catch(s=>{this._writeError??(this._writeError=s)}),this._lastFlushEnd=r.start+r.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let r=this._chunks.findIndex(c=>c.start<=t&&t<c.start+this._chunkSize);r===-1&&(r=this._createChunk(t));const s=this._chunks[r],n=t-s.start,a=e.subarray(0,Math.min(this._chunkSize-n,e.byteLength));s.data.set(a,n);const o={start:n,end:n+a.byteLength};if(this._insertSectionIntoChunk(s,o),s.written[0].start===0&&s.written[0].end===this._chunkSize&&(s.shouldFlush=!0),this._chunks.length>$f){for(let c=0;c<this._chunks.length-1;c++)this._chunks[c].shouldFlush=!0;this._tryToFlushChunks()}a.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(a.byteLength),t+a.byteLength)}_insertSectionIntoChunk(e,t){let r=0,s=e.written.length-1,n=-1;for(;r<=s;){const a=Math.floor(r+(s-r+1)/2);e.written[a].start<=t.start?(r=a+1,n=a):s=a-1}for(e.written.splice(n+1,0,t),(n===-1||e.written[n].end<t.start)&&n++;n<e.written.length-1&&e.written[n].end>=e.written[n+1].start;)e.written[n].end=Math.max(e.written[n].end,e.written[n+1].end),e.written.splice(n+1,1)}_createChunk(e){const r={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(r),this._chunks.sort((s,n)=>s.start-n.start),this._chunks.indexOf(r)}_tryToFlushChunks(e=!1){m(this._streamWriter);for(let t=0;t<this._chunks.length;t++){const r=this._chunks[t];if(!(!r.shouldFlush&&!e)){for(const s of r.written){const n=r.start+s.start;if(this._monotonicity===!0&&n!==this._lastFlushEnd)throw new Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:r.data.subarray(s.start,s.end),position:n}).catch(a=>{this._writeError??(this._writeError=a)}),this._lastFlushEnd=r.start+s.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),this._writeError!==null)throw this._writeError;m(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){var e;return(e=this._streamWriter)==null?void 0:e.close()}}class Ym extends Le{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new _l(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:t=>{if(this._monotonicity!==!0)throw new Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return m(t.position===this._nextWritePos),this._nextWritePos+=t.data.byteLength,m(this._writer),this._writer.write(t.data)},close:()=>{var t;return(t=this._writer)==null?void 0:t.close()}}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class Zm extends Le{constructor(e,t={}){if(typeof e!="string")throw new TypeError("filePath must be a string.");if(!t||typeof t!="object")throw new TypeError("options must be an object.");if(!xo.fs)throw new Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super(),this._fileHandle=null;const r=new WritableStream({start:async()=>{this._fileHandle=await xo.fs.open(e,"w")},write:async s=>{m(this._fileHandle),await this._fileHandle.write(s.data,0,s.data.byteLength,s.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new _l(r,{chunked:!0,...t})}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class Il extends Le{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class Yf extends Le{constructor(e,t){super(),this._baseTarget=e,this._offset=t}_start(){}_write(e,t){this._baseTarget._write(e,this._offset+t),this._dispatchWrite(t,t+e.byteLength)}_flush(){return this._baseTarget._flush()}async _finalize(){this._emit("finalized")}async _close(){}_setMonotonicity(e){super._setMonotonicity(e),this._baseTarget._setMonotonicity(e)}}class zt{constructor(e,t){if(this.rootPath=e,this.getTarget=t,typeof e!="string")throw new TypeError("rootPath must be a string.");if(typeof t!="function")throw new TypeError("getTarget must be a function.")}}/*!
|
|
343
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
344
|
+
*
|
|
345
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
346
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
347
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
348
|
+
*/const it=57600,Zf=2082844800,Jf=i=>{const e={},t=i.track;return t.metadata.name!==void 0&&(e.name=t.metadata.name),e},pe=(i,e,t=!0)=>{const r=i*e;return t?Math.round(r):r};class em extends Bt{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new Zs,this.auxWriter=new Ei(this.auxTarget,!1),this.auxBoxWriter=new Oi(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=ge(),this.creationTime=Math.floor(Date.now()/1e3)+Zf,this.finalizedChunks=[],this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.isQuickTime=t instanceof Ul,this.isCmaf=t instanceof zo,this.minimumFragmentDuration=t._options.minimumFragmentDuration??(t instanceof zo?1/0:1)}async start(){var r;const e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(s=>this.format._options.fastStart!==void 0?this.format._options.fastStart==="fragmented":s instanceof Zs),this.boxWriter=new Oi(this.writer),this.fastStart=this.format._options.fastStart??(this.writer.target instanceof Zs?"in-memory":!1),this.isFragmented=this.fastStart==="fragmented"),this.isCmaf){if(!this.output._hasInitTarget())throw new Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");const s=await this.output._getInitTarget(),n=new Ei(s,!0);n.start(),this.initWriter=n,this.initBoxWriter=new Oi(n)}const t=this.output._tracks.some(s=>s.isVideoTrack()&&s.source._codec==="avc");{const s=this.initBoxWriter??this.boxWriter;if(m(s),this.format._options.onFtyp&&s.writer.startTrackingWrites(),s.writeBox(Nh({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.format._options.onFtyp){const{data:n,start:a}=s.writer.stopTrackingWrites();this.format._options.onFtyp(n,a)}this.ftypSize=s.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if(this.fastStart!=="in-memory")if(this.fastStart==="reserve"){for(const s of this.output._tracks)if(s.metadata.maximumPacketCount===void 0)throw new Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(m(this.writer),m(this.boxWriter),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Wi(!0),this.boxWriter.writeBox(this.mdat));await((r=this.writer)==null?void 0:r.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(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return mc({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,r){const s=this.trackDatas.find(h=>h.track===e);if(s)return s;ms(r),m(r),m(r.decoderConfig);const n={...r.decoderConfig};m(n.codedWidth!==void 0),m(n.codedHeight!==void 0);let a=!1;if(e.source._codec==="avc"&&!n.description){const h=Gn(t.data);if(!h)throw new Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");n.description=xu(h),a=!0}else if(e.source._codec==="hevc"&&!n.description){const h=Xn(t.data);if(!h)throw new Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");n.description=Fu(h),a=!0}const o=Jl(1/(e.metadata.frameRate??it),1e6).den,c=n.displayAspectWidth,u=n.displayAspectHeight,l=c===void 0||u===void 0?{num:1,den:1}:Ti({num:c*n.codedHeight,den:u*n.codedWidth}),d={muxer:this,track:e,type:"video",info:{width:n.codedWidth,height:n.codedHeight,pixelAspectRatio:l,decoderConfig:n,requiresAnnexBTransformation:a},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(d),this.trackDatas.sort((h,p)=>h.track.id-p.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),d}getAudioTrackData(e,t,r){const s=this.trackDatas.find(c=>c.track===e);if(s)return s;qt(r),m(r),m(r.decoderConfig);const n={...r.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!n.description){const c=_t(Me.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const u=Lt[c.samplingFrequencyIndex],l=Dr[c.channelConfiguration];if(u===void 0||l===void 0)throw new Error("Invalid ADTS frame header.");n.description=Wn({objectType:c.objectType,sampleRate:u,numberOfChannels:l}),a=!0}const o={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:n,requiresPcmTransformation:!this.isFragmented&&Pe.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:a,firstPacket:t},timescale:n.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,u)=>c.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const r=this.trackDatas.find(n=>n.track===e);if(r)return r;Jo(t),m(t),m(t.config);const s={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,r);let a=t.data;if(n.info.requiresAnnexBTransformation){const c=[...Ur(a)].map(u=>a.subarray(u.offset,u.offset+u.length));if(c.length===0)throw new Error("Failed to transform packet data. Make sure all packets are provided in Annex B format, as specified in ITU-T-REC-H.264 and ITU-T-REC-H.265.");a=Kn(c,4)}this.validateTimestamp(n.track,t.timestamp,t.type==="key");const o=this.createSampleForTrack(n,a,t.timestamp,t.duration,t.type);await this.registerSample(n,o)}finally{s()}}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,t,r);let a=t.data;if(n.info.requiresAdtsStripping){const l=_t(Me.tempFromBytes(a));if(!l)throw new Error("Expected ADTS frame, didn't get one.");const d=l.crcCheck===null?xi:Ot;a=a.subarray(d)}this.validateTimestamp(n.track,t.timestamp,t.type==="key");let o=t.timestamp,c=t.duration;if(n.info.requiresPcmTransformation){const d=st(n.info.decoderConfig.codec).sampleSize*n.info.numberOfChannels;if(c=a.byteLength/d/n.info.sampleRate,n.info.expectedNextPcmPacketTimestamp!==null){const h=o-n.info.expectedNextPcmPacketTimestamp;if(h<.01)o=n.info.expectedNextPcmPacketTimestamp;else{const p=await this.padWithSilence(n,n.info.expectedNextPcmPacketTimestamp,h);o=n.info.expectedNextPcmPacketTimestamp+p}}n.info.expectedNextPcmPacketTimestamp=o+c}const u=this.createSampleForTrack(n,a,o,c,t.type);await this.registerSample(n,u)}finally{s()}}async padWithSilence(e,t,r){const s=pe(r,e.timescale);if(r=s/e.timescale,s>0){const{sampleSize:n,silentValue:a}=st(e.info.decoderConfig.codec),o=s*e.info.numberOfChannels,c=new Uint8Array(n*o).fill(a),u=this.createSampleForTrack(e,new Uint8Array(c.buffer),t,r,"key");await this.registerSample(e,u)}return r}async addSubtitleCue(e,t,r){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,!0),e.source._codec==="webvtt"&&(n.cueQueue.push(t),await this.processWebVTTCues(n,t.timestamp))}finally{s()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){const r=new Set([]);for(const u of e.cueQueue)m(u.timestamp<=t),m(e.lastCueEndTimestamp<=u.timestamp+u.duration),r.add(Math.max(u.timestamp,e.lastCueEndTimestamp)),r.add(u.timestamp+u.duration);const s=[...r].sort((u,l)=>u-l),n=s[0],a=s[1]??n;if(t<a)break;if(e.lastCueEndTimestamp<n){this.auxWriter.seek(0);const u=Uf();this.auxBoxWriter.writeBox(u);const l=this.auxTarget._getSlice(0,this.auxWriter.getPos()),d=this.createSampleForTrack(e,l,e.lastCueEndTimestamp,n-e.lastCueEndTimestamp,"key");await this.registerSample(e,d),e.lastCueEndTimestamp=n}this.auxWriter.seek(0);for(let u=0;u<e.cueQueue.length;u++){const l=e.cueQueue[u];if(l.timestamp>=a)break;ls.lastIndex=0;const d=ls.test(l.text),h=l.timestamp+l.duration;let p=e.cueToSourceId.get(l);if(p===void 0&&a<h&&(p=e.nextSourceId++,e.cueToSourceId.set(l,p)),l.notes){const f=Vf(l.notes);this.auxBoxWriter.writeBox(f)}const y=Nf(l.text,d?n:null,l.identifier??null,l.settings??null,p??null);this.auxBoxWriter.writeBox(y),h===a&&e.cueQueue.splice(u--,1)}const o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),c=this.createSampleForTrack(e,o,n,a-n,"key");await this.registerSample(e,c),e.lastCueEndTimestamp=a}}createSampleForTrack(e,t,r,s,n){return{timestamp:r,decodeTimestamp:r,duration:s,data:t,size:t.byteLength,type:n,timescaleUnitsToNextSample:pe(s,e.timescale)}}processTimestamps(e,t){if(e.timestampProcessingQueue.length===0)return;if(e.type==="audio"&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??(e.startTimestampOffset=e.timestampProcessingQueue[0].timestamp));let s=0;for(let n=0;n<e.timestampProcessingQueue.length;n++){const a=e.timestampProcessingQueue[n],o=pe(a.duration,e.timescale);s+=o}if(e.timeToSampleTable.length===0)e.timeToSampleTable.push({sampleCount:s,sampleDelta:1});else{const n=we(e.timeToSampleTable);n.sampleCount+=s}e.timestampProcessingQueue.length=0;return}const r=e.timestampProcessingQueue.map(s=>s.timestamp).sort((s,n)=>s-n);this.isFragmented||(e.startTimestampOffset??(e.startTimestampOffset=r[0]));for(let s=0;s<e.timestampProcessingQueue.length;s++){const n=e.timestampProcessingQueue[s];n.decodeTimestamp=r[s];const a=pe(n.timestamp-n.decodeTimestamp,e.timescale),o=pe(n.duration,e.timescale);if(e.lastTimescaleUnits!==null){m(e.lastSample);const c=pe(n.decodeTimestamp,e.timescale,!1),u=Math.round(c-e.lastTimescaleUnits);if(m(u>=0),e.lastTimescaleUnits+=u,e.lastSample.timescaleUnitsToNextSample=u,!this.isFragmented){let l=we(e.timeToSampleTable);if(m(l),l.sampleCount===1){l.sampleDelta=u;const h=e.timeToSampleTable[e.timeToSampleTable.length-2];h&&h.sampleDelta===u&&(h.sampleCount++,e.timeToSampleTable.pop(),l=h)}else l.sampleDelta!==u&&(l.sampleCount--,e.timeToSampleTable.push(l={sampleCount:1,sampleDelta:u}));l.sampleDelta===o?l.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});const d=we(e.compositionTimeOffsetTable);m(d),d.sampleCompositionTimeOffset===a?d.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a})}}else e.lastTimescaleUnits=pe(n.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:a}));e.lastSample=n}if(e.timestampProcessingQueue.length=0,m(e.lastSample),m(e.lastTimescaleUnits!==null),t!==void 0&&e.lastSample.timescaleUnitsToNextSample===0){m(t.type==="key");const s=pe(t.timestamp,e.timescale,!1),n=Math.round(s-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=n}}async registerSample(e,t){t.type==="key"&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):this.fastStart==="reserve"?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),this.fastStart==="reserve")){const s=e.track.metadata.maximumPacketCount;if(m(s!==void 0),e.samples.length>s)throw new Error(`Track #${e.track.id} has already reached the maximum packet count (${s}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(!e.currentChunk)r=!0;else{e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);const s=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){const n=this.trackDatas.every(a=>{if(e===a)return t.type==="key";const o=a.sampleQueue[0];return o?o.type==="key":a.closed});s>=this.minimumFragmentDuration&&n&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=s>=.5}r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null}),m(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(m(!this.isFragmented),m(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if(e.type==="audio"&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((r,s)=>r+pe(s.duration,e.timescale),0)),(e.compactlyCodedChunkTable.length===0||we(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),this.fastStart==="in-memory"){e.currentChunk.offset=0;return}e.currentChunk.offset=this.writer.getPos();for(const r of e.currentChunk.samples)m(r.data),this.writer.write(r.data),r.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(m(this.isFragmented),!(!e&&!this.allTracksAreKnown()))e:for(;;){let t=null,r=1/0;for(const n of this.trackDatas){if(!e&&n.sampleQueue.length===0&&!n.closed)break e;n.sampleQueue.length>0&&n.sampleQueue[0].timestamp<r&&(t=n,r=n.sampleQueue[0].timestamp)}if(!t)break;const s=t.sampleQueue.shift();await this.addSampleToTrack(t,s)}}async finalizeFragment(e=!this.isCmaf){m(this.isFragmented);const t=this.nextFragmentNumber++;if(t===1){const p=this.initBoxWriter??this.boxWriter;m(p),this.format._options.onMoov&&p.writer.startTrackingWrites();const y=li(this);if(p.writeBox(y),this.format._options.onMoov){const{data:f,start:w}=p.writer.stopTrackingWrites();this.format._options.onMoov(f,w)}if(this.isCmaf){m(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new Oi(this.writer);const f=this.boxWriter.measureBox(bo()),w=this.boxWriter.measureBox(ko(this,0));this.segmentHeaderSize=f+w,this.writer.seek(this.segmentHeaderSize)}}m(this.writer),m(this.boxWriter);const r=this.trackDatas.filter(p=>p.currentChunk),s=So(t,r),n=this.writer.getPos(),a=n+this.boxWriter.measureBox(s);let o=a+kt,c=1/0;for(const p of r){p.currentChunk.offset=o,p.currentChunk.moofOffset=n;for(const y of p.currentChunk.samples)o+=y.size;c=Math.min(c,p.currentChunk.startTimestamp)}const u=o-a,l=u>=2**32;if(l)for(const p of r)p.currentChunk.offset+=Jt-kt;this.format._options.onMoof&&this.writer.startTrackingWrites();const d=So(t,r);if(this.boxWriter.writeBox(d),this.format._options.onMoof){const{data:p,start:y}=this.writer.stopTrackingWrites();this.format._options.onMoof(p,y,c)}m(this.writer.getPos()===a),this.format._options.onMdat&&this.writer.startTrackingWrites();const h=Wi(l);h.size=u,this.boxWriter.writeBox(h),this.writer.seek(a+(l?Jt:kt));for(const p of r)for(const y of p.currentChunk.samples)this.writer.write(y.data),y.data=null;if(this.format._options.onMdat){const{data:p,start:y}=this.writer.stopTrackingWrites();this.format._options.onMdat(p,y)}for(const p of r)p.finalizedChunks.push(p.currentChunk),this.finalizedChunks.push(p.currentChunk),p.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){if(m(this.writer),m(this.boxWriter),this.allTracksAreKnown()){if(!this.mdat){const r=li(this),n=this.boxWriter.measureBox(r)+this.computeSampleTableSizeUpperBound()+4096;m(this.ftypSize!==null),this.writer.seek(this.ftypSize+n),this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat=Wi(!0),this.boxWriter.writeBox(this.mdat);for(const a of this.trackDatas){for(const o of a.sampleQueue)await this.addSampleToTrack(a,o);a.sampleQueue.length=0}}await this.addSampleToTrack(e,t)}else e.sampleQueue.push(t)}computeSampleTableSizeUpperBound(){m(this.fastStart==="reserve");let e=0;for(const t of this.trackDatas){const r=t.track.metadata.maximumPacketCount;m(r!==void 0),e+=8*Math.ceil(2/3*r),e+=4*r,e+=8*Math.ceil(2/3*r),e+=12*Math.ceil(2/3*r),e+=4*r,e+=8*r}return e}async onTrackClose(e){const t=await this.mutex.acquire(),r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0,r.type==="subtitle"&&e.source._codec==="webvtt"&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0,t.type==="subtitle"&&t.track.source._codec==="webvtt"&&await this.processWebVTTCues(t,1/0),this.processTimestamps(t);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(const t of this.trackDatas){await this.finalizeCurrentChunk(t),m(t.startTimestampOffset!==null);for(let r=0;r<t.samples.length;r++){const s=t.samples[r];s.timestamp-=t.startTimestampOffset,s.decodeTimestamp-=t.startTimestampOffset}}if(m(this.writer),m(this.boxWriter),this.fastStart==="in-memory"){this.mdat=Wi(!1);let t;for(let s=0;s<2;s++){const n=li(this),a=this.boxWriter.measureBox(n);t=this.boxWriter.measureBox(this.mdat);let o=this.writer.getPos()+a+t;for(const c of this.finalizedChunks){c.offset=o;for(const{data:u}of c.samples)m(u),o+=u.byteLength,t+=u.byteLength}if(o<2**32)break;t>=2**32&&(this.mdat.largeSize=!0)}this.format._options.onMoov&&this.writer.startTrackingWrites();const r=li(this);if(this.boxWriter.writeBox(r),this.format._options.onMoov){const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMoov(s,n)}this.format._options.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=t,this.boxWriter.writeBox(this.mdat);for(const s of this.finalizedChunks)for(const n of s.samples)m(n.data),this.writer.write(n.data),n.data=null;if(this.format._options.onMdat){const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onMdat(s,n)}}else if(this.isFragmented)if(this.isCmaf){const t=this.segmentHeaderSize!==null?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(bo()),this.boxWriter.writeBox(ko(this,t))}else{const t=this.writer.getPos(),r=Mf(this.trackDatas);this.boxWriter.writeBox(r);const s=this.writer.getPos()-t;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(s)}else{m(this.mdat);const t=this.boxWriter.offsets.get(this.mdat);m(t!==void 0);const r=this.writer.getPos()-t;if(this.mdat.size=r,this.mdat.largeSize=r>=2**32,this.boxWriter.patchBox(this.mdat),this.format._options.onMdat){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMdat(n,a)}const s=li(this);if(this.fastStart==="reserve"){m(this.ftypSize!==null),this.writer.seek(this.ftypSize),this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);const n=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(Vh(n))}else this.format._options.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(s);if(this.format._options.onMoov){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onMoov(n,a)}}e()}}/*!
|
|
349
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
350
|
+
*
|
|
351
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
352
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
353
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
354
|
+
*/const tm=-32768,rm=2**15-1,Po="Mediabunny",Co=6,_o=5,im={video:1,audio:2,subtitle:17};class sm extends Bt{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=ge(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMaxMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new Yu(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),await this.writer.flush(),e()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();const e={id:x.EBML,data:[{id:x.EBMLVersion,data:1},{id:x.EBMLReadVersion,data:1},{id:x.EBMLMaxIDLength,data:4},{id:x.EBMLMaxSizeLength,data:8},{id:x.DocType,data:this.format instanceof No?"webm":"matroska"},{id:x.DocTypeVersion,data:2},{id:x.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){const{data:t,start:r}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(t,r)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;const t=new Uint8Array([28,83,187,107]),r=new Uint8Array([21,73,169,102]),s=new Uint8Array([22,84,174,107]),n=new Uint8Array([25,65,164,105]),a=new Uint8Array([18,84,195,103]),o={id:x.SeekHead,data:[{id:x.Seek,data:[{id:x.SeekID,data:t},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:x.Seek,data:[{id:x.SeekID,data:r},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:x.Seek,data:[{id:x.SeekID,data:s},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:x.Seek,data:[{id:x.SeekID,data:n},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:x.Seek,data:[{id:x.SeekID,data:a},{id:x.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=o}createSegmentInfo(){const e={id:x.Duration,data:new gn(0)};this.segmentDuration=e;const t={id:x.Info,data:[{id:x.TimestampScale,data:1e6},{id:x.MuxingApp,data:Po},{id:x.WritingApp,data:Po},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){var t,r,s,n,a,o;const e={id:x.Tracks,data:[]};this.tracksElement=e;for(const c of this.trackDatas){const u=Ve[c.track.source._codec];m(u);let l=0;if(c.type==="audio"&&c.track.source._codec==="opus"){l=1e6*80;const d=c.info.decoderConfig.description;if(d){const h=he(d),p=ks(h);l=Math.round(1e9*(p.preSkip/zr))}}e.data.push({id:x.TrackEntry,data:[{id:x.TrackNumber,data:c.track.id},{id:x.TrackUID,data:c.track.id},{id:x.TrackType,data:im[c.type]},((t=c.track.metadata.disposition)==null?void 0:t.default)===!1?{id:x.FlagDefault,data:0}:null,(r=c.track.metadata.disposition)!=null&&r.forced?{id:x.FlagForced,data:1}:null,(s=c.track.metadata.disposition)!=null&&s.hearingImpaired?{id:x.FlagHearingImpaired,data:1}:null,(n=c.track.metadata.disposition)!=null&&n.visuallyImpaired?{id:x.FlagVisualImpaired,data:1}:null,(a=c.track.metadata.disposition)!=null&&a.original?{id:x.FlagOriginal,data:1}:null,(o=c.track.metadata.disposition)!=null&&o.commentary?{id:x.FlagCommentary,data:1}:null,{id:x.FlagLacing,data:0},{id:x.Language,data:c.track.metadata.languageCode??ve},{id:x.CodecID,data:u},{id:x.CodecDelay,data:0},{id:x.SeekPreRoll,data:l},c.track.metadata.name!==void 0?{id:x.Name,data:new Rt(c.track.metadata.name)}:null,c.type==="video"?this.videoSpecificTrackInfo(c):null,c.type==="audio"?this.audioSpecificTrackInfo(c):null,c.type==="subtitle"?this.subtitleSpecificTrackInfo(c):null]})}}videoSpecificTrackInfo(e){const{frameRate:t,rotation:r}=e.track.metadata,s=[e.info.decoderConfig.description?{id:x.CodecPrivate,data:he(e.info.decoderConfig.description)}:null,t?{id:x.DefaultDuration,data:1e9/t}:null],n=r?Er(-r):0,a=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!==e.info.aspectRatio.den*e.info.width,o=e.info.decoderConfig.colorSpace,c={id:x.Video,data:[{id:x.PixelWidth,data:e.info.width},{id:x.PixelHeight,data:e.info.height},a?{id:x.DisplayWidth,data:e.info.aspectRatio.num}:null,a?{id:x.DisplayHeight,data:e.info.aspectRatio.den}:null,a?{id:x.DisplayUnit,data:3}:null,e.info.alphaMode?{id:x.AlphaMode,data:1}:null,Oo(o)?{id:x.Colour,data:[{id:x.MatrixCoefficients,data:cr[o.matrix]},{id:x.TransferCharacteristics,data:or[o.transfer]},{id:x.Primaries,data:ar[o.primaries]},{id:x.Range,data:o.fullRange?2:1}]}:null,n?{id:x.Projection,data:[{id:x.ProjectionType,data:0},{id:x.ProjectionPoseRoll,data:new pn((n+180)%360-180)}]}:null]};return s.push(c),s}audioSpecificTrackInfo(e){const t=Pe.includes(e.track.source._codec)?st(e.track.source._codec):null;return[e.info.decoderConfig.description?{id:x.CodecPrivate,data:he(e.info.decoderConfig.description)}:null,{id:x.Audio,data:[{id:x.SamplingFrequency,data:new pn(e.info.sampleRate)},{id:x.Channels,data:e.info.numberOfChannels},t?{id:x.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[{id:x.CodecPrivate,data:le.encode(e.info.config.description)}]}maybeCreateTags(){const e=[],t=(n,a)=>{e.push({id:x.SimpleTag,data:[{id:x.TagName,data:new Rt(n)},typeof a=="string"?{id:x.TagString,data:new Rt(a)}:{id:x.TagBinary,data:a}]})},r=this.output._metadataTags,s=new Set;for(const{key:n,value:a}of Rr(r))switch(n){case"title":t("TITLE",a),s.add("TITLE");break;case"description":t("DESCRIPTION",a),s.add("DESCRIPTION");break;case"artist":t("ARTIST",a),s.add("ARTIST");break;case"album":t("ALBUM",a),s.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),s.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),s.add("GENRE");break;case"comment":t("COMMENT",a),s.add("COMMENT");break;case"lyrics":t("LYRICS",a),s.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),s.add("DATE");break;case"trackNumber":{const o=r.tracksTotal!==void 0?`${a}/${r.tracksTotal}`:a.toString();t("PART_NUMBER",o),s.add("PART_NUMBER")}break;case"discNumber":{const o=r.discsTotal!==void 0?`${a}/${r.discsTotal}`:a.toString();t("DISC",o),s.add("DISC")}break;case"tracksTotal":case"discsTotal":break;case"images":case"raw":break;default:De(n)}if(r.raw)for(const n in r.raw){const a=r.raw[n];a==null||s.has(n)||(typeof a=="string"||a instanceof Uint8Array)&&t(n,a)}e.length!==0&&(this.tagsElement={id:x.Tags,data:[{id:x.Tag,data:[{id:x.Targets,data:[{id:x.TargetTypeValue,data:50},{id:x.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){const e=this.output._metadataTags,t=[],r=new Set,s=e.images??[];for(const n of s){let a=n.name;a===void 0&&(a=(n.kind==="coverFront"?"cover":n.kind==="coverBack"?"back":"image")+(tu(n.mimeType)??""));let o;for(;;){o=0n;for(let c=0;c<8;c++)o<<=8n,o|=BigInt(Math.floor(Math.random()*256));if(o!==0n&&!r.has(o))break}r.add(o),t.push({id:x.AttachedFile,data:[n.description!==void 0?{id:x.FileDescription,data:new Rt(n.description)}:null,{id:x.FileName,data:new Rt(a)},{id:x.FileMediaType,data:n.mimeType},{id:x.FileData,data:n.data},{id:x.FileUID,data:o}]})}for(const[n,a]of Object.entries(e.raw??{}))!(a instanceof On)||!/^\d+$/.test(n)||s.find(c=>c.mimeType===a.mimeType&&Ho(c.data,a.data))||t.push({id:x.AttachedFile,data:[a.description!==void 0?{id:x.FileDescription,data:new Rt(a.description)}:null,{id:x.FileName,data:new Rt(a.name??"")},{id:x.FileMediaType,data:a.mimeType??""},{id:x.FileData,data:a.data},{id:x.FileUID,data:BigInt(n)}]});t.length!==0&&(this.attachmentsElement={id:x.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);const e={id:x.Segment,size:this.format._options.appendOnly?-1:Co,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){const{data:t,start:r}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(t,r)}}createCues(){this.cues={id:x.Cues,data:[]}}get segmentDataOffset(){return m(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async getMimeType(){await this.allTracksKnown.promise;const e=this.trackDatas.map(t=>t.type==="video"||t.type==="audio"?t.info.decoderConfig.codec:{webvtt:"wvtt"}[t.track.source._codec]);return _c({isWebM:this.format instanceof No,hasVideo:this.trackDatas.some(t=>t.type==="video"),hasAudio:this.trackDatas.some(t=>t.type==="audio"),codecStrings:e})}getVideoTrackData(e,t,r){const s=this.trackDatas.find(u=>u.track===e);if(s)return s;ms(r),m(r),m(r.decoderConfig),m(r.decoderConfig.codedWidth!==void 0),m(r.decoderConfig.codedHeight!==void 0);const n=r.decoderConfig.displayAspectWidth,a=r.decoderConfig.displayAspectHeight,o=n===void 0||a===void 0?null:Ti({num:n,den:a}),c={track:e,type:"video",info:{width:r.decoderConfig.codedWidth,height:r.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:r.decoderConfig,alphaMode:!!t.sideData.alpha},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return e.source._codec==="vp9"?c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array(lu(c.info.decoderConfig.codec))}:e.source._codec==="av1"&&(c.info.decoderConfig={...c.info.decoderConfig,description:new Uint8Array($o(c.info.decoderConfig.codec))}),this.trackDatas.push(c),this.trackDatas.sort((u,l)=>u.track.id-l.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t,r){const s=this.trackDatas.find(c=>c.track===e);if(s)return s;qt(r),m(r),m(r.decoderConfig);const n={...r.decoderConfig};let a=!1;if(e.source._codec==="aac"&&!n.description){const c=_t(Me.tempFromBytes(t.data));if(!c)throw new Error("Couldn't parse ADTS header from the AAC packet. Make sure the packets are in ADTS format (as specified in ISO 13818-7) when not providing a description, or provide a description (must be an AudioSpecificConfig as specified in ISO 14496-3) and ensure the packets are raw AAC data.");const u=Lt[c.samplingFrequencyIndex],l=Dr[c.channelConfiguration];if(u===void 0||l===void 0)throw new Error("Invalid ADTS frame header.");n.description=Wn({objectType:c.objectType,sampleRate:u,numberOfChannels:l}),a=!0}const o={track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:n,requiresAdtsStripping:a},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((c,u)=>c.track.id-u.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){const r=this.trackDatas.find(n=>n.track===e);if(r)return r;Jo(t),m(t),m(t.config);const s={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,closed:!1};return this.trackDatas.push(s),this.trackDatas.sort((n,a)=>n.track.id-a.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}async addEncodedVideoPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,t,r),a=t.type==="key";this.validateTimestamp(n.track,t.timestamp,a);let o=t.timestamp,c=t.duration;e.metadata.frameRate!==void 0&&(o=vr(o,e.metadata.frameRate),c=vr(c,e.metadata.frameRate));const u=n.info.alphaMode?t.sideData.alpha??null:null,l=this.createInternalChunk(t.data,o,c,t.type,u);e.source._codec==="vp9"&&this.fixVP9ColorSpace(n,l),n.chunkQueue.push(l),await this.interleaveChunks()}finally{s()}}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,t,r);let a=t.data;if(n.info.requiresAdtsStripping){const u=_t(Me.tempFromBytes(a));if(!u)throw new Error("Expected ADTS frame, didn't get one.");const l=u.crcCheck===null?xi:Ot;a=a.subarray(l)}const o=t.type==="key";this.validateTimestamp(n.track,t.timestamp,o);const c=this.createInternalChunk(a,t.timestamp,t.duration,t.type);n.chunkQueue.push(c),await this.interleaveChunks()}finally{s()}}async addSubtitleCue(e,t,r){const s=await this.mutex.acquire();try{const n=this.getSubtitleTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,!0);let a=t.text;const o=Math.round(t.timestamp*1e3);ls.lastIndex=0,a=a.replace(ls,d=>{const p=Fn(d.slice(1,-1))-o;return`<${wl(p)}>`});const c=le.encode(a),u=`${t.settings??""}
|
|
355
|
+
${t.identifier??""}
|
|
356
|
+
${t.notes??""}`,l=this.createInternalChunk(c,t.timestamp,t.duration,"key",u.trim()?le.encode(u):null);n.chunkQueue.push(l),await this.interleaveChunks()}finally{s()}}async interleaveChunks(e=!1){if(!(!e&&!this.allTracksAreKnown())){e:for(;;){let t=null,r=1/0;for(const n of this.trackDatas){if(!e&&n.chunkQueue.length===0&&!n.closed)break e;n.chunkQueue.length>0&&n.chunkQueue[0].timestamp<r&&(t=n,r=n.chunkQueue[0].timestamp)}if(!t)break;const s=t.chunkQueue.shift();this.writeBlock(t,s)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if(t.type!=="key"||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;const r=new re(t.data);r.skipBits(2);const s=r.readBits(1),a=(r.readBits(1)<<1)+s;if(a===3&&r.skipBits(1),r.readBits(1)||r.readBits(1)!==0||(r.skipBits(2),r.readBits(24)!==4817730))return;a>=2&&r.skipBits(1);const l={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];Wl(t.data,r.pos,r.pos+3,l)}createInternalChunk(e,t,r,s,n=null){return{data:e,type:s,timestamp:t,duration:r,additions:n}}writeBlock(e,t){this.segment||this.createSegment();const r=Math.round(1e3*t.timestamp),s=this.trackDatas.every(l=>{if(e===l)return t.type==="key";const d=l.chunkQueue[0];return d?d.type==="key":l.closed});let n=!1;if(!this.currentCluster)n=!0;else{m(this.currentClusterStartMsTimestamp!==null),m(this.currentClusterMaxMsTimestamp!==null);const l=r-this.currentClusterStartMsTimestamp;n=s&&r>this.currentClusterMaxMsTimestamp&&l>=1e3*(this.format._options.minimumClusterDuration??1)||l>rm}n&&this.createNewCluster(r);const a=r-this.currentClusterStartMsTimestamp;if(a<tm)return;const o=new Uint8Array(4),c=new DataView(o.buffer);c.setUint8(0,128|e.track.id),c.setInt16(1,a,!1);const u=Math.round(1e3*t.duration);if(t.additions){const l={id:x.BlockGroup,data:[{id:x.Block,data:[o,t.data]},t.type==="delta"?{id:x.ReferenceBlock,data:new Ac(e.lastWrittenMsTimestamp-r)}:null,t.additions?{id:x.BlockAdditions,data:[{id:x.BlockMore,data:[{id:x.BlockAddID,data:1},{id:x.BlockAdditional,data:t.additions}]}]}:null,u>0?{id:x.BlockDuration,data:u}:null]};this.ebmlWriter.writeEBML(l)}else{c.setUint8(3,+(t.type==="key")<<7);const l={id:x.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(l)}this.startTimestamp=Math.min(this.startTimestamp,r),this.endTimestamp=Math.max(this.endTimestamp,r+u),e.lastWrittenMsTimestamp=r,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:r}),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,r)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:x.Cluster,size:this.format._options.appendOnly?-1:_o,data:[{id:x.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(m(this.currentCluster),!this.format._options.appendOnly){const s=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),n=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(s,_o),this.writer.seek(n)}if(this.format._options.onCluster){m(this.currentClusterStartMsTimestamp!==null);const{data:s,start:n}=this.writer.stopTrackingWrites();this.format._options.onCluster(s,n,this.currentClusterStartMsTimestamp/1e3)}const e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(const[s,{firstMsTimestamp:n}]of this.trackDatasInCurrentCluster)t.has(n)||t.set(n,[]),t.get(n).push(s);const r=[...t.entries()].sort((s,n)=>s[0]-n[0]);for(const[s,n]of r)m(this.cues),this.cues.data.push({id:x.CuePoint,data:[{id:x.CueTime,data:s},...n.map(a=>({id:x.CueTrackPositions,data:[{id:x.CueTrack,data:a.track.id},{id:x.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){const t=await this.mutex.acquire(),r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),m(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){const t=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(t,Co);const r=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new gn(r),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),m(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}/*!
|
|
357
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
358
|
+
*
|
|
359
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
360
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
361
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
362
|
+
*/class nm{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=255,s=224|e.mpegVersionId<<3|e.layer<<1;let n;e.mpegVersionId&2?n=e.mpegVersionId&1?0:1:n=1;const a=0,o=155;let c=-1;const u=n*16*4+e.layer*16;for(let w=0;w<16;w++){const g=ln[u+w];if(un(n,e.layer,1e3*g,e.sampleRate,a)>=o){c=w;break}}if(c===-1)throw new Error("No suitable bitrate found.");const l=c<<4|e.frequencyIndex<<2|a<<1,d=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=r,this.helper[1]=s,this.helper[2]=l,this.helper[3]=d,this.writer.write(this.helper.subarray(0,4));const h=gs(e.mpegVersionId,e.channel);this.writer.seek(t+h),this.writeU32(ps);let p=0;e.frameCount!==null&&(p|=sr.FrameCount),e.fileSize!==null&&(p|=sr.FileSize),e.toc!==null&&(p|=sr.Toc),this.writeU32(p),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));const y=ln[u+c],f=un(n,e.layer,1e3*y,e.sampleRate,a);this.writer.seek(t+f)}}/*!
|
|
363
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
364
|
+
*
|
|
365
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
366
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
367
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
368
|
+
*/class am extends Bt{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(this.format._options.xingHeader===!1),this.mp3Writer=new nm(this.writer),Si(this.output._metadataTags)||new ua(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw new Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){const r=await this.mutex.acquire();try{const s=this.format._options.xingHeader!==!1;if(!this.xingFrameData&&s){const n=Z(t.data);if(n.byteLength<4)throw new Error("Invalid MP3 header in sample.");const a=n.getUint32(0,!1),o=ws(a,null).header;if(!o)throw new Error("Invalid MP3 header in sample.");const c=gs(o.mpegVersionId,o.channel);if(n.byteLength>=c+4){const u=n.getUint32(c,!1);if(u===ps||u===qn)return}this.xingFrameData={mpegVersionId:o.mpegVersionId,layer:o.layer,frequencyIndex:o.frequencyIndex,sampleRate:o.sampleRate,channel:o.channel,modeExtension:o.modeExtension,copyright:o.copyright,original:o.original,emphasis:o.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,t.timestamp,t.type==="key"),s&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{r()}}async addSubtitleCue(){throw new Error("MP3 does not support subtitles.")}async finalize(){if(!this.xingFrameData||this.xingFramePos===null)return;const e=await this.mutex.acquire(),r=this.writer.getPos()-this.xingFramePos;this.writer.seek(this.xingFramePos);const s=new Uint8Array(100);for(let n=0;n<100;n++){const a=Math.floor(this.framePositions.length*(n/100)),o=this.framePositions[a]-this.xingFramePos;s[n]=256*(o/r)}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=r,this.xingFrameData.toc=s,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){const{data:n,start:a}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(n,a)}e()}}/*!
|
|
369
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
370
|
+
*
|
|
371
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
372
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
373
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
374
|
+
*/const om=8192;class cm extends Bt{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=ge(),this.pageBytes=new Uint8Array(Mc),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,Rc({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw new Error("Video tracks are not supported.")}getTrackData(e,t){const r=this.trackDatas.find(a=>a.track===e);if(r)return r;let s;do s=Math.floor(2**32*Math.random());while(this.trackDatas.some(a=>a.serialNumber===s));m(e.source._codec==="vorbis"||e.source._codec==="opus"),qt(t),m(t),m(t.decoderConfig);const n={track:e,serialNumber:s,internalSampleRate:e.source._codec==="opus"?zr:t.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,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(n,t),this.trackDatas.push(n),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),n}queueHeaderPackets(e,t){if(m(t.decoderConfig),e.track.source._codec==="vorbis"){m(t.decoderConfig.description);const r=he(t.decoderConfig.description);if(r[0]!==2)throw new TypeError("First byte of Vorbis decoder description must be 2.");let s=1;const n=()=>{let f=0;for(;;){const w=r[s++];if(w===void 0)throw new TypeError("Vorbis decoder description is too short.");if(f+=w,w<255)return f}},a=n(),o=n();if(r.length-s<=0)throw new TypeError("Vorbis decoder description is too short.");const u=r.subarray(s,s+=a);s+=o;const l=r.subarray(s),d=new Uint8Array(7);d[0]=3,d[1]=118,d[2]=111,d[3]=114,d[4]=98,d[5]=105,d[6]=115;const h=fn(d,this.output._metadataTags,!0);e.packetQueue.push({data:u,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:h,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});const y=Z(u).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(y&15),1<<(y>>4)],modeBlockflags:cc(l).modeBlockflags}}else if(e.track.source._codec==="opus"){if(!t.decoderConfig.description)throw new TypeError("For Ogg, Opus decoder description is required.");const r=he(t.decoderConfig.description),s=new Uint8Array(8),n=Z(s);n.setUint32(0,1332770163,!1),n.setUint32(4,1415669619,!1);const a=fn(s,this.output._metadataTags,!0);e.packetQueue.push({data:r,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:a,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:ks(r).preSkip}}}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=n.currentTimestampInSamples,{durationInSamples:o,vorbisBlockSize:c}=Fc(t.data,n.codecInfo,n.vorbisLastBlocksize);n.currentTimestampInSamples+=o,n.vorbisLastBlocksize=c,n.packetQueue.push({data:t.data,timestampInSamples:a,durationInSamples:o,forcePageFlush:!1}),await this.interleavePages()}finally{s()}}addSubtitleCue(){throw new Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(const t of this.trackDatas)for(;t.packetQueue.length>0;){const r=t.packetQueue.shift();if(this.writePacket(t,r,!1),r.forcePageFlush)break}this.bosPagesWritten=!0}e:for(;;){let t=null,r=1/0;for(const a of this.trackDatas){if(!e&&a.packetQueue.length<=1&&!a.closed)break e;a.packetQueue.length>0&&a.packetQueue[0].timestampInSamples<r&&(t=a,r=a.packetQueue[0].timestampInSamples)}if(!t)break;const s=t.packetQueue.shift(),n=t.packetQueue.length===0;this.writePacket(t,s,n)}e||await this.writer.flush()}writePacket(e,t,r){const s=t.timestampInSamples+t.durationInSamples;if(this.format._options.maximumPageDuration!==void 0){const u=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&s-e.currentPageStartTimestampInSamples>u&&this.writePage(e,!1)}let n=t.data.length,a=0,o=0;for(;;){e.currentLacingValues.length===0&&a>0&&(e.currentPageStartsWithFreshPacket=!1);const u=Math.min(255,n);e.currentLacingValues.push(u),e.currentPageSize++,o+=u;const l=n<255;if(e.currentLacingValues.length===255){const d=t.data.subarray(a,o);if(a=o,e.currentPageData.push(d),e.currentPageSize+=d.length,this.writePage(e,r&&l),l)return}if(l)break;n-=255}const c=t.data.subarray(a);e.currentPageData.push(c),e.currentPageSize+=c.length,e.currentGranulePosition=s,(e.currentPageSize>=om||t.forcePageFlush)&&this.writePage(e,r)}writePage(e,t){this.pageView.setUint32(0,Jn,!0),this.pageView.setUint8(4,0);let r=0;e.currentPageStartsWithFreshPacket||(r|=1),e.pagesWritten===0&&(r|=2),t&&(r|=4),this.pageView.setUint8(5,r);const s=e.currentLacingValues.every(c=>c===255)?-1:e.currentGranulePosition;Ql(this.pageView,6,s),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 n=27+e.currentLacingValues.length;for(const c of e.currentPageData)this.pageBytes.set(c,n),n+=c.length;const a=this.pageBytes.subarray(0,n),o=Bc(a);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(a),this.format._options.onPage){const{data:c,start:u}=this.writer.stopTrackingWrites();this.format._options.onPage(c,u,e.track.source)}}async onTrackClose(e){const t=await this.mutex.acquire(),r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0;await this.interleavePages(!0);for(const t of this.trackDatas)t.currentLacingValues.length>0&&this.writePage(t,!0);e()}}/*!
|
|
375
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
376
|
+
*
|
|
377
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
378
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
379
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
380
|
+
*/const lm=0,El=4096,Io=256,um=224,Eo=192,vo=new Uint8Array([9,240]),Bo=new Uint8Array([70,1]);class dm extends Bt{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(ze),this.packetView=Z(this.packetBuffer),this.allTracksKnown=ge(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=t}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,Nc(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){const r=this.trackDatas.find(u=>u.track===e);if(r)return r;ms(t),m(t==null?void 0:t.decoderConfig);const s=e.source._codec;m(s==="avc"||s==="hevc");const n=s==="avc"?27:36,a=Io+this.trackDatas.length,o=um+this.videoTrackIndex++,c={track:e,pid:a,streamType:n,streamId:o,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}getAudioTrackData(e,t){const r=this.trackDatas.find(u=>u.track===e);if(r)return r;qt(t),m(t==null?void 0:t.decoderConfig);const s=e.source._codec;m(s==="aac"||s==="mp3"||s==="ac3"||s==="eac3");let n,a;switch(s){case"aac":n=15,a=Eo+this.audioTrackIndex++;break;case"mp3":n=3,a=Eo+this.audioTrackIndex++;break;case"ac3":n=129,a=189;break;case"eac3":n=135,a=189;break}const o=Io+this.trackDatas.length,c={track:e,pid:o,streamType:n,streamId:a,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(c),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),c}async addEncodedVideoPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getVideoTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=this.prepareVideoPacket(n,t,r);t.type==="key"&&await this.flushTimestampQueue(n),n.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{s()}}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{const n=this.getAudioTrackData(e,r);this.validateTimestamp(n.track,t.timestamp,t.type==="key");const a=this.prepareAudioPacket(n,t,r);t.type==="key"&&await this.flushTimestampQueue(n),n.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:t.type==="key"})}finally{s()}}async addSubtitleCue(){throw new Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,t,r){var n;const s=e.track.source._codec;if(e.inputIsAnnexB===null){const a=(n=r==null?void 0:r.decoderConfig)==null?void 0:n.description;if(e.inputIsAnnexB=!a,!e.inputIsAnnexB){const o=he(a);s==="avc"?e.avcDecoderConfig=rc(o):e.hevcDecoderConfig=Ru(o)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,s):this.prepareLengthPrefixedVideoPacket(e,t,s)}prepareAnnexBVideoPacket(e,t){const r=[];for(const n of Ur(e)){const a=e.subarray(n.offset,n.offset+n.length);(t==="avc"?Br(a[0])===Xe.AUD:Ht(a[0])===Te.AUD_NUT)||r.push(a)}const s=t==="avc"?vo:Bo;return r.unshift(s),ts(r)}prepareLengthPrefixedVideoPacket(e,t,r){const s=t.data,n=r==="avc"?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,a=[];for(const c of jn(s,n)){const u=s.subarray(c.offset,c.offset+c.length);(r==="avc"?Br(u[0])===Xe.AUD:Ht(u[0])===Te.AUD_NUT)||a.push(u)}if(t.type==="key")if(r==="avc"){const c=e.avcDecoderConfig;for(const u of c.pictureParameterSets)a.unshift(u);for(const u of c.sequenceParameterSets)a.unshift(u)}else{const c=e.hevcDecoderConfig;for(const u of c.arrays)if(u.nalUnitType===Te.PPS_NUT)for(const l of u.nalUnits)a.unshift(l);for(const u of c.arrays)if(u.nalUnitType===Te.SPS_NUT)for(const l of u.nalUnits)a.unshift(l);for(const u of c.arrays)if(u.nalUnitType===Te.VPS_NUT)for(const l of u.nalUnits)a.unshift(l)}const o=r==="avc"?vo:Bo;return a.unshift(o),ts(a)}prepareAudioPacket(e,t,r){var c;const s=e.track.source._codec;if(s==="mp3"||s==="ac3"||s==="eac3")return t.data;if(e.inputIsAdts===null){const u=(c=r==null?void 0:r.decoderConfig)==null?void 0:c.description;if(e.inputIsAdts=!u,!e.inputIsAdts){const l=Bi(he(u)),d=Go(l);e.adtsHeader=d.header,e.adtsHeaderBitstream=d.bitstream}}if(e.inputIsAdts)return t.data;m(e.adtsHeader),m(e.adtsHeaderBitstream);const n=e.adtsHeader,a=t.data.byteLength+n.byteLength;Qo(e.adtsHeaderBitstream,a);const o=new Uint8Array(a);return o.set(n,0),o.set(t.data,n.byteLength),o}allTracksAreKnown(){for(const e of this.output._tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async flushTimestampQueue(e,t=!0){if(e.timestampProcessingQueue.length===0)return;const r=e.timestampProcessingQueue.map(s=>s.presentationTimestamp).sort((s,n)=>s-n);for(let s=0;s<e.timestampProcessingQueue.length;s++){const n=e.timestampProcessingQueue[s];n.decodeTimestamp=r[s],e.packetQueue.push(n)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}e:for(;;){let t=null,r=1/0;for(const n of this.trackDatas){if(!e&&n.packetQueue.length===0&&!n.closed)break e;n.packetQueue.length>0&&n.packetQueue[0].presentationTimestamp<r&&(t=n,r=n.packetQueue[0].presentationTimestamp)}if(!t)break;const s=t.packetQueue.shift();this.writePesPacket(t,s)}e||await this.writer.flush()}writeTables(){m(!this.tablesWritten),this.writePsiSection(lm,$t),this.writePsiSection(El,fm(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let r=0,s=!0;for(;r<t.length;){const a=184-(s?1:0),o=t.length-r,c=Math.min(a,o);let u;s?(u=this.payloadBuffer.subarray(0,1+c),u[0]=0,u.set(t.subarray(r,r+c),1)):u=t.subarray(r,r+c),this.writeTsPacket(e,s,null,u),r+=c,s=!1}}writePesPacket(e,t){const r=e.track.type==="video",s=r?10:5,n=new Uint8Array(9+s),a=Z(n),o=new re(n.subarray(9));hs(a,0,1,!1),n[3]=e.streamId;const c=e.track.type==="video"?0:Math.min(8+t.data.length,65535);a.setUint16(4,c,!1),a.setUint8(6,132),a.setUint8(7,r?192:128),a.setUint8(8,s);const u=Math.round(t.presentationTimestamp*tt);if(o.pos=0,o.writeBits(4,r?3:2),o.writeBits(3,u>>>30&7),o.writeBits(1,1),o.writeBits(15,u>>>15&32767),o.writeBits(1,1),o.writeBits(15,u&32767),o.writeBits(1,1),r){m(t.decodeTimestamp!==null);const p=Math.round(t.decodeTimestamp*tt);o.writeBits(4,1),o.writeBits(3,p>>>30&7),o.writeBits(1,1),o.writeBits(15,p>>>15&32767),o.writeBits(1,1),o.writeBits(15,p&32767),o.writeBits(1,1)}const l=n.length+t.data.length;let d=0,h=!0;for(;d<l;){const p=h,y=l-d,f=h&&t.isKeyframe,w=h&&!e.firstPacketWritten,g=Math.max(0,184-y);let b;f||w?b=Math.max(2,g):b=g;let k=null;if(b>0){const P=this.adaptationFieldBuffer;b===1?P[0]=0:(P[0]=b-1,P[1]=Number(w)<<7|Number(f)<<6,P.fill(255,2,b)),k=P.subarray(0,b)}const S=Math.min(184-b,y),A=this.payloadBuffer.subarray(0,S);let _=0;if(d<n.length){const P=Math.min(n.length-d,S);A.set(n.subarray(d,d+P),0),_=P}const I=Math.max(0,d-n.length),C=I+(S-_);_<S&&A.set(t.data.subarray(I,C),_),this.writeTsPacket(e.pid,p,k,A),d+=S,h=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,r,s){const n=this.continuityCounters.get(e)??0,a=s.length>0,o=r?a?3:2:a?1:0;this.packetBuffer[0]=71,this.packetView.setUint16(1,(t?16384:0)|e&8191,!1),this.packetBuffer[3]=o<<4|n&15,a&&this.continuityCounters.set(e,n+1&15);let c=4;r&&(this.packetBuffer.set(r,c),c+=r.length),this.packetBuffer.set(s,c),c+=s.length,c<ze&&this.packetBuffer.fill(255,c);const u=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),u)}async onTrackClose(e){const t=await this.mutex.acquire(),r=this.trackDatas.find(s=>s.track===e);r&&(r.closed=!0,await this.flushTimestampQueue(r,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),t()}async finalize(){const e=await this.mutex.acquire();this.allTracksKnown.resolve();for(const t of this.trackDatas)t.closed=!0,await this.flushTimestampQueue(t,!1);await this.interleavePackets(!0),e()}}const hm=79764919,vl=new Uint32Array(256);for(let i=0;i<256;i++){let e=i<<24;for(let t=0;t<8;t++)e=e&2147483648?e<<1^hm:e<<1;vl[i]=e>>>0&4294967295}const Bl=i=>{let e=4294967295;for(let t=0;t<i.length;t++){const r=i[t];e=(e<<8^vl[e>>>24^r])>>>0}return e},$t=new Uint8Array(16);{const i=Z($t);$t[0]=0,i.setUint16(1,45069,!1),i.setUint16(3,1,!1),$t[5]=193,$t[6]=0,$t[7]=0,i.setUint16(8,1,!1),i.setUint16(10,57344|El&8191,!1),i.setUint32(12,Bl($t.subarray(0,12)),!1)}const fm=i=>{let e=0;for(const c of i)e+=5,c.streamType===129?e+=zi.length:c.streamType===135&&(e+=Ui.length);const t=9+e+4,r=new Uint8Array(3+t-4),s=Z(r);r[0]=2,s.setUint16(1,45056|t&4095,!1),s.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,s.setUint16(8,65535,!1),s.setUint16(10,61440,!1);let n=12;for(const c of i)r[n++]=c.streamType,s.setUint16(n,57344|c.pid&8191,!1),n+=2,c.streamType===129?(s.setUint16(n,61440|zi.length,!1),n+=2,r.set(zi,n),n+=zi.length):c.streamType===135?(s.setUint16(n,61440|Ui.length,!1),n+=2,r.set(Ui,n),n+=Ui.length):(s.setUint16(n,61440,!1),n+=2);const a=Bl(r),o=new Uint8Array(r.length+4);return o.set(r,0),Z(o).setUint32(r.length,a,!1),o};/*!
|
|
381
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
382
|
+
*
|
|
383
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
384
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
385
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
386
|
+
*/class mm{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))}}/*!
|
|
387
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
388
|
+
*
|
|
389
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
390
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
391
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
392
|
+
*/class pm extends Bt{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){const e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new mm(this.writer),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw new Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,r){const s=await this.mutex.acquire();try{if(this.headerWritten||(qt(r),m(r),m(r.decoderConfig),this.writeHeader(e,r.decoderConfig),this.sampleRate=r.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,t.type==="key"),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=2**32)throw new Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{s()}}async addSubtitleCue(){throw new Error("WAVE does not support subtitles.")}writeHeader(e,t){this.format._options.onHeader&&this.writer.startTrackingWrites();let r;const s=e.source._codec,n=st(s);n.dataType==="ulaw"?r=Oe.MULAW:n.dataType==="alaw"?r=Oe.ALAW:n.dataType==="float"?r=Oe.IEEE_FLOAT:r=Oe.PCM;const a=t.numberOfChannels,o=t.sampleRate,c=n.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(4294967295):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(r),this.riffWriter.writeU16(a),this.riffWriter.writeU32(o),this.riffWriter.writeU32(o*c),this.riffWriter.writeU16(c),this.riffWriter.writeU16(8*n.sampleSize),!Si(this.output._metadataTags)){const u=this.format._options.metadataFormat??"info";u==="info"?this.writeInfoChunk(this.output._metadataTags):u==="id3"?this.writeId3Chunk(this.output._metadataTags):De(u)}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:u,start:l}=this.writer.stopTrackingWrites();this.format._options.onHeader(u,l)}}writeInfoChunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");const r=new Set,s=(o,c)=>{if(!pt(c)){console.warn(`Didn't write tag '${o}' because '${c}' is not ISO 8859-1-compatible.`);return}const u=c.length+1,l=new Uint8Array(u);for(let d=0;d<c.length;d++)l[d]=c.charCodeAt(d);this.riffWriter.writeAscii(o),this.riffWriter.writeU32(u),this.writer.write(l),u&1&&this.writer.write(new Uint8Array(1)),r.add(o)};for(const{key:o,value:c}of Rr(e))switch(o){case"title":s("INAM",c),r.add("INAM");break;case"artist":s("IART",c),r.add("IART");break;case"album":s("IPRD",c),r.add("IPRD");break;case"trackNumber":{const u=e.tracksTotal!==void 0?`${c}/${e.tracksTotal}`:c.toString();s("ITRK",u),r.add("ITRK")}break;case"genre":s("IGNR",c),r.add("IGNR");break;case"date":s("ICRD",c.toISOString().slice(0,10)),r.add("ICRD");break;case"comment":s("ICMT",c),r.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":break;case"raw":break;default:De(o)}if(e.raw)for(const o in e.raw){const c=e.raw[o];c==null||o.length!==4||r.has(o)||typeof c=="string"&&s(o,c)}const n=this.writer.getPos(),a=n-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(a),this.writer.seek(n),a&1&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){const t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);const s=new ua(this.writer).writeId3V2Tag(e),n=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(s),this.writer.seek(n),s&1&&this.writer.write(new Uint8Array(1))}async finalize(){const e=await this.mutex.acquire(),t=this.writer.getPos();this.isRf64?(m(this.ds64RiffSizePos!==null),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),m(this.ds64DataSizePos!==null),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),m(this.ds64SampleCountPos!==null),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(m(this.riffSizePos!==null),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),m(this.dataSizePos!==null),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}}/*!
|
|
393
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
394
|
+
*
|
|
395
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
396
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
397
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
398
|
+
*/class Fl{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.endTime=e.endTime,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(this.targetSampleRate*5),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples),this.bufferStartFrame=Math.floor(e.startTime*this.targetSampleRate),this.timestampOffset=e.startTime-this.bufferStartFrame/this.targetSampleRate}doChannelMixerSetup(){m(this.sourceNumberOfChannels!==null);const e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;e===1&&t===2?this.channelMixer=(r,s)=>r[s*e]:e===1&&t===4?this.channelMixer=(r,s,n)=>r[s*e]*+(n<2):e===1&&t===6?this.channelMixer=(r,s,n)=>r[s*e]*+(n===2):e===2&&t===1?this.channelMixer=(r,s)=>{const n=s*e;return .5*(r[n]+r[n+1])}:e===2&&t===4?this.channelMixer=(r,s,n)=>r[s*e+n]*+(n<2):e===2&&t===6?this.channelMixer=(r,s,n)=>r[s*e+n]*+(n<2):e===4&&t===1?this.channelMixer=(r,s)=>{const n=s*e;return .25*(r[n]+r[n+1]+r[n+2]+r[n+3])}:e===4&&t===2?this.channelMixer=(r,s,n)=>{const a=s*e;return .5*(r[a+n]+r[a+n+2])}:e===4&&t===6?this.channelMixer=(r,s,n)=>{const a=s*e;return n<2?r[a+n]:n===2||n===3?0:r[a+n-2]}:e===6&&t===1?this.channelMixer=(r,s)=>{const n=s*e;return Math.SQRT1_2*(r[n]+r[n+1])+r[n+2]+.5*(r[n+4]+r[n+5])}:e===6&&t===2?this.channelMixer=(r,s,n)=>{const a=s*e;return r[a+n]+Math.SQRT1_2*(r[a+2]+r[a+n+4])}:e===6&&t===4?this.channelMixer=(r,s,n)=>{const a=s*e;return n<2?r[a+n]+Math.SQRT1_2*r[a+2]:r[a+n+2]}:this.channelMixer=(r,s,n)=>n<e?r[s*e+n]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){const r=new Float32Array(t);r.set(this.tempSourceBuffer),this.tempSourceBuffer=r}}async add(e){this.sourceSampleRate===null&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup());const t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);const r=e.allocationSize({planeIndex:0,format:"f32"}),s=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(s,{planeIndex:0,format:"f32"});const n=e.timestamp,a=Math.min(e.timestamp+e.duration,this.endTime),o=Math.floor(n*this.targetSampleRate),c=Math.ceil(a*this.targetSampleRate);for(let u=o;u<c;u++){if(u<this.bufferStartFrame)continue;for(;u>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;const l=u-this.bufferStartFrame;m(l<this.bufferSizeInFrames);const p=(u/this.targetSampleRate-n)*this.sourceSampleRate,y=Math.floor(p),f=Math.ceil(p),w=p-y;for(let g=0;g<this.targetNumberOfChannels;g++){let b=0,k=0;y>=0&&y<e.numberOfFrames&&(b=this.channelMixer(s,y,g)),f>=0&&f<e.numberOfFrames&&(k=this.channelMixer(s,f,g));const S=b+w*(k-b),A=l*this.targetNumberOfChannels+g;this.outputBuffer[A]+=S}this.maxWrittenFrame===null?this.maxWrittenFrame=l:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,l)}}async finalizeCurrentBuffer(){if(this.maxWrittenFrame===null)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,s=new Ee({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:r+this.timestampOffset,data:t});await this.onSample(s),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}/*!
|
|
399
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
400
|
+
*
|
|
401
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
402
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
403
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
404
|
+
*/class fa{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}_ensureValidAdd(){if(!this._connectedTrack)throw new Error("Source is not connected to an output track.");if(this._connectedTrack.output.state==="canceled")throw new Error("Output has been canceled.");if(this._connectedTrack.output.state==="finalizing"||this._connectedTrack.output.state==="finalized")throw new Error("Output has been finalized.");if(this._connectedTrack.output.state==="pending")throw new Error("Output has not started.");if(this._closed)throw new Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;const e=this._connectedTrack;if(!e)throw new Error("Cannot call close without connecting the source to an output track.");if(e.output.state==="pending")throw new Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,!(e.output.state==="finalizing"||e.output.state==="finalized")&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??(this._closingPromise=(async()=>{await this._flushAndClose(e),this._closed=!0})())}}class Ri extends fa{constructor(e){if(super(),this._connectedTrack=null,!Se.includes(e))throw new TypeError(`Invalid video codec '${e}'. Must be one of: ${Se.join(", ")}.`);this._codec=e}}const Rn=(i,e)=>{if(i.metadata.hasOnlyKeyPackets&&e.type!=="key")throw new Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class Rl extends Ri{constructor(e){super(e)}add(e,t){if(!(e instanceof de))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),Rn(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class ma{constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.codedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new ki,this.customEncoderQueueSize=0,this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t,r){var n,a,o,c,u,l,d,h,p,y,f,w;const s=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();const g=this.encodingConfig,b=g.sizeChangeBehavior??"deny";let k=!1;if(this.codedWidth!==null&&this.codedHeight!==null){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(k=!0,b==="deny"))throw new Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(((n=g.transform)==null?void 0:n.width)!==void 0||((a=g.transform)==null?void 0:a.height)!==void 0||((o=g.transform)==null?void 0:o.rotate)!==void 0||((c=g.transform)==null?void 0:c.crop)!==void 0||((u=g.transform)==null?void 0:u.force)===!0||k&&b!=="passThrough"){let I=(l=g.transform)==null?void 0:l.width,C=(d=g.transform)==null?void 0:d.height,P=((h=g.transform)==null?void 0:h.fit)??"fill";k&&b!=="passThrough"&&(m(this.outputWidth),m(this.outputHeight),m(b!=="deny"),I=this.outputWidth,C=this.outputHeight,P=b);const v=await e.transform({width:I,height:C,roundDimensionsTo:2,crop:(p=g.transform)==null?void 0:p.crop,rotate:(y=g.transform)==null?void 0:y.rotate,fit:P,alpha:g.alpha});(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=v.displayWidth,this.outputHeight=v.displayHeight),t&&e.close(),e=v,t=!0}else(this.outputWidth===null||this.outputHeight===null)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);const _=(f=g.transform)==null?void 0:f.frameRate;if(_!==void 0){const I=e.timestamp+e.duration,C=ba(e.timestamp,_);if(this.frameRateLastSample!==null)if(C<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=I;return}else await this.padFrameRate(C,r);e===s&&(e=e.clone(),t=!0),e.setTimestamp(C),e.setDuration(1/_),(w=this.frameRateLastSample)==null||w.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=C,this.frameRateLastEndTimestamp=I}await this.processAndEncode(e,r)}finally{t&&e.close()}}async processAndEncode(e,t){var n;const r=this.encodingConfig;let s;if((n=r.transform)!=null&&n.process){let a=r.transform.process(e);if(a instanceof Promise&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]),s=a.map(o=>o instanceof Ae?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new Ae(o):new Ae(o,{timestamp:e.timestamp,duration:e.duration}))}else s=[e];try{for(const a of s){this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(a),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);const o=this.encodingConfig.keyFrameInterval??2,c=Math.floor(a.timestamp/o),u={...t,keyFrame:(t==null?void 0:t.keyFrame)||o===0||c!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=c,this.customEncoder){this.customEncoderQueueSize++;const l=a.clone(),d=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(l,u)).then(()=>this.customEncoderQueueSize--).catch(h=>this.error??(this.error=h)).finally(()=>{l.close()});this.customEncoderQueueSize>=4&&await d}else{m(this.encoder);const l=a.toVideoFrame(),d=ne(this.preciseTimings,l.timestamp,p=>p.microsecondTimestamp),h=d!==-1?this.preciseTimings[d]:null;if(h&&h.microsecondTimestamp===l.timestamp?(h.timestamp!==a.timestamp&&(h.timestampIsValid=!1),h.duration!==a.duration&&(h.durationIsValid=!1)):(this.preciseTimings.splice(d+1,0,{microsecondTimestamp:l.timestamp,timestamp:a.timestamp,duration:a.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),!this.alphaEncoder)this.encoder.encode(l,u),l.close();else if(!!l.format&&!l.format.includes("A")||this.splitterCreationFailed)this.alphaFrameQueue.push(null),this.encoder.encode(l,u),l.close();else{const y=l.displayWidth,f=l.displayHeight;this.splitter||(this.splitter=new Es(y,f));const{colorFrame:w,alphaFrame:g}=await this.splitter.update(l);this.alphaFrameQueue.push(g),this.encoder.encode(w,u),w.close()}this.encoder.encodeQueueSize>=4&&await new Promise(p=>this.encoder.addEventListener("dequeue",p,{once:!0}))}await this.lastMuxerPromise}}finally{for(const a of s)a!==e&&a.close()}}async padFrameRate(e,t){const r=this.encodingConfig.transform.frameRate;m(this.frameRateLastSample);const s=Math.round((e-this.frameRateLastTimestamp)*r);for(let n=1;n<s;n++){const a=this.frameRateLastSample.clone();a.setTimestamp(this.frameRateLastTimestamp+n/r),a.setDuration(1/r),await this.processAndEncode(a,t),a.close()}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var s,n,a;const t=dl({...this.encodingConfig,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:(s=this.source._connectedTrack)==null?void 0:s.metadata.frameRate});(a=(n=this.encodingConfig).onEncoderConfig)==null||a.call(n,t);const r=os.find(o=>o.supports(this.encodingConfig.codec,t));if(r)this.customEncoder=new r,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=t,this.customEncoder.onPacket=(o,c)=>{var u,l;if(!(o instanceof de))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(c!==void 0&&(!c||typeof c!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");Rn(this.source._connectedTrack,o),(l=(u=this.encodingConfig).onEncodedPacket)==null||l.call(u,o,c),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,o,c).catch(d=>{this.error??(this.error=d)})},await this.customEncoder.init();else{if(typeof VideoEncoder>"u")throw new Error("VideoEncoder is not supported by this browser.");if(t.alpha="discard",this.encodingConfig.alpha==="keep"&&(t.latencyMode="quality"),(t.width%2===1||t.height%2===1)&&(this.encodingConfig.codec==="avc"||this.encodingConfig.codec==="hevc"))throw new Error(`The dimensions ${t.width}x${t.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);if(!(await VideoEncoder.isConfigSupported(t)).supported)throw new Error(`This specific encoder configuration (${t.codec}, ${t.bitrate} bps, ${t.width}x${t.height}, hardware acceleration: ${t.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`);const u=[],l=[];let d=0,h=0;const p=(f,w,g)=>{var I,C;const b={};if(w){const P=new Uint8Array(w.byteLength);w.copyTo(P),b.alpha=P}let k=de.fromEncodedChunk(f,b);const S=ne(this.preciseTimings,f.timestamp,P=>P.microsecondTimestamp),A=S!==-1?this.preciseTimings[S]:null;let _=null;this.emittedEncoderPackets===0&&k.type==="delta"&&(g!=null&&g.decoderConfig)&&(_=Ts(this.encodingConfig.codec,g.decoderConfig,k.data)),(A&&A.microsecondTimestamp===f.timestamp||_!==null)&&(k=k.clone({timestamp:A!=null&&A.timestampIsValid?A.timestamp:void 0,duration:A!=null&&A.durationIsValid?A.duration:void 0,type:_??void 0})),Rn(this.source._connectedTrack,k),(C=(I=this.encodingConfig).onEncodedPacket)==null||C.call(I,k,g),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,k,g).catch(P=>{this.error??(this.error=P)}),this.emittedEncoderPackets++},y=new Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(f,w)=>{if(!this.alphaEncoder){p(f,null,w);return}const g=this.alphaFrameQueue.shift();m(g!==void 0),g?(this.alphaEncoder.encode(g,{keyFrame:f.type==="key"}),h++,g.close(),u.push({chunk:f,meta:w})):h===0?p(f,null,w):(l.push(d+h),u.push({chunk:f,meta:w}))},error:f=>{f.stack=y,this.error??(this.error=f)}}),this.encoder.configure(t),this.encodingConfig.alpha==="keep"){const f=new Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(w,g)=>{h--;const b=u.shift();for(m(b!==void 0),p(b.chunk,w,b.meta),d++;l.length>0&&l[0]===d;){l.shift();const k=u.shift();m(k!==void 0),p(k.chunk,null,k.meta)}},error:w=>{w.stack=f,this.error??(this.error=w)}}),this.alphaEncoder.configure(t)}}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){var t,r,s;if(e||this.checkForEncoderError(),!e&&this.frameRateLastSample){const n=this.encodingConfig.transform.frameRate,a=ba(this.frameRateLastEndTimestamp,n);await this.padFrameRate(a)}(t=this.frameRateLastSample)==null||t.close(),this.frameRateLastSample=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||(await this.encoder.flush(),await((r=this.alphaEncoder)==null?void 0:r.flush())),this.encoder.state!=="closed"&&this.encoder.close(),this.alphaEncoder&&this.alphaEncoder.state!=="closed"&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(n=>n==null?void 0:n.close()),(s=this.splitter)==null||s.close()),e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.error)throw this.error}}let Fo=!1;class Es{constructor(e,t){this.canvas=null,this.gl=null,this.colorProgram=null,this.alphaProgram=null,this.vao=null,this.sourceTexture=null,this.alphaResolutionLocation=null,this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0;const r=typeof OffscreenCanvas<"u"||typeof document<"u"&&typeof document.createElement=="function";if(!Es.forceCpu&&r&&!Fo)try{typeof OffscreenCanvas<"u"?this.canvas=new OffscreenCanvas(e,t):(this.canvas=document.createElement("canvas"),this.canvas.width=e,this.canvas.height=t);const s=this.canvas.getContext("webgl2",{alpha:!0});if(!s)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=s,this.colorProgram=this.createColorProgram(),this.alphaProgram=this.createAlphaProgram(),this.vao=this.createVAO(),this.sourceTexture=this.createTexture(),this.alphaResolutionLocation=this.gl.getUniformLocation(this.alphaProgram,"u_resolution"),this.gl.useProgram(this.colorProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.colorProgram,"u_sourceTexture"),0),this.gl.useProgram(this.alphaProgram),this.gl.uniform1i(this.gl.getUniformLocation(this.alphaProgram,"u_sourceTexture"),0)}catch(s){this.gl=null,this.canvas=null,Fo=!0,console.warn("Falling back to CPU for color/alpha splitting.",s)}}async update(e){return this.gl?this.updateGpu(e):this.updateCpu(e)}updateGpu(e){m(this.gl),m(this.canvas),(e.displayWidth!==this.canvas.width||e.displayHeight!==this.canvas.height)&&(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.sourceTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e);const t=this.runColorProgram(e),r=this.runAlphaProgram(e);return e.close(),{colorFrame:t,alphaFrame:r}}createVertexShader(){return m(this.gl),this.createShader(this.gl.VERTEX_SHADER,`#version 300 es
|
|
405
|
+
in vec2 a_position;
|
|
406
|
+
in vec2 a_texCoord;
|
|
407
|
+
out vec2 v_texCoord;
|
|
408
|
+
|
|
409
|
+
void main() {
|
|
410
|
+
gl_Position = vec4(a_position, 0.0, 1.0);
|
|
411
|
+
v_texCoord = a_texCoord;
|
|
412
|
+
}
|
|
413
|
+
`)}createColorProgram(){m(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
414
|
+
precision highp float;
|
|
415
|
+
|
|
416
|
+
uniform sampler2D u_sourceTexture;
|
|
417
|
+
in vec2 v_texCoord;
|
|
418
|
+
out vec4 fragColor;
|
|
419
|
+
|
|
420
|
+
void main() {
|
|
421
|
+
vec4 source = texture(u_sourceTexture, v_texCoord);
|
|
422
|
+
fragColor = vec4(source.rgb, 1.0);
|
|
423
|
+
}
|
|
424
|
+
`),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createAlphaProgram(){m(this.gl);const e=this.createVertexShader(),t=this.createShader(this.gl.FRAGMENT_SHADER,`#version 300 es
|
|
425
|
+
precision highp float;
|
|
426
|
+
|
|
427
|
+
uniform sampler2D u_sourceTexture;
|
|
428
|
+
uniform vec2 u_resolution; // The width and height of the canvas
|
|
429
|
+
in vec2 v_texCoord;
|
|
430
|
+
out vec4 fragColor;
|
|
431
|
+
|
|
432
|
+
// This function determines the value for a single byte in the YUV stream
|
|
433
|
+
float getByteValue(float byteOffset) {
|
|
434
|
+
float width = u_resolution.x;
|
|
435
|
+
float height = u_resolution.y;
|
|
436
|
+
|
|
437
|
+
float yPlaneSize = width * height;
|
|
438
|
+
|
|
439
|
+
if (byteOffset < yPlaneSize) {
|
|
440
|
+
// This byte is in the luma plane. Find the corresponding pixel coordinates to sample from
|
|
441
|
+
float y = floor(byteOffset / width);
|
|
442
|
+
float x = mod(byteOffset, width);
|
|
443
|
+
|
|
444
|
+
// Add 0.5 to sample the center of the texel
|
|
445
|
+
vec2 sampleCoord = (vec2(x, y) + 0.5) / u_resolution;
|
|
446
|
+
|
|
447
|
+
// The luma value is the alpha from the source texture
|
|
448
|
+
return texture(u_sourceTexture, sampleCoord).a;
|
|
449
|
+
} else {
|
|
450
|
+
// Write a fixed value for chroma and beyond
|
|
451
|
+
return 128.0 / 255.0;
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
void main() {
|
|
456
|
+
// Each fragment writes 4 bytes (R, G, B, A)
|
|
457
|
+
float pixelIndex = floor(gl_FragCoord.y) * u_resolution.x + floor(gl_FragCoord.x);
|
|
458
|
+
float baseByteOffset = pixelIndex * 4.0;
|
|
459
|
+
|
|
460
|
+
vec4 result;
|
|
461
|
+
for (int i = 0; i < 4; i++) {
|
|
462
|
+
float currentByteOffset = baseByteOffset + float(i);
|
|
463
|
+
result[i] = getByteValue(currentByteOffset);
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
fragColor = result;
|
|
467
|
+
}
|
|
468
|
+
`),r=this.gl.createProgram();return this.gl.attachShader(r,e),this.gl.attachShader(r,t),this.gl.linkProgram(r),r}createShader(e,t){m(this.gl);const r=this.gl.createShader(e);return this.gl.shaderSource(r,t),this.gl.compileShader(r),this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS)||console.error("Shader compile error:",this.gl.getShaderInfoLog(r)),r}createVAO(){m(this.gl),m(this.colorProgram);const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),r=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,r),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const s=this.gl.getAttribLocation(this.colorProgram,"a_position"),n=this.gl.getAttribLocation(this.colorProgram,"a_texCoord");return this.gl.enableVertexAttribArray(s),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){m(this.gl);const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}runColorProgram(e){return m(this.gl),m(this.canvas),this.gl.useProgram(this.colorProgram),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4),new VideoFrame(this.canvas,{timestamp:e.timestamp,duration:e.duration??void 0,alpha:"discard"})}runAlphaProgram(e){m(this.gl),m(this.canvas),this.gl.useProgram(this.alphaProgram),this.gl.uniform2f(this.alphaResolutionLocation,this.canvas.width,this.canvas.height),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4);const{width:t,height:r}=this.canvas,s=Math.ceil(t/2)*Math.ceil(r/2),n=t*r+s*2,a=Math.ceil(n/(t*4));let o=new Uint8Array(4*t*a);this.gl.readPixels(0,0,t,a,this.gl.RGBA,this.gl.UNSIGNED_BYTE,o),o=o.subarray(0,n),m(o[t*r]===128),m(o[o.length-1]===128);const c={format:"I420",codedWidth:t,codedHeight:r,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[o.buffer]};return new VideoFrame(o,c)}updateCpu(e){if(!this.worker){const s=new Blob([`(${gm.toString()})()`],{type:"application/javascript"}),n=URL.createObjectURL(s);this.worker=new Worker(n),URL.revokeObjectURL(n),this.worker.addEventListener("message",a=>{const o=a.data,c=this.pendingRequests.get(o.id);c&&(this.pendingRequests.delete(o.id),"error"in o?c.reject(new Error(o.error)):c.resolve({colorFrame:o.colorFrame,alphaFrame:o.alphaFrame}))}),this.worker.addEventListener("error",a=>{const o=new Error(a.message||"Color/alpha splitter worker error.");for(const c of this.pendingRequests.values())c.reject(o);this.pendingRequests.clear()})}const t=this.nextRequestId++,r=ge();return this.pendingRequests.set(t,r),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),r.promise}close(){var t,r,s;(r=(t=this.gl)==null?void 0:t.getExtension("WEBGL_lose_context"))==null||r.loseContext(),this.gl=null,this.canvas=null,(s=this.worker)==null||s.terminate(),this.worker=null;const e=new Error("Color/alpha splitter closed.");for(const n of this.pendingRequests.values())n.reject(e);this.pendingRequests.clear()}}Es.forceCpu=!0;const gm=()=>{let i=null,e=Promise.resolve();self.addEventListener("message",n=>{const{id:a,sourceFrame:o}=n.data;e=e.then(async()=>{try{const{colorFrame:c,alphaFrame:u}=await t(o);self.postMessage({id:a,colorFrame:c,alphaFrame:u},{transfer:[c,u]})}catch(c){self.postMessage({id:a,error:c.message})}finally{o.close()}})});const t=async n=>{const a=n.format;if(!a)throw new Error("CPU color/alpha splitting requires a known VideoFrame format.");const o=n.codedWidth,c=n.codedHeight,u=n.allocationSize();if((!i||i.byteLength!==u)&&(i=new Uint8Array(u)),await n.copyTo(i),a==="RGBA"||a==="BGRA")return r(i,o,c,a,n);if(a==="I420A"||a==="I420AP10"||a==="I420AP12"||a==="I422A"||a==="I422AP10"||a==="I422AP12"||a==="I444A"||a==="I444AP10"||a==="I444AP12")return s(i,o,c,a,n);throw new Error(`CPU color/alpha splitting does not support format '${a}'.`)},r=(n,a,o,c,u)=>{const l=a*o,d=Math.ceil(a/2),h=Math.ceil(o/2),p=l+d*h*2,y=new Uint8Array(p);for(let b=0,k=3;b<l;b++,k+=4)y[b]=n[k];y.fill(128,l);const f=new VideoFrame(n,{format:c==="RGBA"?"RGBX":"BGRX",codedWidth:a,codedHeight:o,timestamp:u.timestamp,duration:u.duration??void 0}),w={format:"I420",codedWidth:a,codedHeight:o,timestamp:u.timestamp,duration:u.duration??void 0,transfer:[y.buffer]},g=new VideoFrame(y,w);return{colorFrame:f,alphaFrame:g}},s=(n,a,o,c,u)=>{const l=c.includes("P10"),d=c.includes("P12"),h=l||d?2:1;let p,y;c.startsWith("I420")?(p=Math.ceil(a/2),y=Math.ceil(o/2)):c.startsWith("I422")?(p=Math.ceil(a/2),y=o):(p=a,y=o);const f=a*o,w=p*y,g=f*h,b=w*h,k=f*h,S=g+b*2,A=c.replace("A",""),_=Math.ceil(a/2),I=Math.ceil(o/2),C=_*I,P=C*h,v=k+2*P,M=new Uint8Array(v),R=S;M.set(n.subarray(R,R+k),0);const L=k,H=l?512:d?2048:128;h===1?M.fill(H,L):new Uint16Array(M.buffer,L,2*C).fill(H);const q=l?"I420P10":d?"I420P12":"I420",O=new VideoFrame(n.subarray(0,S),{format:A,codedWidth:a,codedHeight:o,timestamp:u.timestamp,duration:u.duration??void 0}),ee={format:q,codedWidth:a,codedHeight:o,timestamp:u.timestamp,duration:u.duration??void 0,transfer:[M.buffer]},ue=new VideoFrame(M,ee);return{colorFrame:O,alphaFrame:ue}}};class Ro extends Ri{constructor(e){ia(e),super(e.codec),this._encoder=new ma(this,e)}add(e,t){if(!(e instanceof Ae))throw new TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class Jm extends Ri{constructor(e,t){if(!(typeof HTMLCanvasElement<"u"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas<"u"&&e instanceof OffscreenCanvas))throw new TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");ia(t),super(t.codec),this._encoder=new ma(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 s=new Ae(this._canvas,{timestamp:e,duration:t});return this._encoder.add(s,!0,r)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class ep extends Ri{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,r={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="video")throw new TypeError("track must be a video MediaStreamTrack.");if(ia(t),typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.frameRate!=null&&(typeof r.frameRate!="number"||r.frameRate<=0))throw new TypeError("options.frameRate, when provided, must be either a positive number or null.");if(r.timestampBase!==void 0&&r.timestampBase!=="synced-zero"&&r.timestampBase!=="zero"&&r.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");t={...t,latencyMode:"realtime"},super(t.codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=ge(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=r,this._encoder=new ma(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.");const e=this._options.frameRate!==void 0?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let t=null,r=null,s=0,n=!1,a=null,o=0;const c=()=>{if(m(e!==null),!this._lastVideoFrame)return;m(r!==null),m(t!==null);const d=performance.now();for(;d-r>1e3/e;){r+=1e3/e;const h=t+s/e,p=new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*h,duration:1e6/e});l(p,d)}};e!==null&&(this._timerHandle=au(c,4));const u=d=>{var h;if(e===null)l(d);else{const p=performance.now();this._lastVideoFrame?(c(),(h=this._lastVideoFrame)==null||h.close(),this._lastVideoFrame=d):(l(d.clone(),p),r=p,this._lastVideoFrame=d)}},l=(d,h=performance.now())=>{if(n){d.close();return}s++;const p=d.timestamp/1e6;if(this._paused){if(t!==null){if(a!==null&&this._options.timestampBase!=="unix"){const w=p-a;o-=w}a=p}d.close();return}if(t===null){t=p;let f;const w=this._options.timestampBase??"synced-zero";if(w==="unix")f=Date.now()/1e3;else if(w==="zero")f=0;else{const g=this._connectedTrack.output;g._firstMediaStreamTimestamp===null?(g._firstMediaStreamTimestamp=h/1e3,f=0):f=h/1e3-g._firstMediaStreamTimestamp}o=f-t}if(a=p,this._encoder.getQueueSize()>=8){d.close();return}const y=new Ae(d,{timestamp:p+o});this._encoder.add(y,!0).catch(f=>{var w;n=!0,(w=this._abortController)==null||w.abort(),this._promiseWithResolvers.reject(f),this._workerTrackId!==null&&en({type:"stopTrack",trackId:this._workerTrackId})})};if(typeof MediaStreamTrackProcessor<"u"){const d=new MediaStreamTrackProcessor({track:this._track}),h=new WritableStream({write:u});d.readable.pipeTo(h,{signal:this._abortController.signal}).catch(p=>{p instanceof DOMException&&p.name==="AbortError"||this._promiseWithResolvers.reject(p)})}else if(await km())this._workerTrackId=ym++,en({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=h=>{const p=h.data;p.type==="videoFrame"&&p.trackId===this._workerTrackId?u(p.videoFrame):p.type==="error"&&p.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(p.error)},rt.addEventListener("message",this._workerListener);else if(e!==null){const h=document.createElement("video");h.style.position="fixed",h.style.left="-10000px",h.style.top="-10000px",h.style.width="1px",h.style.height="1px",h.style.opacity="0",h.style.pointerEvents="none",h.muted=!0,h.srcObject=new MediaStream([this._track]),document.body.appendChild(h),this._videoElement=h,h.addEventListener("loadeddata",()=>{if(n||!this._videoElement)return;const p=new VideoFrame(h,{timestamp:1e3*performance.now()});u(p),p.close()},{once:!0}),h.play().catch(p=>{n=!0,this._promiseWithResolvers.reject(p)})}else throw new Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){var t;this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&ou(this._timerHandle),(t=this._lastVideoFrame)==null||t.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),this._workerTrackId!==null&&(m(this._workerListener),en({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(r=>{const s=n=>{const a=n.data;a.type==="trackStopped"&&a.trackId===this._workerTrackId&&(m(this._workerListener),rt.removeEventListener("message",this._workerListener),rt.removeEventListener("message",s),r())};rt.addEventListener("message",s)})),await this._encoder.flushAndClose(e)}}class Mi extends fa{constructor(e){if(super(),this._connectedTrack=null,!Ce.includes(e))throw new TypeError(`Invalid audio codec '${e}'. Must be one of: ${Ce.join(", ")}.`);this._codec=e}}class Ml extends Mi{constructor(e){super(e)}add(e,t){if(!(e instanceof de))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be added.");if(t!==void 0&&(!t||typeof t!="object"))throw new TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class pa{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 ki,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.lastMuxerPromise=Promise.resolve()}async add(e,t){var r,s;try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),this.lastNumberOfChannels!==null&&this.lastSampleRate!==null){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw new Error(`Audio parameters must remain constant. Expected ${this.lastNumberOfChannels} channels at ${this.lastSampleRate} Hz, got ${e.numberOfChannels} channels at ${e.sampleRate} Hz.`)}else this.lastNumberOfChannels=e.numberOfChannels,this.lastSampleRate=e.sampleRate;const n=this.encodingConfig;((r=n.transform)==null?void 0:r.numberOfChannels)!==void 0||((s=n.transform)==null?void 0:s.sampleRate)!==void 0?(this.resampler||(this.resampler=new Fl({targetNumberOfChannels:n.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:n.transform.sampleRate??e.sampleRate,startTime:e.timestamp,endTime:1/0,onSample:async o=>{await this.processAndEncode(o,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){var s,n;const r=this.encodingConfig;if(((s=r.transform)==null?void 0:s.sampleFormat)!==void 0&&cl(e.format)!==r.transform.sampleFormat){const a=ll(e,r.transform.sampleFormat);t&&e.close(),e=a,t=!0}if((n=r.transform)!=null&&n.process){let a=r.transform.process(e);if(a instanceof Promise&&(a=await a),a===null)return;Array.isArray(a)||(a=[a]);for(const o of a){if(!(o instanceof Ee))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");await this.encodeSample(o,!0)}t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{this.encoderInitialized||(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),m(this.encoderInitialized);{const r=Math.round(e.timestamp*e.sampleRate),s=Math.round((e.timestamp+e.duration)*e.sampleRate);if(this.lastEndSampleIndex===null)this.lastEndSampleIndex=s;else{const n=r-this.lastEndSampleIndex;if(n>=64){const a=new Ee({data:new Float32Array(n*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:n,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(a,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.customEncoder){this.customEncoderQueueSize++;const r=e.clone(),s=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(r)).then(()=>this.customEncoderQueueSize--).catch(n=>this.error??(this.error=n)).finally(()=>{r.close()});this.customEncoderQueueSize>=4&&await s,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{m(this.encoder);const r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(s=>this.encoder.addEventListener("dequeue",s,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){var h,p;m(this.outputSampleSize),m(this.writeOutputValue);const{numberOfChannels:r,numberOfFrames:s,sampleRate:n,timestamp:a}=e,o=2048,c=[];for(let y=0;y<s;y+=o){const f=Math.min(o,e.numberOfFrames-y),w=f*r*this.outputSampleSize,g=new ArrayBuffer(w),b=new DataView(g);c.push({frameCount:f,view:b})}const u=e.allocationSize({planeIndex:0,format:"f32-planar"}),l=new Float32Array(u/Float32Array.BYTES_PER_ELEMENT);for(let y=0;y<r;y++){e.copyTo(l,{planeIndex:y,format:"f32-planar"});for(let f=0;f<c.length;f++){const{frameCount:w,view:g}=c[f];for(let b=0;b<w;b++)this.writeOutputValue(g,(b*r+y)*this.outputSampleSize,l[f*o+b])}}t&&e.close();const d={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:n}};for(let y=0;y<c.length;y++){const{frameCount:f,view:w}=c[y],g=w.buffer,b=y*o,k=new de(new Uint8Array(g),"key",a+b/n,f/n);(p=(h=this.encodingConfig).onEncodedPacket)==null||p.call(h,k,d),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,k,d)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{var a,o;const{numberOfChannels:t,sampleRate:r}=e,s=fl({numberOfChannels:t,sampleRate:r,...this.encodingConfig});(o=(a=this.encodingConfig).onEncoderConfig)==null||o.call(a,s);const n=cs.find(c=>c.supports(this.encodingConfig.codec,s));if(n)this.customEncoder=new n,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(c,u)=>{var l,d;if(!(c instanceof de))throw new TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(u!==void 0&&(!u||typeof u!="object"))throw new TypeError("The second argument passed to onPacket must be an object or undefined.");(d=(l=this.encodingConfig).onEncodedPacket)==null||d.call(l,c,u),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,c,u).catch(h=>{this.error??(this.error=h)})},await this.customEncoder.init();else if(Pe.includes(this.encodingConfig.codec))this.initPcmEncoder();else{if(typeof AudioEncoder>"u")throw new Error("AudioEncoder is not supported by this browser.");if(!(await AudioEncoder.isConfigSupported(s)).supported)throw new Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);const u=new Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(l,d)=>{var p,y;if(this.encodingConfig.codec==="aac"&&(d!=null&&d.decoderConfig)){let f=!1;if(!d.decoderConfig.description||d.decoderConfig.description.byteLength<2?f=!0:f=Bi(he(d.decoderConfig.description)).objectType===0,f){const w=Number(we(s.codec.split(".")));d.decoderConfig.description=Wn({objectType:w,numberOfChannels:d.decoderConfig.numberOfChannels,sampleRate:d.decoderConfig.sampleRate})}}let h=de.fromEncodedChunk(l);h=h.clone({timestamp:vr(h.timestamp,s.sampleRate),duration:l.duration!=null?vr(h.duration,s.sampleRate):void 0}),(y=(p=this.encodingConfig).onEncodedPacket)==null||y.call(p,h,d),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,h,d).catch(f=>{this.error??(this.error=f)})},error:l=>{l.stack=u,this.error??(this.error=l)}}),this.encoder.configure(s)}m(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;const e=this.encodingConfig.codec,{dataType:t,sampleSize:r,littleEndian:s}=st(e);switch(this.outputSampleSize=r,r){case 1:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint8(a,Ie((o+1)*127.5,0,255)):t==="signed"?this.writeOutputValue=(n,a,o)=>{n.setInt8(a,Ie(Math.round(o*128),-128,127))}:t==="ulaw"?this.writeOutputValue=(n,a,o)=>{const c=Ie(Math.floor(o*32767),-32768,32767);n.setUint8(a,mh(c))}:t==="alaw"?this.writeOutputValue=(n,a,o)=>{const c=Ie(Math.floor(o*32767),-32768,32767);n.setUint8(a,gh(c))}:m(!1);break;case 2:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint16(a,Ie((o+1)*32767.5,0,65535),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt16(a,Ie(Math.round(o*32767),-32768,32767),s):m(!1);break;case 3:t==="unsigned"?this.writeOutputValue=(n,a,o)=>hs(n,a,Ie((o+1)*83886075e-1,0,16777215),s):t==="signed"?this.writeOutputValue=(n,a,o)=>Gl(n,a,Ie(Math.round(o*8388607),-8388608,8388607),s):m(!1);break;case 4:t==="unsigned"?this.writeOutputValue=(n,a,o)=>n.setUint32(a,Ie((o+1)*21474836475e-1,0,4294967295),s):t==="signed"?this.writeOutputValue=(n,a,o)=>n.setInt32(a,Ie(Math.round(o*2147483647),-2147483648,2147483647),s):t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat32(a,o,s):m(!1);break;case 8:t==="float"?this.writeOutputValue=(n,a,o)=>n.setFloat64(a,o,s):m(!1);break;default:De(r),m(!1)}}async flushAndClose(e){e||this.checkForEncoderError(),!e&&this.resampler&&await this.resampler.finalize(),this.resampler=null,this.customEncoder?(e||this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()),await this.customEncoderCallSerializer.call(()=>this.customEncoder.close())):this.encoder&&(e||await this.encoder.flush(),this.encoder.state!=="closed"&&this.encoder.close()),e||this.checkForEncoderError()}getQueueSize(){var e;return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:((e=this.encoder)==null?void 0:e.encodeQueueSize)??0}checkForEncoderError(){if(this.error)throw this.error}}class Mo extends Mi{constructor(e){sa(e),super(e.codec),this._encoder=new pa(this,e)}add(e){if(!(e instanceof Ee))throw new TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class tp extends Mi{constructor(e){sa(e),super(e.codec),this._accumulatedTime=0,this._encoder=new pa(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const t=Ee._fromAudioBuffer(e,this._accumulatedTime);this._accumulatedTime+=e.duration;for(const r of t)await this._encoder.add(r,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class rp extends Mi{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,r={}){if(!(e instanceof MediaStreamTrack)||e.kind!=="audio")throw new TypeError("track must be an audio MediaStreamTrack.");if(sa(t),typeof r!="object"||!r)throw new TypeError("options must be an object.");if(r.timestampBase!==void 0&&r.timestampBase!=="synced-zero"&&r.timestampBase!=="zero"&&r.timestampBase!=="unix")throw new TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=ge(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=r,this._encoder=new pa(this,t),this._track=e}async _start(){this._errorPromiseAccessed||console.warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,r=null,s=0;const n=a=>{if(t){a.close();return}const o=a.timestamp;if(this._paused){if(e!==null){if(r!==null&&this._options.timestampBase!=="unix"){const u=o-r;s-=u}r=o}a.close();return}if(e===null){e=a.timestamp;let c;const u=this._options.timestampBase??"synced-zero";if(u==="unix")c=Date.now()/1e3;else if(u==="zero")c=0;else{const l=this._connectedTrack.output;l._firstMediaStreamTimestamp===null?(l._firstMediaStreamTimestamp=performance.now()/1e3,c=0):c=performance.now()/1e3-l._firstMediaStreamTimestamp}s=c-e}if(r=o,this._encoder.getQueueSize()>=8){a.close();return}a.setTimestamp(o+s),this._encoder.add(a,!0).catch(c=>{var u,l;t=!0,(u=this._abortController)==null||u.abort(),this._promiseWithResolvers.reject(c),(l=this._audioContext)==null||l.suspend()})};if(typeof MediaStreamTrackProcessor<"u"){const a=new MediaStreamTrackProcessor({track:this._track}),o=new WritableStream({write:c=>n(new Ee(c))});a.readable.pipeTo(o,{signal:this._abortController.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||this._promiseWithResolvers.reject(c)})}else{const a=window.AudioContext||window.webkitAudioContext;this._audioContext=new a({sampleRate:this._track.getSettings().sampleRate});const o=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),this._audioContext.state==="suspended"&&await this._audioContext.resume(),o.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let c=0;this._scriptProcessorNode.onaudioprocess=u=>{const l=Ee._fromAudioBuffer(u.inputBuffer,c);c+=u.inputBuffer.duration;for(const d of l)n(d)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(m(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}}const wm=()=>{const i=(r,s)=>{s?self.postMessage(r,{transfer:s}):self.postMessage(r)};i({type:"support",supported:typeof MediaStreamTrackProcessor<"u"});const e=new Map,t=new Map;self.addEventListener("message",r=>{const s=r.data;switch(s.type){case"videoTrack":{t.set(s.trackId,s.track);const n=new MediaStreamTrackProcessor({track:s.track}),a=new WritableStream({write:c=>{if(!t.has(s.trackId)){c.close();return}i({type:"videoFrame",trackId:s.trackId,videoFrame:c},[c])}}),o=new AbortController;e.set(s.trackId,o),n.readable.pipeTo(a,{signal:o.signal}).catch(c=>{c instanceof DOMException&&c.name==="AbortError"||i({type:"error",trackId:s.trackId,error:c})})}break;case"stopTrack":{const n=e.get(s.trackId);n&&(n.abort(),e.delete(s.trackId));const a=t.get(s.trackId);a==null||a.stop(),t.delete(s.trackId),i({type:"trackStopped",trackId:s.trackId})}break;default:De(s)}})};let ym=0,rt=null;const bm=()=>{const i=new Blob([`(${wm.toString()})()`],{type:"application/javascript"}),e=URL.createObjectURL(i);rt=new Worker(e)};let Js=null;const km=async()=>Js!==null?Js:(rt||bm(),new Promise(i=>{m(rt);const e=t=>{const r=t.data;r.type==="support"&&(Js=r.supported,rt.removeEventListener("message",e),i(r.supported))};rt.addEventListener("message",e)})),en=(i,e)=>{m(rt),rt.postMessage(i)};class Dl extends fa{constructor(e){if(super(),this._connectedTrack=null,!dt.includes(e))throw new TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${dt.join(", ")}.`);this._codec=e}}class ip extends Dl{constructor(e){super(e),this._error=null,this._lastMuxerPromise=Promise.resolve(),this._parser=new Dh({codec:e,output:(t,r)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,t,r).catch(s=>{this._error??(this._error=s)})}})}add(e){if(typeof e!="string")throw new TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_checkForError(){if(this._error)throw this._error}async _flushAndClose(e){e||this._checkForError()}}/*!
|
|
469
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
470
|
+
*
|
|
471
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
472
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
473
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
474
|
+
*/class Tm extends Bt{constructor(e,t){if(!(e._target instanceof zt))throw new TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=t._options.getPlaylistPath??(({n:r})=>`playlist-${r}.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(r=>r.isSingleFile?`segments-${r.playlist.n}${r.format.fileExtension}`:`segment-${r.playlist.n}-${r.n}${r.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(r=>`init-${r.n}${r.segmentFormat.fileExtension}`)}async start(){const e=await this.mutex.acquire(),t=this.output._tracks.some(w=>w.metadata.isRelativeToUnixEpoch),r=this.output._tracks.some(w=>!w.metadata.isRelativeToUnixEpoch);if(t&&r)throw new Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;const s=new Map,n=[];let a=!1,o=!1,c=!1;for(const w of this.output._tracks){w.type==="video"&&(a=!0);const g=new Map;for(const b of this.output._tracks){if(w===b||!w.canBePairedWith(b))continue;if(w.type===b.type){o||(console.warn(`Illegal pairing of two ${w.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),o=!0);continue}if(w.isVideoTrack()&&w.metadata.hasOnlyKeyPackets||b.isVideoTrack()&&b.metadata.hasOnlyKeyPackets){c||(console.warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),c=!0);continue}let k=g.get(b.source._codec);k||g.set(b.source._codec,k=[]),k.push(b)}for(const[,b]of g){const k=b.map(_=>_.id).join("-");n.find(_=>_.key===k)||n.push({name:b[0].type+"-"+(n.length+1),key:k,tracks:b,needsEmit:!1,firstNoUri:!1});let A=s.get(w);A||s.set(w,A=[]),A.push(k)}}const u=a?"video":"audio",l=[],d=[],h=[];for(const w of this.output._tracks){const g=s.get(w);if(g){if(m(g.length>0),w.type!==u)continue;for(const b of g){const k=n.find(S=>S.key===b);if(m(k),g.length===1&&k.tracks.length===1){const S=s.get(k.tracks[0]);if(m(S!==void 0),S.length===1){const A=n.find(_=>_.key===S[0]);if(A.tracks.length===1){m(A.tracks[0]===w),l.push({tracks:[w,k.tracks[0]],linkedGroup:null});continue}}}l.push({tracks:[w],linkedGroup:k}),k.needsEmit=!0}}else w.type==="video"?d.push(w):w.type==="audio"&&h.push(w)}const p=({metadata:w})=>{var b,k,S;let g="";return g+=`${w.languageCode??ve}-`,g+=`${w.name??""}-`,g+=`${((b=w.disposition)==null?void 0:b.default)??!0}-`,g+=`${((k=w.disposition)==null?void 0:k.primary)??!1}-`,g+=`${((S=w.disposition)==null?void 0:S.forced)??!1}-`,g};if(d.length>0)if(new Set(d.map(p)).size>1){const g={key:d.map(b=>b.id).join("-"),name:"video-"+(n.length+1),tracks:d,needsEmit:!0,firstNoUri:!0};n.push(g),l.push({tracks:[d[0]],linkedGroup:g})}else for(const g of d)l.push({tracks:[g],linkedGroup:null});if(h.length>0)if(new Set(h.map(p)).size>1){const g={key:h.map(b=>b.id).join("-"),name:"audio-"+(n.length+1),tracks:h,needsEmit:!0,firstNoUri:!0};n.push(g),l.push({tracks:[h[0]],linkedGroup:g})}else for(const g of h)l.push({tracks:[g],linkedGroup:null});const y=w=>{const g=[];let b=0,k=0,S=!1,A=null,_=-1/0;for(const I of w)I.isVideoTrack()?(b++,S||(S=(I.metadata.rotation??0)!==0)):I.isAudioTrack()&&k++,g.push(I.source._codec);for(const I of Pr(this.format._options.segmentFormat)){const C=I.getSupportedCodecs(),P=I.getSupportedTrackCounts();if(g.some(M=>!C.includes(M))||b<P.video.min||b>P.video.max||k<P.audio.min||k>P.audio.max)continue;let v=0;S&&I.supportsVideoRotationMetadata&&v++,v>_&&(A=I,_=v)}return m(A),A},f=async w=>{if(w.some(A=>this.playlists.some(_=>_.tracks.includes(A))))throw new Error("Internal error: track is already registered in a playlist.");const g=y(w),b=this.playlists.length+1,k=await this.getPlaylistPath({n:b,tracks:w,segmentFormat:g});Sm(k);const S={id:this.playlists.length+1,path:k,tracks:w,segmentFormat:g,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new lr};return this.playlists.push(S),S};for(const w of n)if(w.needsEmit)for(let g=0;g<w.tracks.length;g++){const b=w.tracks[g];let k=this.playlists.find(S=>S.tracks[0].id===b.id);k??(k=await f([b])),this.playlistDeclarations.push({playlist:k,groupId:w.name,noUri:w.firstNoUri&&g===0,references:[]})}for(const w of l){let g=this.playlists.find(b=>b.tracks[0].id===w.tracks[0].id);g??(g=await f(w.tracks)),this.playlistDeclarations.push({playlist:g,groupId:null,noUri:!1,references:w.linkedGroup?this.playlistDeclarations.filter(b=>b.groupId===w.linkedGroup.name):[]})}e()}async getMimeType(){return Ir}allTracksAreKnown(e){for(const t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(r=>r.track===t))return!1;return!0}async onTrackClose(e){const t=this.trackDatas.find(n=>n.track===e);t&&(t.closed=!0);const r=this.playlists.find(n=>n.tracks.includes(e));m(r);const s=await r.mutex.acquire();try{await this.advancePlaylist(r)}finally{s()}}getVideoTrackData(e,t){let r=this.trackDatas.find(n=>n.track===e);if(r)return r;ms(t),m(t),m(t==null?void 0:t.decoderConfig);const s=this.playlists.filter(n=>n.tracks.includes(e));return m(s.length===1),r={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:t.decoderConfig}},this.trackDatas.push(r),r}getAudioTrackData(e,t){let r=this.trackDatas.find(n=>n.track===e);if(r)return r;qt(t),m(t),m(t==null?void 0:t.decoderConfig);const s=this.playlists.filter(n=>n.tracks.includes(e));return m(s.length===1),r={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:t.decoderConfig}},this.trackDatas.push(r),r}async addEncodedVideoPacket(e,t,r){const s=this.getVideoTrackData(e,r),n=s.playlist,a=await n.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),s.packets.push(t),n.currentSegmentStartTimestamp===null?n.currentSegmentStartTimestamp=t.timestamp:n.currentSegmentStartTimestampIsFixed||(n.currentSegmentStartTimestamp=Math.min(n.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(n)}finally{a()}}async addEncodedAudioPacket(e,t,r){const s=this.getAudioTrackData(e,r),n=s.playlist,a=await n.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,t.type==="key"),s.packets.push(t),n.currentSegmentStartTimestamp===null?n.currentSegmentStartTimestamp=t.timestamp:n.currentSegmentStartTimestampIsFixed||(n.currentSegmentStartTimestamp=Math.min(n.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(n)}finally{a()}}async addSubtitleCue(e,t,r){throw new Error("Unreachable.")}async advancePlaylist(e){var n,a,o,c;if(m(!e.done),!this.allTracksAreKnown(e))return;if(e.currentSegmentStartTimestamp===null){await this.onPlaylistDone(e);return}const t=this.trackDatas.filter(u=>e.tracks.includes(u.track)),r=t.find(u=>u.info.type==="video"),s=t.find(u=>u.info.type==="audio");for(;;){const u=e.currentSegmentStartTimestamp+this.targetSegmentDuration;let l=0,d=0;if(r&&(!r.closed||r.packets.length>0)){const I=r.packets.every(v=>v.timestamp<u);let C=null,P=null;if(I){if(!r.closed)return}else for(let v=0;v<r.packets.length;v++){const M=r.packets[v];if(C!==null&&M.timestamp>u)break;v>0&&M.type==="key"&&(C=M,P=v)}if(P!==null){if(l=P,s){const v=s.packets.findIndex(M=>M.timestamp>=C.timestamp);if(v!==-1)d=v;else if(s.closed)d=s.packets.length;else return}}else{if(!r.closed)return;l=r.packets.length;const v=iu(r.packets,R=>R.timestamp),M=r.packets[v];if(m(M),s)if(M.timestamp<u){const R=s.packets.findIndex(L=>L.timestamp>=u);if(R!==-1)d=R;else if(s.closed)d=s.packets.length;else return}else{const R=s.packets.findIndex(L=>L.timestamp>M.timestamp);if(R!==-1)d=R;else if(s.closed)d=s.packets.length;else return}}}else if(s&&(!s.closed||s.packets.length>0))if(s.packets.every(C=>C.timestamp<u))if(s.closed)d=s.packets.length;else return;else{const C=us(s.packets,P=>P.timestamp<=u);d=Math.max(C,1)}if(l===0&&d===0){t.every(C=>C.closed)&&await this.onPlaylistDone(e);return}let h=null,p,y;m(this.output._target instanceof zt);const f=this.output._target;if(this.singleFilePerPlaylist)if(e.singleFile===null){const I={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:Li(e)};p=await this.getSegmentPath(I),Do(p),y=Fe(Fe(f.rootPath,e.path),p);const C=await this.output._getTarget({path:y,isRoot:!1,mimeType:e.segmentFormat.mimeType});C._start(),e.singleFile={target:C,path:p,nextOffset:0,info:I}}else p=e.singleFile.path,y=Fe(Fe(f.rootPath,e.path),p);else h={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:Li(e)},p=await this.getSegmentPath(h),Do(p),y=Fe(Fe(f.rootPath,e.path),p),e.nextSegmentId++;let w=0,g=null;const b=new Mn({format:e.segmentFormat,target:new zt(y,async I=>{const C={...I,isRoot:!1};if(I.isRoot)if(e.singleFile){const P=e.singleFile.target.slice(e.singleFile.nextOffset);return P.on("write",({end:v})=>w=Math.max(w,v)),P}else{const P=await this.output._getTarget(C);return g=P,P.on("write",({end:v})=>w=Math.max(w,v)),P}return this.output._getTarget(C)}),initTarget:async()=>{if(e.initSegment)return new Il;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};const I=e.singleFile.target.slice(e.singleFile.nextOffset);return I.on("write",({end:C})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,C)}),I.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),I}else{const I=Li(e),C=await this.getInitPath(I);Am(C),e.initSegment={path:C,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};const P=Fe(Fe(f.rootPath,e.path),C),v=await this.output._getTarget({path:P,isRoot:!1,mimeType:e.segmentFormat.mimeType});return v.on("write",({end:M})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,M)}),v.on("finalized",()=>{var M,R;(R=(M=this.format._options).onInit)==null||R.call(M,v,I)}),v}}});let k=-1/0;try{let I=null,C=null;if(r&&(I=new Rl(r.track.source._codec),b.addVideoTrack(I,r.track.metadata)),s&&(C=new Ml(s.track.source._codec),b.addAudioTrack(C,s.track.metadata)),await b.start(),r){m(I);const P={decoderConfig:r.info.decoderConfig};for(let v=0;v<l;v++){const M=r.packets[v];await I.add(M,P),k=Math.max(k,M.timestamp+M.duration)}}if(s){m(C);const P={decoderConfig:s.info.decoderConfig};for(let v=0;v<d;v++){const M=s.packets[v];await C.add(M,P),k=Math.max(k,M.timestamp+M.duration)}}await b.finalize()}catch(I){throw await b.cancel(),I}h&&(m(g),(a=(n=this.format._options).onSegment)==null||a.call(n,g,h)),l>0&&(m(r),r.packets.splice(0,l)),d>0&&(m(s),s.packets.splice(0,d));let S=1/0;r&&r.packets.length>0&&(S=r.packets[0].timestamp),s&&s.packets.length>0&&(S=Math.min(S,s.packets[0].timestamp));const A=S<1/0?S:k;m(Number.isFinite(A));const _=A-e.currentSegmentStartTimestamp;if(m(_>=0),e.writtenSegments.push({path:p,duration:_,timestamp:e.currentSegmentStartTimestamp,byteSize:w,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:h??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,_),e.currentSegmentStartTimestamp=A,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=w),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){const I=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(m(I.info),(c=(o=this.format._options).onSegmentPopped)==null||c.call(o,I.path,I.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){var t,r;m(!e.done),e.done=!0,e.singleFile&&(await e.singleFile.target._flush(),await e.singleFile.target._finalize(),(r=(t=this.format._options).onSegment)==null||r.call(t,e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&e.writtenSegments.length===0&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){const t=e.writtenSegments;let r=0,s=0,n=0;for(let a=0;a<t.length;a++){n+=t[a].duration;let o=0,c=0;for(let u=a;u<t.length&&(o+=t[u].byteSize,c+=t[u].duration,c>=.5*this.globalTargetDuration&&c<=1.5*this.globalTargetDuration&&(r=Math.max(r,8*o/c)),!(c>1.5*this.globalTargetDuration));u++);}if(r===0)for(const a of t){const o=a.duration||1;r=Math.max(r,8*a.byteSize/o)}for(const a of t)s+=8*a.byteSize;e.peakBitrate=r,e.averageBitrate=s/(n||1)}async writePlaylist(e){var d,h;m(this.output._target instanceof zt);const t=this.output._target;this.updatePlaylistBitrates(e);let r=!1;for(const p of e.writtenSegments)r||(r=p.byteOffset!==null);const s=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets;let n=3;(s||r)&&(n=4),e.initSegment&&(n=5),e.initSegment&&!s&&(n=6);const a=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,o=Fe(t.rootPath,e.path),c=`#EXTM3U
|
|
475
|
+
#EXT-X-VERSION:${n}
|
|
476
|
+
`+(this.isLive?"":`#EXT-X-PLAYLIST-TYPE:VOD
|
|
477
|
+
`)+`#EXT-X-TARGETDURATION:${Math.ceil(a)}
|
|
478
|
+
`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}
|
|
479
|
+
`:"")+`#EXT-X-INDEPENDENT-SEGMENTS
|
|
480
|
+
`+(s?`#EXT-X-I-FRAMES-ONLY
|
|
481
|
+
`:"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}"`+(e.initSegment.byteOffset!==null?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+`
|
|
482
|
+
`:"")+`
|
|
483
|
+
`+e.writtenSegments.map(p=>`#EXTINF:${+p.duration.toFixed(12)},
|
|
484
|
+
`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*p.timestamp).toISOString()}
|
|
485
|
+
`:"")+(p.byteOffset!==null?`#EXT-X-BYTERANGE:${p.byteSize}@${p.byteOffset}
|
|
486
|
+
`:"")+`${p.path}
|
|
487
|
+
`).join("")+(e.done?(e.writtenSegments.length>0?`
|
|
488
|
+
`:"")+`#EXT-X-ENDLIST
|
|
489
|
+
`:"");(h=(d=this.format._options).onPlaylist)==null||h.call(d,c,Li(e));const u=await this.output._getTarget({path:o,isRoot:!1,mimeType:Ir}),l=new Ei(u,!0);l.start(),l.write(le.encode(c)),await l.flush(),await l.finalize()}async writeMasterPlaylist(){var c,u;m(this.output._target instanceof zt);const e=this.output._target;let t=`#EXTM3U
|
|
490
|
+
`,r=!1,s=null,n=0,a=!1;for(const l of this.playlistDeclarations)if(l.groupId===null){const d=l.playlist.tracks[0].isVideoTrack()&&l.playlist.tracks[0].metadata.hasOnlyKeyPackets,h=[];for(const b of l.playlist.tracks){const k=this.trackDatas.find(A=>A.track===b),S=(k==null?void 0:k.info.decoderConfig.codec)??b.source._codec;h.push(S)}let p=0,y=0;if(l.references.length>0){const k=l.references[0].playlist.tracks[0],S=this.trackDatas.find(_=>_.track===k),A=(S==null?void 0:S.info.decoderConfig.codec)??k.source._codec;h.push(A);for(const _ of l.references)m(_.playlist.peakBitrate!==null),p=Math.max(p,_.playlist.peakBitrate),y=Math.max(y,_.playlist.averageBitrate??0)}m(l.playlist.peakBitrate!==null);const f=l.playlist.peakBitrate+p,w=(l.playlist.averageBitrate??0)+y;r||(t+=`
|
|
491
|
+
`,r=!0),d?t+="#EXT-X-I-FRAME-STREAM-INF:":t+="#EXT-X-STREAM-INF:",t+=`BANDWIDTH=${Math.ceil(f)}`,w>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(w)}`),t+=`,CODECS="${h.join(",")}"`;const g=l.playlist.tracks.find(b=>b.isVideoTrack());if(g!=null&&g.isVideoTrack()){const b=this.trackDatas.find(S=>S.track===g),k=b==null?void 0:b.info.decoderConfig;if(k){let S=k.displayAspectWidth??k.codedWidth,A=k.displayAspectHeight??k.codedHeight;S!==void 0&&A!==void 0&&(g.metadata.rotation!==void 0&&g.metadata.rotation%180===90&&([S,A]=[A,S]),t+=`,RESOLUTION=${S}x${A}`)}!d&&g.metadata.frameRate!==void 0&&(t+=`,FRAME-RATE=${+g.metadata.frameRate.toFixed(3)}`)}if(!d){const b=new Map;for(const k of l.references){m(k.groupId!==null);const S=k.playlist.tracks[0].type;b.set(S,k.groupId)}for(const[k,S]of b)t+=`,${k.toUpperCase()}="${S}"`}d?(t+=`,URI="${l.playlist.path}"`,t+=`
|
|
492
|
+
`):(t+=`
|
|
493
|
+
`,t+=`${l.playlist.path}
|
|
494
|
+
`)}else{m(l.playlist.tracks.length===1);const d=l.playlist.tracks[0],h=d.type;let p=d.metadata.name??null;const y=d.metadata.languageCode,f=d.metadata.disposition;(s===null||l.groupId!==s)&&(n=0,t+=`
|
|
495
|
+
`,a=!1),s=l.groupId,n++,t+=`#EXT-X-MEDIA:TYPE=${h.toUpperCase()},GROUP-ID="${l.groupId}"`,p!==null&&/[\n\r"]/.test(p)&&(console.warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),p=null),p??(p=`${y??l.groupId}-${n}`),t+=`,NAME="${p}"`,y!==void 0&&(t+=`,LANGUAGE="${y}"`);const w=(f==null?void 0:f.primary)??!1,g=(f==null?void 0:f.default)??!0,b=(f==null?void 0:f.forced)??!1;if(w&&!a&&(t+=",DEFAULT=YES",a=!0),(w||g)&&(t+=",AUTOSELECT=YES"),b&&(t+=",FORCED=YES"),h==="audio"){const k=this.trackDatas.find(A=>A.track===d),S=k==null?void 0:k.info.decoderConfig;S&&(t+=`,CHANNELS="${S.numberOfChannels}"`)}l.noUri||(t+=`,URI="${l.playlist.path}"`),t+=`
|
|
496
|
+
`}(u=(c=this.format._options).onMaster)==null||u.call(c,t);const o=await this.mutex.acquire();try{let l;if(this.numWrittenMasterPlaylists===0)l=await this.output._getRootWriter(!0);else{const d=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:Ir});l=new Ei(d,!0),l.start()}l.write(le.encode(t)),await l.flush(),await l.finalize(),this.numWrittenMasterPlaylists++}finally{o()}}async tryWriteMasterPlaylist(){m(this.isLive);for(const e of this.playlists)if(e.writtenSegments.length===0&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){(await Promise.all(this.playlists.map(t=>t.mutex.acquire()))).forEach(t=>t());for(const t of this.trackDatas)t.closed=!0;await Promise.all(this.playlists.map(t=>t.done?Promise.resolve():this.advancePlaylist(t))),this.isLive||await this.writeMasterPlaylist()}}const Sm=i=>{if(typeof i!="string")throw new TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},Do=i=>{if(typeof i!="string")throw new TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Segment paths cannot contain line feed or carriage return characters.")},Am=i=>{if(typeof i!="string")throw new TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(i))throw new TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},Li=i=>({n:i.id,tracks:i.tracks,segmentFormat:i.segmentFormat});/*!
|
|
497
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
498
|
+
*
|
|
499
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
500
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
501
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
502
|
+
*/class Ye{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>Se.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>Ce.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>dt.includes(e))}_codecUnsupportedHint(e){return""}}class ga extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.fastStart!==void 0&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw new TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(e.minimumFragmentDuration!==void 0&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw new TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(e.onFtyp!==void 0&&typeof e.onFtyp!="function")throw new TypeError("options.onFtyp, when provided, must be a function.");if(e.onMoov!==void 0&&typeof e.onMoov!="function")throw new TypeError("options.onMoov, when provided, must be a function.");if(e.onMdat!==void 0&&typeof e.onMdat!="function")throw new TypeError("options.onMdat, when provided, must be a function.");if(e.onMoof!==void 0&&typeof e.onMoof!="function")throw new TypeError("options.onMoof, when provided, must be a function.");if(e.metadataFormat!==void 0&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:4294967295},audio:{min:0,max:4294967295},subtitle:{min:0,max:4294967295},total:{min:1,max:4294967295}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new em(e,this)}}class zl extends ga{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Se,...rr,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...dt]}_codecUnsupportedHint(e){return new Ul().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class zo extends ga{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...Se,...rr,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...dt]}}class Ul extends ga{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...Se,...Ce]}_codecUnsupportedHint(e){return new zl().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class Uo extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");if(e.minimumClusterDuration!==void 0&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw new TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(e.onEbmlHeader!==void 0&&typeof e.onEbmlHeader!="function")throw new TypeError("options.onEbmlHeader, when provided, must be a function.");if(e.onSegmentHeader!==void 0&&typeof e.onSegmentHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");if(e.onCluster!==void 0&&typeof e.onCluster!="function")throw new TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new sm(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:1,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...Se,...rr,...Pe.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...dt]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class No extends Uo{constructor(e){super(e)}getSupportedCodecs(){return[...Se.filter(e=>["vp8","vp9","av1"].includes(e)),...Ce.filter(e=>["opus","vorbis"].includes(e)),...dt]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new Uo().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class sp extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.xingHeader!==void 0&&typeof e.xingHeader!="boolean")throw new TypeError("options.xingHeader, when provided, must be a boolean.");if(e.onXingFrame!==void 0&&typeof e.onXingFrame!="function")throw new TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new am(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}get supportsTimestampedMediaData(){return!1}}class np extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.large!==void 0&&typeof e.large!="boolean")throw new TypeError("options.large, when provided, must be a boolean.");if(e.metadataFormat!==void 0&&!["info","id3"].includes(e.metadataFormat))throw new TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(e.onHeader!==void 0&&typeof e.onHeader!="function")throw new TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new pm(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}get supportsTimestampedMediaData(){return!1}}class ap extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.maximumPageDuration!==void 0&&(!Number.isFinite(e.maximumPageDuration)||e.maximumPageDuration<=0))throw new TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(e.onPage!==void 0&&typeof e.onPage!="function")throw new TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cm(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:4294967296},subtitle:{min:0,max:0},total:{min:1,max:4294967296}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...Ce.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class op extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onFrame!==void 0&&typeof e.onFrame!="function")throw new TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new vh(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}get supportsTimestampedMediaData(){return!1}}class cp extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.appendOnly!==void 0&&typeof e.appendOnly!="boolean")throw new TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=e}_createMuxer(e){return new Rh(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}get supportsTimestampedMediaData(){return!1}}class lp extends Ye{constructor(e={}){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(e.onPacket!==void 0&&typeof e.onPacket!="function")throw new TypeError("options.onPacket, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new dm(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:1,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...Se.filter(e=>["avc","hevc"].includes(e)),...Ce.filter(e=>["aac","mp3","ac3","eac3"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class up extends Ye{constructor(e){if(!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.segmentFormat instanceof Ye)&&(!Array.isArray(e.segmentFormat)||e.segmentFormat.length===0||!e.segmentFormat.every(t=>t instanceof Ye)))throw new TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(e.targetDuration!==void 0&&(typeof e.targetDuration!="number"||e.targetDuration<=0))throw new TypeError("options.targetDuration, when provided, must be a positive number.");if(e.singleFilePerPlaylist!==void 0&&typeof e.singleFilePerPlaylist!="boolean")throw new TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(e.live!==void 0&&typeof e.live!="boolean")throw new TypeError("options.live, when provided, must be a boolean.");if(e.maxLiveSegmentCount!==void 0&&(typeof e.maxLiveSegmentCount!="number"||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw new TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(e.getPlaylistPath!==void 0&&typeof e.getPlaylistPath!="function")throw new TypeError("options.getPlaylistPath, when provided, must be a function.");if(e.getSegmentPath!==void 0&&typeof e.getSegmentPath!="function")throw new TypeError("options.getSegmentPath, when provided, must be a function.");if(e.getInitPath!==void 0&&typeof e.getInitPath!="function")throw new TypeError("options.getInitPath, when provided, must be a function.");if(e.onMaster!==void 0&&typeof e.onMaster!="function")throw new TypeError("options.onMaster, when provided, must be a function.");if(e.onPlaylist!==void 0&&typeof e.onPlaylist!="function")throw new TypeError("options.onPlaylist, when provided, must be a function.");if(e.onSegment!==void 0&&typeof e.onSegment!="function")throw new TypeError("options.onSegment, when provided, must be a function.");if(e.onInit!==void 0&&typeof e.onInit!="function")throw new TypeError("options.onInit, when provided, must be a function.");if(e.onSegmentPopped!==void 0&&typeof e.onSegmentPopped!="function")throw new TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new Tm(e,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return Ir}getSupportedCodecs(){return[...new Set(Pr(this._options.segmentFormat).flatMap(t=>t.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,r=!1;for(const s of Pr(this._options.segmentFormat)){const n=s.getSupportedTrackCounts();e||(e=n.video.max>0),t||(t=n.audio.max>0),r||(r=n.subtitle.max>0)}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:1,max:1/0}}}get supportsVideoRotationMetadata(){return Pr(this._options.segmentFormat).some(e=>e.supportsVideoRotationMetadata)}get supportsTimestampedMediaData(){return!0}_codecUnsupportedHint(e){return" Using different segment formats may grant support for this codec."}}/*!
|
|
503
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
504
|
+
*
|
|
505
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
506
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
507
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
508
|
+
*/const xm=["video","audio","subtitle"];class Di{constructor(e,t,r,s,n){this.id=e,this.output=t,this.type=r,this.source=s,this.metadata=n}isVideoTrack(){return this.type==="video"}isAudioTrack(){return this.type==="audio"}isSubtitleTrack(){return this.type==="subtitle"}canBePairedWith(e){if(!(e instanceof Di))throw new TypeError("other must be an OutputTrack.");if(this===e)return!1;const t=Pr(this.metadata.group),r=Pr(e.metadata.group);for(const s of t)if(this.type!==e.type&&r.some(o=>s===o)||r.some(o=>s._pairedGroups.has(o)))return!0;return!1}}class Pm extends Di{constructor(e,t,r,s){super(e,t,"video",r,s)}}class Cm extends Di{constructor(e,t,r,s){super(e,t,"audio",r,s)}}class _m extends Di{constructor(e,t,r,s){super(e,t,"subtitle",r,s)}}class nt{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof nt))throw new TypeError("other must be an OutputTrackGroup.");if(this===e)throw new TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}const tn=i=>{if(!i||typeof i!="object")throw new TypeError("metadata must be an object.");if(i.languageCode!==void 0&&!bi(i.languageCode))throw new TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(i.name!==void 0&&typeof i.name!="string")throw new TypeError("metadata.name, when provided, must be a string.");if(i.disposition!==void 0&&cu(i.disposition),i.maximumPacketCount!==void 0&&(!Number.isInteger(i.maximumPacketCount)||i.maximumPacketCount<0))throw new TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(i.group!==void 0&&!(i.group instanceof nt)&&(!Array.isArray(i.group)||i.group.some(e=>!(e instanceof nt))))throw new TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class Mn extends fs{get target(){const e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw new TypeError(e);const t=this._getRootTarget();if(t instanceof Promise)throw new TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new nt,this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._tracks=[],this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new lr,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.format instanceof Ye))throw new TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof Le||e.target instanceof zt))throw new TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof Le&&this._rememberTarget(e.target),e.initTarget!==void 0&&!(e.initTarget instanceof Le)&&typeof e.initTarget!="function")throw new Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(e.onFinalize!==void 0&&typeof e.onFinalize!="function")throw new TypeError("options.onFinalize, when provided, must be a function.");this.format=e.format,this._target=e.target,this._onFinalize=e.onFinalize??null,this._initTarget=e.initTarget??null,this._initTarget instanceof Le&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){m(this._target instanceof zt);const t=this._target.getTarget(e),r=s=>{if(!(s instanceof Le))throw new TypeError("getTarget must return a Target.");return s};return t instanceof Promise?t.then(r):r(t)}async _getTarget(e){m(this._target instanceof zt);const t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),this.state==="canceled"?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(m(this._initTarget!==null),this._initTarget instanceof Le)return this._initTarget;const e=await this._initTarget();return this.state==="canceled"?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return this._initTarget!==null}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof Le)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;const e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),r=s=>(this.state==="canceled"?s._close():this._rememberTarget(s),this._emit("target",{target:s,request:e,isRoot:!0}),this._rootTarget=s,s);return t instanceof Promise?this._rootTargetPromise=t.then(r):r(t)}_getRootWriter(e){return this._rootWriterPromise??(this._rootWriterPromise=(async()=>{const t=await this._getRootTarget(),r=new Ei(t,typeof e=="boolean"?e:e(t));return r.start(),r})())}addVideoTrack(e,t={}){if(!(e instanceof Ri))throw new TypeError("source must be a VideoSource.");if(tn(t),t.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw new TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw new Error(`${this.format._name} does not support video rotation metadata.`);if(t.frameRate!==void 0&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw new TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);const r={...t};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Pm(this._tracks.length+1,this,e,r))}addAudioTrack(e,t={}){if(!(e instanceof Mi))throw new TypeError("source must be an AudioSource.");tn(t);const r={...t};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new Cm(this._tracks.length+1,this,e,r))}addSubtitleTrack(e,t={}){if(!(e instanceof Dl))throw new TypeError("source must be a SubtitleSource.");tn(t);const r={...t};return r.group??(r.group=this.defaultTrackGroup),this._addTrack(new _m(this._tracks.length+1,this,e,r))}setMetadataTags(e){if(cn(e),this.state!=="pending")throw new Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if(this.state!=="pending")throw new Error("Cannot add track after output has been started or canceled.");if(e.source._connectedTrack)throw new Error("Source is already used for a track.");const t=this.format.getSupportedTrackCounts(),r=this._tracks.reduce((a,o)=>a+(o.type===e.type?1:0),0),s=t[e.type].max;if(r===s)throw new Error(s===0?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${s} ${e.type} track${s===1?"":"s"}.`);const n=t.total.max;if(this._tracks.length===n)throw new Error(`${this.format._name} does not support more than ${n} tracks${n===1?"":"s"} in total.`);if(e.isVideoTrack()){const a=this.format.getSupportedVideoCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){const a=this.format.getSupportedAudioCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){const a=this.format.getSupportedSubtitleCodecs();if(a.length===0)throw new Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!a.includes(e.source._codec))throw new Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${a.map(o=>`'${o}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this._tracks.push(e),e.source._connectedTrack=e,e}async start(){const e=this.format.getSupportedTrackCounts();for(const r of xm){const s=this._tracks.reduce((a,o)=>a+(o.type===r?1:0),0),n=e[r].min;if(s<n)throw new Error(n===e[r].max?`${this.format._name} requires exactly ${n} ${r} track${n===1?"":"s"}.`:`${this.format._name} requires at least ${n} ${r} track${n===1?"":"s"}.`)}const t=e.total.min;if(this._tracks.length<t)throw new Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${t===1?"":"s"}.`:`${this.format._name} requires at least ${t} track${t===1?"":"s"}.`);if(this.state==="canceled")throw new Error("Output has been canceled.");return this._startPromise?(console.warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";const r=await this._mutex.acquire();try{await this._muxer.start();const s=this._tracks.map(n=>n.source._start());await Promise.all(s)}finally{r()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return console.warn("Output has already been canceled."),this._cancelPromise;if(this.state==="finalizing"||this.state==="finalized"){this.state==="finalized"&&console.warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";const e=await this._mutex.acquire();try{const t=this._tracks.map(r=>r.source._flushOrWaitForOngoingClose(!0));await Promise.all(t),await Promise.all([...this._unfinalizedTargets].map(r=>r._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if(this.state==="pending")throw new Error("Cannot finalize before starting.");if(this.state==="canceled")throw new Error("Cannot finalize after canceling.");return this._finalizePromise?(console.warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";const e=await this._mutex.acquire();try{const t=this._tracks.map(r=>r.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(t),await this._muxer.finalize(),this._rootWriterPromise){const r=await this._rootWriterPromise;r.finalized||(await r.flush(),await r.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{e()}})()}}/*!
|
|
509
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
510
|
+
*
|
|
511
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
512
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
513
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
514
|
+
*/const Hi=i=>{if(!i||typeof i!="object")throw new TypeError("options.video, when provided, must be an object.");if((i==null?void 0:i.discard)!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.video.discard, when provided, must be a boolean.");if((i==null?void 0:i.forceTranscode)!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.video.forceTranscode, when provided, must be a boolean.");if((i==null?void 0:i.codec)!==void 0&&!Se.includes(i.codec))throw new TypeError(`options.video.codec, when provided, must be one of: ${Se.join(", ")}.`);if((i==null?void 0:i.bitrate)!==void 0&&!(i.bitrate instanceof Ke)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if((i==null?void 0:i.width)!==void 0&&(!Number.isInteger(i.width)||i.width<=0))throw new TypeError("options.video.width, when provided, must be a positive integer.");if((i==null?void 0:i.height)!==void 0&&(!Number.isInteger(i.height)||i.height<=0))throw new TypeError("options.video.height, when provided, must be a positive integer.");if((i==null?void 0:i.fit)!==void 0&&!["fill","contain","cover"].includes(i.fit))throw new TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if((i==null?void 0:i.width)!==void 0&&i.height!==void 0&&i.fit===void 0)throw new TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if((i==null?void 0:i.rotate)!==void 0&&![0,90,180,270].includes(i.rotate))throw new TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if((i==null?void 0:i.allowRotationMetadata)!==void 0&&typeof i.allowRotationMetadata!="boolean")throw new TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if((i==null?void 0:i.crop)!==void 0&&Pi(i.crop,"options.video."),(i==null?void 0:i.frameRate)!==void 0&&(!Number.isFinite(i.frameRate)||i.frameRate<=0))throw new TypeError("options.video.frameRate, when provided, must be a finite positive number.");if((i==null?void 0:i.alpha)!==void 0&&!["discard","keep"].includes(i.alpha))throw new TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if((i==null?void 0:i.keyFrameInterval)!==void 0&&(!Number.isFinite(i.keyFrameInterval)||i.keyFrameInterval<0))throw new TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if((i==null?void 0:i.process)!==void 0&&typeof i.process!="function")throw new TypeError("options.video.process, when provided, must be a function.");if((i==null?void 0:i.processedWidth)!==void 0&&(!Number.isInteger(i.processedWidth)||i.processedWidth<=0))throw new TypeError("options.video.processedWidth, when provided, must be a positive integer.");if((i==null?void 0:i.processedHeight)!==void 0&&(!Number.isInteger(i.processedHeight)||i.processedHeight<=0))throw new TypeError("options.video.processedHeight, when provided, must be a positive integer.");if((i==null?void 0:i.hardwareAcceleration)!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(i.hardwareAcceleration))throw new TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if((i==null?void 0:i.group)!==void 0&&!(i.group instanceof nt||Array.isArray(i.group)&&i.group.every(e=>e instanceof nt)))throw new TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},qi=i=>{if(!i||typeof i!="object")throw new TypeError("options.audio, when provided, must be an object.");if((i==null?void 0:i.discard)!==void 0&&typeof i.discard!="boolean")throw new TypeError("options.audio.discard, when provided, must be a boolean.");if((i==null?void 0:i.forceTranscode)!==void 0&&typeof i.forceTranscode!="boolean")throw new TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if((i==null?void 0:i.codec)!==void 0&&!Ce.includes(i.codec))throw new TypeError(`options.audio.codec, when provided, must be one of: ${Ce.join(", ")}.`);if((i==null?void 0:i.bitrate)!==void 0&&!(i.bitrate instanceof Ke)&&(!Number.isInteger(i.bitrate)||i.bitrate<=0))throw new TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if((i==null?void 0:i.numberOfChannels)!==void 0&&(!Number.isInteger(i.numberOfChannels)||i.numberOfChannels<=0))throw new TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if((i==null?void 0:i.sampleRate)!==void 0&&(!Number.isInteger(i.sampleRate)||i.sampleRate<=0))throw new TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if((i==null?void 0:i.sampleFormat)!==void 0&&!["u8","s16","s32","f32"].includes(i.sampleFormat))throw new TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if((i==null?void 0:i.process)!==void 0&&typeof i.process!="function")throw new TypeError("options.audio.process, when provided, must be a function.");if((i==null?void 0:i.processedNumberOfChannels)!==void 0&&(!Number.isInteger(i.processedNumberOfChannels)||i.processedNumberOfChannels<=0))throw new TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if((i==null?void 0:i.processedSampleRate)!==void 0&&(!Number.isInteger(i.processedSampleRate)||i.processedSampleRate<=0))throw new TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if((i==null?void 0:i.group)!==void 0&&!(i.group instanceof nt||Array.isArray(i.group)&&i.group.every(e=>e instanceof nt)))throw new TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},rn=2,sn=48e3;class Nl{static async init(e){const t=new Nl(e);return await t._init(),t}constructor(e){var s,n,a;if(this._addedCounts={video:0,audio:0,subtitle:0},this._totalTrackCount=0,this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPromises=[],this._executed=!1,this._synchronizer=new Em,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||typeof e!="object")throw new TypeError("options must be an object.");if(!(e.input instanceof _s))throw new TypeError("options.input must be an Input.");if(!(e.output instanceof Mn))throw new TypeError("options.output must be an Output.");if(e.tracks!==void 0&&e.tracks!=="all"&&e.tracks!=="primary")throw new TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(e.output._tracks.length>0||Object.keys(e.output._metadataTags).length>0||e.output.state!=="pending")throw new TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(e.video!==void 0&&typeof e.video!="function")if(Array.isArray(e.video))for(const o of e.video)Hi(o);else Hi(e.video);if(e.audio!==void 0&&typeof e.audio!="function")if(Array.isArray(e.audio))for(const o of e.audio)qi(o);else qi(e.audio);if(e.trim!==void 0&&(!e.trim||typeof e.trim!="object"))throw new TypeError("options.trim, when provided, must be an object.");if(((s=e.trim)==null?void 0:s.start)!==void 0&&!Number.isFinite(e.trim.start))throw new TypeError("options.trim.start, when provided, must be a finite number.");if(((n=e.trim)==null?void 0:n.end)!==void 0&&!Number.isFinite(e.trim.end))throw new TypeError("options.trim.end, when provided, must be a finite number.");if(((a=e.trim)==null?void 0:a.start)!==void 0&&e.trim.end!==void 0&&e.trim.start>=e.trim.end)throw new TypeError("options.trim.start must be less than options.trim.end.");if(e.tags!==void 0&&(typeof e.tags!="object"||!e.tags)&&typeof e.tags!="function")throw new TypeError("options.tags, when provided, must be an object or a function.");if(typeof e.tags=="object"&&cn(e.tags),e.showWarnings!==void 0&&typeof e.showWarnings!="boolean")throw new TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this.input=e.input,this.output=e.output;const{promise:t,resolve:r}=ge();this._started=t,this._start=r}async _init(){var p,y;const e=await this.input.getFormat();let t,r=this._options.tracks;if(r===void 0&&(r=e.name.includes("(HLS)")?"primary":"all"),r==="all")t=await this.input.getTracks();else if(r==="primary"){const f=await this.input.getPrimaryVideoTrack(),w=await this.input.getPrimaryAudioTrack();t=[f,w].filter(g=>g!==null)}else De(r),m(!1);const s=this.output.format.getSupportedTrackCounts();let n=1,a=1;const o=[],c=[];for(const f of t){let w;if(f.isVideoTrack())if(this._options.video)if(typeof this._options.video=="function"){const k=await this._options.video(f,n)??{};if(Array.isArray(k))for(const S of k)Hi(S);else Hi(k);w=Array.isArray(k)?k:[k],n++}else w=Array.isArray(this._options.video)?this._options.video:[this._options.video];else w=[{}];else if(f.isAudioTrack())if(this._options.audio)if(typeof this._options.audio=="function"){const k=await this._options.audio(f,a)??{};if(Array.isArray(k))for(const S of k)qi(S);else qi(k);w=Array.isArray(k)?k:[k],a++}else w=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else w=[{}];else m(!1);const g=w.filter(k=>k.discard);for(const k of g)this.discardedTracks.push({track:f,reason:"discarded_by_user",trackOptions:k});if(w.length===g.length){w.length===0&&this.discardedTracks.push({track:f,reason:"discarded_by_user",trackOptions:{}});continue}const b=w.filter(k=>!k.discard);o.push(f),c.push(b)}((p=this._options.trim)==null?void 0:p.start)!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(((y=this._options.trim)==null?void 0:y.end)??1/0,this._startTimestamp);for(let f=0;f<o.length;f++){const w=o[f],g=c[f];for(const b of g){if(this._totalTrackCount===s.total.max){this.discardedTracks.push({track:w,reason:"max_track_count_reached",trackOptions:b});continue}if(this._addedCounts[w.type]===s[w.type].max){this.discardedTracks.push({track:w,reason:"max_track_count_of_type_reached",trackOptions:b});continue}const k=this._nextOutputTrackId++;w.isVideoTrack()?await this._processVideoTrack(w,b,k):w.isAudioTrack()?await this._processAudioTrack(w,b,k):m(!1)}}for(let f=0;f<this.utilizedTracks.length-1;f++)for(let w=f+1;w<this.utilizedTracks.length;w++){const g=this.utilizedTracks[f],b=this.utilizedTracks[w],k=this._outputOwnTrackGroups[f],S=this._outputOwnTrackGroups[w];m(k!==void 0),m(S!==void 0),k&&S&&g.canBePairedWith(b)&&k.pairWith(S)}const u=await this.input.getMetadataTags();let l;if(this._options.tags){const f=typeof this._options.tags=="function"?await this._options.tags(u):this._options.tags;cn(f),l=f}else l=u;const d=e.mimeType===this.output.format.mimeType,h=u.raw===l.raw;if(u.raw&&h&&!d&&delete l.raw,this.output.setMetadataTags(l),this.isValid=this._totalTrackCount>=s.total.min&&this._addedCounts.video>=s.video.min&&this._addedCounts.audio>=s.audio.min&&this._addedCounts.subtitle>=s.subtitle.min,this._options.showWarnings??!0){const f=[],w=this.discardedTracks.filter(g=>g.reason!=="discarded_by_user");w.length>0&&f.push("Some tracks had to be discarded from the conversion:",w),this.isValid||(f.length>0&&f.push(`
|
|
515
|
+
|
|
516
|
+
`),f.push(this._getInvalidityExplanation().join(""))),f.length>0&&console.warn(...f)}}_getInvalidityExplanation(){const e=[];if(this.discardedTracks.length===0)e.push("Due to missing tracks, this conversion cannot be executed.");else{const t=this.discardedTracks.every(r=>r.reason==="discarded_by_user"||r.reason==="no_encodable_target_codec")&&this.discardedTracks.some(r=>r.reason==="no_encodable_target_codec");if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){const r=this.discardedTracks.flatMap(n=>n.reason==="discarded_by_user"?[]:n.track.type==="video"?this.output.format.getSupportedVideoCodecs():n.track.type==="audio"?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs()),s=[...new Set(r)];s.length===1?e.push(`
|
|
517
|
+
Tracks were discarded because your environment is not able to encode '${s[0]}'.`):e.push(`
|
|
518
|
+
Tracks were discarded because your environment is not able to encode any of the following codecs: ${s.map(n=>`'${n}'`).join(", ")}.`),s.includes("mp3")&&e.push(`
|
|
519
|
+
The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),s.includes("aac")&&e.push(`
|
|
520
|
+
The @mediabunny/aac-encoder extension package provides support for encoding AAC.`),(s.includes("ac3")||s.includes("eac3"))&&e.push(`
|
|
521
|
+
The @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3.`),s.includes("flac")&&e.push(`
|
|
522
|
+
The @mediabunny/flac-encoder extension package provides support for encoding FLAC.`)}else e.push(`
|
|
523
|
+
Check the discardedTracks field for more info.`)}return e}async execute(){var e,t;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.
|
|
524
|
+
`+this._getInvalidityExplanation().join(""));if(this._executed)throw new Error("Conversion cannot be executed twice.");this._executed=!0;for(const r of this._outputTrackIds)this._synchronizer.declareTrack(r);if(this.onProgress){const s=[...new Set(this.utilizedTracks)].map(async a=>await a.isLive()?1/0:await a.getDurationFromMetadata()??await a.computeDuration()),n=Math.max(0,...await Promise.all(s));this._computeProgress=!0,this._totalDuration=Math.min(n-this._startTimestamp,this._endTimestamp-this._startTimestamp);for(const a of this._outputTrackIds)this._maxTimestamps.set(a,0);(e=this.onProgress)==null||e.call(this,0,0)}await this.output.start(),this._start();try{await Promise.all(this._trackPromises)}catch(r){throw this._canceled||this.cancel(),r}if(this._canceled)throw new Im;if(await this.output.finalize(),this._computeProgress){const r=Math.min(...this._maxTimestamps.values());(t=this.onProgress)==null||t.call(this,1,r)}}async cancel(){if(!(this.output.state==="finalizing"||this.output.state==="finalized")){if(this._canceled){console.warn("Conversion already canceled.");return}this._canceled=!0,await this.output.cancel()}}async _processVideoTrack(e,t,r){const s=await e.getCodec();if(!s){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let n;const a=await e.getRotation(),o=Er(a+(t.rotate??0));let c=o;const u=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??!0),l=await e.getSquarePixelWidth(),d=await e.getSquarePixelHeight(),[h,p]=o%180===0?[l,d]:[d,l];let y=t.crop;y&&(y=as(y,h,p));const[f,w]=y?[y.width,y.height]:[h,p];let g=f,b=w;const k=g/b;t.width!==void 0&&t.height===void 0?(g=dr(t.width),b=dr(Math.round(g/k))):t.width===void 0&&t.height!==void 0?(b=dr(t.height),g=dr(Math.round(b*k))):t.width!==void 0&&t.height!==void 0&&(g=dr(t.width),b=dr(t.height));const S=await e.getFirstTimestamp();let A=this.output.format.getSupportedVideoCodecs();const _=!!t.forceTranscode||S<this._startTimestamp||!!t.frameRate||t.keyFrameInterval!==void 0||t.process!==void 0||t.bitrate!==void 0||!A.includes(s)||t.codec&&t.codec!==s||g!==f||b!==w||o!==0&&!u||!!y,I=t.alpha??"discard";if(_){if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}t.codec&&(A=A.filter(O=>O===t.codec));const M=t.bitrate??ho,R=await lh(A,{width:t.process&&t.processedWidth?t.processedWidth:g,height:t.process&&t.processedHeight?t.processedHeight:b,bitrate:M});if(!R){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}const L={codec:R,bitrate:M,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:I,hardwareAcceleration:t.hardwareAcceleration,transform:{}};m(L.transform);let H=g!==f||b!==w||o!==0&&(!u||t.process!==void 0)||!!y||l!==await e.getCodedWidth()||d!==await e.getCodedHeight();if(!H){const O=new Mn({format:new zl,target:new Il}),ee=new Ro(L);O.addVideoTrack(ee),await O.start();const xe=await new En(e).getSample(S);if(xe)try{await ee.add(xe),xe.close(),await O.finalize()}catch(Ue){console.info("Error when probing encoder support. Falling back to rerender path.",Ue),H=!0,O.cancel()}else await O.cancel()}t.frameRate&&(L.transform.frameRate=t.frameRate),H&&(c=0,L.transform.width=g,L.transform.height=b,L.transform.fit=t.fit??"fill",L.transform.rotate=Er(o-a),L.transform.crop=y,L.transform.alpha=I);const q=new Ro(L);n=q,this._trackPromises.push((async()=>{await this._started;const O=new En(e);for await(const ee of O.samples(this._startTimestamp,this._endTimestamp)){if(this._canceled){ee.close();return}const ue=Math.max(ee.timestamp-this._startTimestamp,0);ee.setTimestamp(ue),await this._registerVideoSample(t,r,q,ee),ee.close()}q.close(),this._synchronizer.closeTrack(r)})())}else{const v=new Rl(s);n=v,this._trackPromises.push((async()=>{await this._started;const M=new Ii(e),L={decoderConfig:await e.getDecoderConfig()??void 0};for await(const H of M.packets(void 0,void 0,{verifyKeyPackets:!0})){if(this._canceled)return;if(H.timestamp>=this._endTimestamp)break;const q=H.clone({timestamp:H.timestamp-this._startTimestamp,sideData:I==="discard"?{}:H.sideData});m(q.timestamp>=0),this._reportProgress(r,q.timestamp+q.duration),await v.add(q,L),this._synchronizer.shouldWait(r,q.timestamp)&&await this._synchronizer.wait(q.timestamp)}v.close(),this._synchronizer.closeTrack(r)})())}let C=null;t.group||(C=new nt);const P=await e.getLanguageCode();this.output.addVideoTrack(n,{frameRate:t.frameRate,languageCode:bi(P)?P:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:c,group:C??t.group}),this._addedCounts.video++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(C)}async _registerVideoSample(e,t,r,s){if(this._canceled)return;this._reportProgress(t,s.timestamp+s.duration);let n;if(!e.process)n=[s];else{let a=e.process(s);a instanceof Promise&&(a=await a),Array.isArray(a)||(a=a===null?[]:[a]),n=a.map(o=>o instanceof Ae?o:typeof VideoFrame<"u"&&o instanceof VideoFrame?new Ae(o):new Ae(o,{timestamp:s.timestamp,duration:s.duration}))}try{for(const a of n){if(this._canceled)break;await r.add(a),this._synchronizer.shouldWait(t,a.timestamp)&&await this._synchronizer.wait(a.timestamp)}}finally{for(const a of n)a!==s&&a.close()}}async _processAudioTrack(e,t,r){const s=await e.getCodec();if(!s){this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});return}let n;const a=await e.getNumberOfChannels(),o=await e.getSampleRate(),c=await e.getFirstTimestamp();let u=t.numberOfChannels??a,l=t.sampleRate??o,d=u!==a||l!==o||c<this._startTimestamp||c>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,h=this.output.format.getSupportedAudioCodecs();if(!t.forceTranscode&&!t.bitrate&&!d&&h.includes(s)&&(!t.codec||t.codec===s)&&!t.process&&t.sampleFormat===void 0){const f=new Ml(s);n=f,this._trackPromises.push((async()=>{await this._started;const w=new Ii(e),b={decoderConfig:await e.getDecoderConfig()??void 0};for await(const k of w.packets()){if(this._canceled)return;if(k.timestamp>=this._endTimestamp)break;const S=k.clone({timestamp:k.timestamp-this._startTimestamp});m(S.timestamp>=0),this._reportProgress(r,S.timestamp+S.duration),await f.add(S,b),this._synchronizer.shouldWait(r,S.timestamp)&&await this._synchronizer.wait(S.timestamp)}f.close(),this._synchronizer.closeTrack(r)})())}else{if(!await e.canDecode()){this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});return}let w=null;t.codec&&(h=h.filter(k=>k===t.codec));const g=t.bitrate??ho,b=await In(h,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:u,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:l,bitrate:g});if(!b.some(k=>rr.includes(k))&&h.some(k=>rr.includes(k))&&(u!==rn||l!==sn)){const S=(await In(h,{numberOfChannels:rn,sampleRate:sn,bitrate:g})).find(A=>rr.includes(A));S&&(d=!0,w=S,u=rn,l=sn)}else w=b[0]??null;if(w===null){this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});return}if(d)n=this._resampleAudio(e,t,r,w,u,l,g);else{const k=new Mo({codec:w,bitrate:g});n=k,this._trackPromises.push((async()=>{await this._started;const S=new vn(e);for await(const A of S.samples(void 0,this._endTimestamp)){if(this._canceled){A.close();return}A.setTimestamp(A.timestamp-this._startTimestamp),await this._registerAudioSample(t,r,k,A),A.close()}k.close(),this._synchronizer.closeTrack(r)})())}}let p=null;t.group||(p=new nt);const y=await e.getLanguageCode();this.output.addAudioTrack(n,{languageCode:bi(y)?y:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:p??t.group}),this._addedCounts.audio++,this._totalTrackCount++,this.utilizedTracks.push(e),this._outputTrackIds.push(r),this._outputOwnTrackGroups.push(p)}async _registerAudioSample(e,t,r,s){if(this._canceled)return;let n=s;e.sampleFormat!==void 0&&cl(n.format)!==e.sampleFormat&&(n=ll(n,e.sampleFormat)),this._reportProgress(t,n.timestamp+n.duration);let a;if(!e.process)a=[n];else{let o=e.process(n);if(o instanceof Promise&&(o=await o),Array.isArray(o)||(o=o===null?[]:[o]),!o.every(c=>c instanceof Ee))throw new TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");a=o}try{for(const o of a){if(this._canceled)break;await r.add(o),this._synchronizer.shouldWait(t,o.timestamp)&&await this._synchronizer.wait(o.timestamp)}}finally{n!==s&&n.close();for(const o of a)o!==s&&o.close()}}_resampleAudio(e,t,r,s,n,a,o){const c=new Mo({codec:s,bitrate:o});return this._trackPromises.push((async()=>{await this._started;const u=new Fl({targetNumberOfChannels:n,targetSampleRate:a,startTime:this._startTimestamp,endTime:this._endTimestamp,onSample:async h=>{m(h.timestamp>=this._startTimestamp),h.setTimestamp(h.timestamp-this._startTimestamp),await this._registerAudioSample(t,r,c,h),h.close()}}),d=new vn(e).samples(this._startTimestamp,this._endTimestamp);for await(const h of d){if(this._canceled){h.close();return}await u.add(h),h.close()}await u.finalize(),c.close(),this._synchronizer.closeTrack(r)})()),c}_reportProgress(e,t){var n;if(!this._computeProgress)return;m(this._totalDuration!==null),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));const r=Math.min(...this._maxTimestamps.values()),s=Ie(r/this._totalDuration,0,1);s!==this._lastProgress&&(this._lastProgress=s,(n=this.onProgress)==null||n.call(this,s,r))}}class Im extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}const Vo=1;class Em{constructor(){this.maxTimestamps=new Map,this.resolvers=[]}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){const r=this.maxTimestamps.get(e);m(r!==void 0),this.maxTimestamps.set(e,Math.max(t,r));const s=this.computeMinAndMaybeResolve();return t-s>Vo}wait(e){const{promise:t,resolve:r}=ge();return this.resolvers.push({timestamp:e,resolve:r}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}computeMinAndMaybeResolve(){let e=1/0;for(const[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){const r=this.resolvers[t];r.timestamp-e<Vo&&(r.resolve(),this.resolvers.splice(t,1),t--)}return e}}/*!
|
|
525
|
+
* Copyright (c) 2026-present, Vanilagy and contributors
|
|
526
|
+
*
|
|
527
|
+
* This Source Code Form is subject to the terms of the Mozilla Public
|
|
528
|
+
* License, v. 2.0. If a copy of the MPL was not distributed with this
|
|
529
|
+
* file, You can obtain one at https://mozilla.org/MPL/2.0/.
|
|
530
|
+
*/const Vl=Symbol.for("mediabunny loaded");globalThis[Vl]&&console.error(`[WARNING]
|
|
531
|
+
Mediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly.`);globalThis[Vl]=!0;export{tl as ADTS,Rm as ALL_FORMATS,xm as ALL_TRACK_TYPES,Ce as AUDIO_CODECS,Od as AdtsInputFormat,op as AdtsOutputFormat,Ym as AppendOnlyStreamTarget,On as AttachedFile,Xm as AudioBufferSink,tp as AudioBufferSource,Ee as AudioSample,ii as AudioSampleResource,vn as AudioSampleSink,Mo as AudioSampleSource,Mi as AudioSource,ml as BaseMediaSampleSink,Fm as BlobSource,Bm as BufferSource,Zs as BufferTarget,Qm as CanvasSink,Jm as CanvasSource,zo as CmafOutputFormat,vm as ConcurrentRunner,Nl as Conversion,Im as ConversionCanceledError,dh as CustomAudioDecoder,fh as CustomAudioEncoder,xd as CustomPathedSource,uh as CustomVideoDecoder,hh as CustomVideoEncoder,Ml as EncodedAudioPacketSource,de as EncodedPacket,Ii as EncodedPacketSink,Rl as EncodedVideoPacketSource,fs as EventEmitter,Kd as FLAC,jc as FilePathSource,Zm as FilePathTarget,Vd as FlacInputFormat,cp as FlacOutputFormat,il as HLS,Mm as HLS_FORMATS,Yc as HlsInputFormat,up as HlsOutputFormat,_s as Input,Cs as InputAudioTrack,We as InputDisposedError,ft as InputFormat,Fi as InputTrack,Ps as InputVideoTrack,Xc as IsobmffInputFormat,ga as IsobmffOutputFormat,Ld as MATROSKA,el as MP3,Zc as MP4,rl as MPEG_TS,$c as MatroskaInputFormat,fa as MediaSource,rp as MediaStreamAudioTrackSource,ep as MediaStreamVideoTrackSource,Uo as MkvOutputFormat,Ul as MovOutputFormat,zd as Mp3InputFormat,sp as Mp3OutputFormat,Rd as Mp4InputFormat,zl as Mp4OutputFormat,Wd as MpegTsInputFormat,lp as MpegTsOutputFormat,rr as NON_PCM_AUDIO_CODECS,Il as NullTarget,jd as OGG,Nd as OggInputFormat,ap as OggOutputFormat,Mn as Output,Cm as OutputAudioTrack,Ye as OutputFormat,_m as OutputSubtitleTrack,Di as OutputTrack,nt as OutputTrackGroup,Pm as OutputVideoTrack,Pe as PCM_AUDIO_CODECS,Nr as PathedSource,zt as PathedTarget,Jc as QTFF,ho as QUALITY_HIGH,Vm as QUALITY_LOW,Om as QUALITY_MEDIUM,Wm as QUALITY_VERY_HIGH,Nm as QUALITY_VERY_LOW,Ke as Quality,Md as QuickTimeInputFormat,Ed as RangedSource,Yf as RangedTarget,Id as ReadableStreamSource,Cr as RichImageData,dt as SUBTITLE_CODECS,$e as Source,ea as SourceRef,_d as StreamSource,_l as StreamTarget,Dl as SubtitleSource,Le as Target,ip as TextSubtitleSource,go as UnsupportedInputFormatError,qc as UrlSource,Se as VIDEO_CODECS,xn as VIDEO_SAMPLE_PIXEL_FORMATS,Ae as VideoSample,Hs as VideoSampleColorSpace,Kt as VideoSampleResource,En as VideoSampleSink,Ro as VideoSampleSource,Ri as VideoSource,qd as WAVE,Hd as WEBM,np as WavOutputFormat,Ud as WaveInputFormat,Dd as WebMInputFormat,No as WebMOutputFormat,$m as asc,Dm as canDecode,nl as canDecodeAudio,sl as canDecodeVideo,Lm as canEncode,aa as canEncodeAudio,oa as canEncodeSubtitles,na as canEncodeVideo,po as desc,Yd as getDecodableAudioCodecs,zm as getDecodableCodecs,$d as getDecodableVideoCodecs,In as getEncodableAudioCodecs,Hm as getEncodableCodecs,ch as getEncodableSubtitleCodecs,oh as getEncodableVideoCodecs,qm as getFirstEncodableAudioCodec,jm as getFirstEncodableSubtitleCodec,lh as getFirstEncodableVideoCodec,ni as prefer,Km as registerDecoder,Gm as registerEncoder,Um as registerVideoSampleTransformer};
|