PageSourceSearch

https://rehearsenow.ai/_next/static/chunks/8705.93f3e5d6abcd01e3.js

js rehearsenow.ai collected 2026-10-05 12:29:13 UTC 446,011 bytes, 1 lines download raw bytes

1try{!function(){var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},t=(new e.Error).stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf499ab7-b43d-4e75-b008-a47f01b9e4f3",e._sentryDebugIdIdentifier="sentry-dbid-bf499ab7-b43d-4e75-b008-a47f01b9e4f3")}()}catch(e){}"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[8705],{58705:(e,t,r)=>{function i(e){if(!e)throw Error("Assertion failed.")}r.d(t,{ALL_FORMATS:()=>az,AudioBufferSink:()=>sE,AudioBufferSource:()=>lf,BlobSource:()=>i$,BufferTarget:()=>oG,EncodedPacketSink:()=>sw,EncodedVideoPacketSource:()=>lu,Input:()=>sV,Mp4OutputFormat:()=>lk,Output:()=>lI,getFirstEncodableAudioCodec:()=>ls});let a=e=>{let t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw Error(`Invalid rotation ${e}.`)},s=e=>e&&e[e.length-1],n=e=>e>=0&&e<0x100000000,o=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},l=e=>{let t=o(e);return(1&t)==0?-(t>>1):t+1>>1},c=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),u=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),d=new TextDecoder,h=new TextEncoder,f=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),m={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},p=f(m),g={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},k=f(g),b={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},y=f(b),T=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,w=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class S{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let r=!1;e=()=>{r||(t(),this.pending--,r=!0)}}),r=this.currentPromise;return this.currentPromise=t,this.pending++,await r,e}}let P=/^[0-9a-fA-F]+$/,v=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),x=e=>{i(e.length%2==0);let t=new Uint8Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=parseInt(e.slice(r,r+2),16);return t},C=e=>(e=(e=(e=(e=(e=e>>1&0x55555555|(0x55555555&e)<<1)>>2&0x33333333|(0x33333333&e)<<2)>>4&0xf0f0f0f|(0xf0f0f0f&e)<<4)>>8&0xff00ff|(0xff00ff&e)<<8)>>16&65535|(65535&e)<<16)>>>0,I=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;i<=a;){let n=i+a>>1,o=r(e[n]);o===t?(s=n,a=n-1):o<t?i=n+1:a=n-1}return s},E=(e,t,r)=>{let i=0,a=e.length-1,s=-1;for(;i<=a;){let n=i+(a-i+1)/2|0;r(e[n])<=t?(s=n,i=n+1):a=n-1}return s},_=()=>{let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}},B=(e,t)=>{let r=e.indexOf(t);-1!==r&&e.splice(r,1)},A=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return e[r]},F=(e,t)=>{for(let r=e.length-1;r>=0;r--)if(t(e[r]))return r;return -1},M=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},R=e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError("Argument must be an iterable or async iterable.")},D=e=>{throw Error(`Unexpected value: ${e}`)},O=(e,t,r)=>{let i=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return r?i|a<<8|s<<16:i<<16|a<<8|s},N=(e,t,r)=>O(e,t,r)<<8>>8,z=(e,t,r,i)=>{r>>>=0,r&=0xffffff,i?(e.setUint8(t,255&r),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,r>>>16&255)):(e.setUint8(t,r>>>16&255),e.setUint8(t+1,r>>>8&255),e.setUint8(t+2,255&r))},U=(e,t,r,i)=>{(r=W(r,-8388608,8388607))<0&&(r=r+0x1000000&0xffffff),z(e,t,r,i)},L=(e,t)=>({async next(){let r=await e.next();return r.done?{value:void 0,done:!0}:{value:t(r.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),W=(e,t,r)=>
1Math.max(t,Math.min(r,e)),q=(e,t,r)=>e+(t-e)*r,V=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},H=(e,t)=>Math.round(e/t)*t,j=(e,t)=>Math.round(e*t)/t,$=(e,t)=>Math.floor(e/t)*t,K=e=>{let t=0;for(;e;)t++,e>>=1;return t},X=/^[a-z]{3}$/,G=e=>X.test(e),Q=1e6*(1+Number.EPSILON),Y=(e,t)=>{let r=e<0?-1:1,i=0,a=1,s=1,n=0,o=e=Math.abs(e);for(;;){let e=Math.floor(o),r=e*s+i,l=e*n+a;if(l>t||(i=s,a=n,s=r,n=l,!isFinite(o=1/(o-e))))break}return{num:r*s,den:n}};class J{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let Z=null,ee=()=>null!==Z?Z:Z=!!("undefined"!=typeof navigator&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),et=null,er=()=>null!==et?et:et="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),ei=null,ea=()=>null!==ei?ei:ei=!!("undefined"!=typeof navigator&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),es=null,en=()=>{if(null!==es)return es;if("undefined"==typeof navigator)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?es=Number(e[1]):null},eo=(e,t)=>-1!==e?e:t,el=(e,t,r,i)=>e<=i&&r<=t,ec=function*(e){for(let t in e){let r=e[t];void 0!==r&&(yield{key:t,value:r})}},eu=e=>{let t=atob(e),r=new Uint8Array(t.length);for(let e=0;e<t.length;e++)r[e]=t.charCodeAt(e);return r},ed=(e,t)=>{if(e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0},eh=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},ef=e=>"number"==typeof e&&!Number.isNaN(e),em=(e,t)=>{let r;if(t.includes("://"))return t;if(e.includes("://")){let t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}if(t.startsWith("/")){let i=e.indexOf("://");if(-1===i)r=t;else{let a=e.indexOf("/",i+3);r=-1===a?e+t:e.slice(0,a)+t}}else{let i=e.lastIndexOf("/");r=-1===i?t:e.slice(0,i+1)+t}let i="",a=r.indexOf("://");if(-1!==a){let e=r.indexOf("/",a+3);-1!==e&&(i=r.slice(0,e),r=r.slice(e))}let s=r.split("/"),n=[];for(let e of s)".."===e?n.pop():"."!==e&&n.push(e);return i+n.join("/")},ep=(e,t)=>{let r=0;for(let i=0;i<e.length;i++)t(e[i])&&r++;return r},eg=(e,t)=>{let r=-1,i=1/0;for(let a=0;a<e.length;a++){let s=t(e[a]);s<i&&(i=s,r=a)}return r},ek=e=>{i(Number.isInteger(e.num)),i(Number.isInteger(e.den)),i(0!==e.den);let t=Math.abs(e.num),r=Math.abs(e.den);for(;0!==r;){let e=t%r;t=r,r=e}let a=t||1;return{num:e.num/a,den:e.den/a}},eb=(e,t)=>{if("object"!=typeof e||!e)throw TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw TypeError(`${t}.height must be a non-negative integer.`)},ey=e=>new Promise(t=>setTimeout(t,e)),eT=e=>Array.isArray(e)?e:[e];class ew{constructor(){this._listeners=new Map}on(e,t,r){this._listeners.has(e)||this._listeners.set(e,new Set);let i={fn:t,once:r?.once??!1};return this._listeners.get(e).add(i),()=>{this._listeners.get(e)?.delete(i)}}_emit(...e){let[t,r]=e,i=this._listeners.get(t);if(i)for(let e of i){try{e.fn(r)}catch(e){console.error(e)}e.once&&i.delete(e)}}}let eS=e=>null!==e&&"object"==typeof e&&Object.getPrototypeOf(e)===Object.prototype&&Object.values(e).every(e=>"string"==typeof e);!function(e){e[e.Silent=0]="Silent",e[e.Errors=1]="Errors",e[e.Warnings=2]="Warnings",e[e.Info=3]="Info"}(i0||(i0={}));class eP{constructor(){}static get level(){return eP._level}static set level(e){if(e!==i0.Silent&&e!==i0.Errors&&e!==i0.Warnings&&e!==i0.Info)throw TypeError("Invalid log level. Use one of the values of the LogLevel enum.");eP._level=e}static get _emitter(){return eP._emitterInstance??=new ew}static on(e,t,r){return eP._emitter.on(e,t,r)}static _error(...e){eP._emitter._emit("error",e),eP._level>=i0.Errors&&console.error(...e)}
1static _warn(...e){eP._emitter._emit("warn",e),eP._level>=i0.Warnings&&console.warn(...e)}static _info(...e){eP._emitter._emit("info",e),eP._level>=i0.Info&&console.info(...e)}}eP._level=i0.Info,eP._emitterInstance=null;class ev{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if("string"!=typeof t)throw TypeError("mimeType must be a string.")}}class ex{constructor(e,t,r,i){if(this.data=e,this.mimeType=t,this.name=r,this.description=i,!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!=typeof t)throw TypeError("mimeType, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw TypeError("name, when provided, must be a string.");if(void 0!==i&&"string"!=typeof i)throw TypeError("description, when provided, must be a string.")}}let eC=e=>{if(!e||"object"!=typeof e)throw TypeError("tags must be an object.");if(void 0!==e.title&&"string"!=typeof e.title)throw TypeError("tags.title, when provided, must be a string.");if(void 0!==e.description&&"string"!=typeof e.description)throw TypeError("tags.description, when provided, must be a string.");if(void 0!==e.artist&&"string"!=typeof e.artist)throw TypeError("tags.artist, when provided, must be a string.");if(void 0!==e.album&&"string"!=typeof e.album)throw TypeError("tags.album, when provided, must be a string.");if(void 0!==e.albumArtist&&"string"!=typeof e.albumArtist)throw TypeError("tags.albumArtist, when provided, must be a string.");if(void 0!==e.trackNumber&&(!Number.isInteger(e.trackNumber)||e.trackNumber<=0))throw TypeError("tags.trackNumber, when provided, must be a positive integer.");if(void 0!==e.tracksTotal&&(!Number.isInteger(e.tracksTotal)||e.tracksTotal<=0))throw TypeError("tags.tracksTotal, when provided, must be a positive integer.");if(void 0!==e.discNumber&&(!Number.isInteger(e.discNumber)||e.discNumber<=0))throw TypeError("tags.discNumber, when provided, must be a positive integer.");if(void 0!==e.discsTotal&&(!Number.isInteger(e.discsTotal)||e.discsTotal<=0))throw TypeError("tags.discsTotal, when provided, must be a positive integer.");if(void 0!==e.genre&&"string"!=typeof e.genre)throw TypeError("tags.genre, when provided, must be a string.");if(void 0!==e.date&&(!(e.date instanceof Date)||Number.isNaN(e.date.getTime())))throw TypeError("tags.date, when provided, must be a valid Date.");if(void 0!==e.lyrics&&"string"!=typeof e.lyrics)throw TypeError("tags.lyrics, when provided, must be a string.");if(void 0!==e.images){if(!Array.isArray(e.images))throw TypeError("tags.images, when provided, must be an array.");for(let t of e.images){if(!t||"object"!=typeof t)throw TypeError("Each image in tags.images must be an object.");if(!(t.data instanceof Uint8Array))throw TypeError("Each image.data must be a Uint8Array.");if("string"!=typeof t.mimeType)throw TypeError("Each image.mimeType must be a string.");if(!["coverFront","coverBack","unknown"].includes(t.kind))throw TypeError("Each image.kind must be 'coverFront', 'coverBack', or 'unknown'.")}}if(void 0!==e.comment&&"string"!=typeof e.comment)throw TypeError("tags.comment, when provided, must be a string.");if(void 0!==e.raw){if(!e.raw||"object"!=typeof e.raw)throw TypeError("tags.raw, when provided, must be an object.");for(let t of Object.values(e.raw))if(null!==t&&"string"!=typeof t&&!(t instanceof Uint8Array)&&!(t instanceof ev)&&!(t instanceof ex)&&!eS(t))throw TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},eI={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1},eE=e=>{if(!e||"object"!=typeof e)throw TypeError("disposition must be an object.");if(void 0!==e.default&&"boolean"!=typeof e.default)throw TypeError("disposition.default must be a boolean.");if(void 0!==e.primary&&"boolean"!=typeof e.primary)throw TypeError("disposition.primary must be a boolean.");if(void 0!==e.forced&&"boolean"!=typeof e.forced)throw TypeError("disposition.forced must be a boolean.");if(void 0!==e.original&&"boolean"!=typeof e.original)throw TypeError("disposition.original must be a boolean.");if(void 0!==e.commentary&&"boolean"!=typeof e.commentary)throw TypeError("disposition.commentary must be a boolean.");if(void 0!==e.hearingImpaired&&"boolean"!=typeof e.hearingImpaired)throw TypeError("disposition.hearingImpaired must be a boolean.");if(void 0!==e.visuallyImpaired&&"boolean"!=typeof e.visuallyImpaired)throw TypeError("disposition.visuallyImpaired must be a boolean.")};class e_{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){let e=Math.floor(this.pos/8),t=this.bytes[e]??0,r=7-(7&this.pos);return this.pos++,(t&1<<r)>>r}readBits(e){if(1===e)return this.readBit();let t=0;for(let r=0;r<e;r++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let r=this.pos+e;for(let e=this.pos;e<r;e++){let i=Math.floor(e/8),a=this.bytes[i],s=7-(7&e);a&=~(1<<s),a|=(t&1<<r-e-1)>>r-e-1<<s,this.bytes[i]=a}this.pos=r}readAlignedByte(){if(this.pos%8!=0)throw Error("Bitstream is not byte-aligned.");let e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){let e=new e_(this.bytes);return e.pos=this.pos,e}}let eB=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],eA=[-1,1,2,3,4,5,6,8],eF=e=>{if(!e||e.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let t=new e_(e),r=t.readBits(5);31===r&&(r=32+t.readBits(6));let i=t.readBits(4),a=null;15===i?a=t.readBits(24):i<eB.length&&(a=eB[i]);let s=t.readBits(4),n=null;return s>=1&&s<=7&&(n=eA[s]),{objectType:r,frequencyIndex:i,sampleRate:a,channelConfiguration:s,numberOfChannels:n}},eM=e=>{let t=eB.indexOf(e.sampleRate),r=null;-1===t&&(t=15,r=e.sampleRate);let i=eA.indexOf(e.numberOfChannels);if(-1===i)throw TypeError(`Unsupported number of channels: ${e.numberOfChannels}`);let a=13;e.objectType>=32&&(a+=6),15===t&&(a+=24);let s=new Uint8Array(Math.ceil(a/8)),n=new e_(s);return e.objectType<32?n.writeBits(5,e.objectType):(n.writeBits(5,31),n.writeBits(6,e.objectType-32)),n.writeBits(4,t),15===t&&n.writeBits(24,r),n.writeBits(4,i),s},eR=["avc","hevc","vp9","av1","vp8","prores"],eD=["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"],eO=["aac","opus","mp3","vorbis","flac","ac3","eac3"],eN=[...eO,...eD],ez=["webvtt"],eU=[{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}],eL=[{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:0x2200000,maxBitrate:18e7,level:60},{maxPictureSize:0x2200000,maxBitrate:24e7,level:61},{maxPictureSize:0x2200000,maxBitrate:48e7,level:62}],eW=".01.01.01.01.00",eq=".0.110.01.01.01.0",eV=["ap4x","ap4h","apch","apcn","apcs","apco"],eH=e
1=>{let t=e.split("."),r=Number(t[1]),i=t[2],a=Number(i.slice(0,-1)),s=+("H"===i.slice(-1)),n=Number(t[3]),o=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1;return[129,(r<<5)+a,(s<<7)+((8!==n)<<6)+0+(o<<4)+(l<<3)+((t[5]?Number(t[5][1]):1)<<2)+(t[5]?Number(t[5][2]):0),0]},ej=e=>{let{codec:t,codecDescription:r,colorSpace:a,avcCodecInfo:n,hevcCodecInfo:o,vp9CodecInfo:l,av1CodecInfo:c,proresFormat:d}=e;if("avc"===t){if(i(null!==e.avcType),n){let t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${v(t)}`}if(!r||r.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${v(r.subarray(1,4))}`}if("hevc"===t){let e,t,i,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,i=C(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!r||r.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let o=u(r),l=o.getUint8(1);e=l>>6&3,t=31&l,i=C(o.getUint32(2)),a=l>>5&1,s=o.getUint8(12),n=[];for(let e=0;e<6;e++)n.push(o.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=i.toString(16).toUpperCase(),l+=".",l+=0===a?"L":"H",l+=s;n.length>0&&0===n[n.length-1];)n.pop();return n.length>0&&(l+=".",l+=n.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!l){let t=e.width*e.height,r=s(eL).level;for(let e of eL)if(t<=e.maxPictureSize){r=e.level;break}return`vp09.00.${r.toString().padStart(2,"0")}.08`}let t=l.profile.toString().padStart(2,"0"),r=l.level.toString().padStart(2,"0"),i=l.bitDepth.toString().padStart(2,"0"),a=l.chromaSubsampling.toString().padStart(2,"0"),n=l.colourPrimaries.toString().padStart(2,"0"),o=l.transferCharacteristics.toString().padStart(2,"0"),c=l.matrixCoefficients.toString().padStart(2,"0"),u=l.videoFullRangeFlag.toString().padStart(2,"0"),d=`vp09.${t}.${r}.${i}.${a}`;return(d+=`.${n}.${o}.${c}.${u}`).endsWith(eW)&&(d=d.slice(0,-eW.length)),d}if("av1"===t){if(!c){let t=e.width*e.height,r=s(eL).level;for(let e of eL)if(t<=e.maxPictureSize){r=e.level;break}return`av01.0.${r.toString().padStart(2,"0")}M.08`}let t=c.profile,r=c.level.toString().padStart(2,"0"),i=c.tier?"H":"M",n=c.bitDepth.toString().padStart(2,"0"),o=c.monochrome?"1":"0",l=100*c.chromaSubsamplingX+10*c.chromaSubsamplingY+ +(c.chromaSubsamplingX&&c.chromaSubsamplingY?c.chromaSamplePosition:0),u=a?.primaries?m[a.primaries]:1,d=a?.transfer?g[a.transfer]:1,h=a?.matrix?b[a.matrix]:1,f=+!!a?.fullRange,p=`av01.${t}.${r}${i}.${n}`;return p+=`.${o}.${l.toString().padStart(3,"0")}`,p+=`.${u.toString().padStart(2,"0")}`,p+=`.${d.toString().padStart(2,"0")}`,p+=`.${h.toString().padStart(2,"0")}`,(p+=`.${f}`).endsWith(eq)&&(p=p.slice(0,-eq.length)),p}else{if("prores"===t)return d??"apch";null!==t&&D(t)}throw TypeError(`Unhandled codec '${t}'.`)},e$=(e,t,r)=>{if("aac"===e)return t>=2&&r<=24e3?"mp4a.40.29":r<=24e3?"mp4a.40.5":"mp4a.40.2";if("mp3"===e)return"mp3";if("opus"===e)return"opus";if("vorbis"===e)return"vorbis";if("flac"===e)return"flac";else if("ac3"===e)return"ac-3";else if("eac3"===e)return"ec-3";else if(eD.includes(e))return e;throw TypeError(`Unhandled codec '${e}'.`)},eK=e=>{let{codec:t,codecDescription:r,aacCodecInfo:i}=e;if("aac"===t){if(!i)throw TypeError("AAC codec info must be provided.");if(i.isMpeg2)return"mp4a.67";{let e;return e=null!==i.objectType?i.objectType:eF(r).objectType,`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";else if("ac3"===t)return"ac-3";else if("eac3"===t)return"ec-3";else if(t&&eD.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},eX=/^pcm-([usf])(\d+)(be)?$/,eG=e=>{let t;if(i(eD.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};let r=eX.exec(e);i(r),t="u"===r[1]?"unsigned":"s"===r[1]?"signed":"float";let a=Number(r[2])/8;return{dataType:t,sampleSize:a,littleEndian:"be"!==r[3],silentValue:128*("pcm-u8"===e)}},eQ=e=>{if(e.startsWith("avc1")||e.startsWith("avc3"))return"avc";if(e.startsWith("hev1")||e.startsWith("hvc1"))return"hevc";if("vp8"===e)return"vp8";if(e.startsWith("vp09"))return"vp9";if(e.startsWith("av01"))return"av1";else if(eV.includes(e))return"prores";if("mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e)return"mp3";if(e.startsWith("mp4a.40.")||"mp4a.67"===e)return"aac";if("opus"===e)return"opus";if("vorbis"===e)return"vorbis";if("flac"===e)return"flac";
1else if("ac-3"===e||"ac3"===e)return"ac3";else if("ec-3"===e||"eac3"===e)return"eac3";else if("ulaw"===e)return"ulaw";else if("alaw"===e)return"alaw";else if(eX.test(e))return e;return"webvtt"===e?"webvtt":null},eY=e=>"aac"===e?{aac:{format:"aac"}}:"opus"===e?{opus:{format:"opus"}}:{},eJ=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...eV],eZ=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,e0=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,e1=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,e2=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,e3=(e,t)=>{if(!e)throw TypeError("Video chunk metadata must be provided.");if("object"!=typeof e)throw TypeError("Video chunk metadata must be an object.");if(!e.decoderConfig)throw TypeError("Video chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw TypeError("Video chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw TypeError("Video chunk metadata decoder configuration must specify a codec string.");if(!eJ.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError("Video chunk metadata decoder configuration codec string must be a valid video codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(e.decoderConfig.codedWidth)||e.decoderConfig.codedWidth<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedWidth (positive integer).");if(!Number.isInteger(e.decoderConfig.codedHeight)||e.decoderConfig.codedHeight<=0)throw TypeError("Video chunk metadata decoder configuration must specify a valid codedHeight (positive integer).");if(void 0!==e.decoderConfig.displayAspectWidth&&(!Number.isInteger(e.decoderConfig.displayAspectWidth)||e.decoderConfig.displayAspectWidth<=0))throw TypeError("Video chunk metadata decoder configuration displayAspectWidth, when defined, must be a positive integer.");if(void 0!==e.decoderConfig.displayAspectHeight&&(!Number.isInteger(e.decoderConfig.displayAspectHeight)||e.decoderConfig.displayAspectHeight<=0))throw TypeError("Video chunk metadata decoder configuration displayAspectHeight, when defined, must be a positive integer.");if(void 0!==e.decoderConfig.displayAspectWidth!=(void 0!==e.decoderConfig.displayAspectHeight))throw TypeError("Video chunk metadata decoder configuration must specify both displayAspectWidth and displayAspectHeight, or neither.");if(void 0!==e.decoderConfig.description&&!w(e.decoderConfig.description))throw TypeError("Video chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(void 0!==e.decoderConfig.colorSpace){let{colorSpace:t}=e.decoderConfig;if("object"!=typeof t)throw TypeError("Video chunk metadata decoder configuration colorSpace, when provided, must be an object.");let r=Object.keys(m);if(null!=t.primaries&&!r.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${r.join(", ")}.`);let i=Object.keys(g);if(null!=t.transfer&&!i.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${i.join(", ")}.`);let a=Object.keys(b);if(null!=t.matrix&&!a.includes(t.matrix))throw TypeError(`Video chunk metadata decoder configuration colorSpace matrix, when defined, must be one of ${a.join(", ")}.`);if(null!=t.fullRange&&"boolean"!=typeof t.fullRange)throw TypeError("Video chunk metadata decoder configuration colorSpace fullRange, when defined, must be a boolean.")}if(e.decoderConfig.codec.startsWith("avc1")||e.decoderConfig.codec.startsWith("avc3")){if(!eZ.test(e.decoderConfig.codec))throw TypeError("Video chunk metadata decoder configuration codec string for AVC must be a valid AVC codec string as specified in Section 3.4 of RFC 6381.")}else if(e.decoderConfig.codec.startsWith("hev1")||e.decoderConfig.codec.startsWith("hvc1")){if(!e0.test(e.decoderConfig.codec))throw TypeError("Video chunk metadata decoder configuration codec string for HEVC must be a valid HEVC codec string as specified in Section E.3 of ISO 14496-15.")}else if(e.decoderConfig.codec.startsWith("vp8")){if("vp8"!==e.decoderConfig.codec)throw TypeError('Video chunk metadata decoder configuration codec string for VP8 must be "vp8".')}else if(e.decoderConfig.codec.startsWith("vp09")){if(!e1.test(e.decoderConfig.codec))throw TypeError('Video chunk metadata decoder configuration codec string for VP9 must be a valid VP9 codec string as specified in Section "Codecs Parameter String" of https://www.webmproject.org/vp9/mp4/.')}else if(e.decoderConfig.codec.startsWith("av01")){if(!e2.test(e.decoderConfig.codec))throw TypeError('Video chunk metadata decoder configuration codec string for AV1 must be a valid AV1 codec string as specified in Section "Codecs Parameter String" of https://aomediacodec.github.io/av1-isobmff/.')}else if(eV.some(t=>e.decoderConfig.codec.startsWith(t))&&!eV.some(t=>e.decoderConfig.codec===t))throw TypeError(`Video chunk metadata decoder configuration codec string for ProRes must be one of the valid ProRes four-character codes: ${eV.join(", ")}.`);
1if(null!==t&&eQ(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},e4=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3"],e8=(e,t)=>{if(!e)throw TypeError("Audio chunk metadata must be provided.");if("object"!=typeof e)throw TypeError("Audio chunk metadata must be an object.");if(!e.decoderConfig)throw TypeError("Audio chunk metadata must include a decoder configuration.");if("object"!=typeof e.decoderConfig)throw TypeError("Audio chunk metadata decoder configuration must be an object.");if("string"!=typeof e.decoderConfig.codec)throw TypeError("Audio chunk metadata decoder configuration must specify a codec string.");if(!e4.some(t=>e.decoderConfig.codec.startsWith(t)))throw TypeError("Audio chunk metadata decoder configuration codec string must be a valid audio codec string as specified in the Mediabunny Codec Registry.");if(!Number.isInteger(e.decoderConfig.sampleRate)||e.decoderConfig.sampleRate<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid sampleRate (positive integer).");if(!Number.isInteger(e.decoderConfig.numberOfChannels)||e.decoderConfig.numberOfChannels<=0)throw TypeError("Audio chunk metadata decoder configuration must specify a valid numberOfChannels (positive integer).");if(void 0!==e.decoderConfig.description&&!w(e.decoderConfig.description))throw TypeError("Audio chunk metadata decoder configuration description, when defined, must be an ArrayBuffer or an ArrayBuffer view.");if(e.decoderConfig.codec.startsWith("mp4a")&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec){if(!["mp4a.40.2","mp4a.40.02","mp4a.40.5","mp4a.40.05","mp4a.40.29","mp4a.67"].includes(e.decoderConfig.codec))throw TypeError("Audio chunk metadata decoder configuration codec string for AAC must be a valid AAC codec string as specified in https://www.w3.org/TR/webcodecs-aac-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("mp3")||e.decoderConfig.codec.startsWith("mp4a")){if("mp3"!==e.decoderConfig.codec&&"mp4a.69"!==e.decoderConfig.codec&&"mp4a.6B"!==e.decoderConfig.codec&&"mp4a.6b"!==e.decoderConfig.codec)throw TypeError('Audio chunk metadata decoder configuration codec string for MP3 must be "mp3", "mp4a.69" or "mp4a.6B".')}else if(e.decoderConfig.codec.startsWith("opus")){if("opus"!==e.decoderConfig.codec)throw TypeError('Audio chunk metadata decoder configuration codec string for Opus must be "opus".');if(e.decoderConfig.description&&e.decoderConfig.description.byteLength<18)throw TypeError("Audio chunk metadata decoder configuration description, when specified, is expected to be an Identification Header as specified in Section 5.1 of RFC 7845.")}else if(e.decoderConfig.codec.startsWith("vorbis")){if("vorbis"!==e.decoderConfig.codec)throw TypeError('Audio chunk metadata decoder configuration codec string for Vorbis must be "vorbis".');if(!e.decoderConfig.description)throw TypeError("Audio chunk metadata decoder configuration for Vorbis must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-vorbis-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("flac")){if("flac"!==e.decoderConfig.codec)throw TypeError('Audio chunk metadata decoder configuration codec string for FLAC must be "flac".');if(!e.decoderConfig.description||e.decoderConfig.description.byteLength<42)throw TypeError("Audio chunk metadata decoder configuration for FLAC must include a description, which is expected to adhere to the format described in https://www.w3.org/TR/webcodecs-flac-codec-registration/.")}else if(e.decoderConfig.codec.startsWith("ac-3")||e.decoderConfig.codec.startsWith("ac3")){if("ac-3"!==e.decoderConfig.codec)throw TypeError('Audio chunk metadata decoder configuration codec string for AC-3 must be "ac-3".')}else if(e.decoderConfig.codec.startsWith("ec-3")||e.decoderConfig.codec.startsWith("eac3")){if("ec-3"!==e.decoderConfig.codec)throw TypeError('Audio chunk metadata decoder configuration codec string for EC-3 must be "ec-3".')}else if((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!eD.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${eD.join(", ")}).`);if(null!==t&&eQ(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},e6=e=>{if(!e)throw TypeError("Subtitle metadata must be provided.");if("object"!=typeof e)throw TypeError("Subtitle metadata must be an object.");if(!e.config)throw TypeError("Subtitle metadata must include a config object.");if("object"!=typeof e.config)throw TypeError("Subtitle metadata config must be an object.");if("string"!=typeof e.config.description)throw TypeError("Subtitle metadata config description must be a string.")},e5=[44100,48e3,32e3],e7=[-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],e9=(e,t,r,i,a)=>0===t?0:1===t?Math.floor(144*r/(i<<e))+a:2===t?Math.floor(144*r/i)+a:(Math.floor(12*r/i)+a)*4,te=(e,t,r,i)=>0===t?0:1===t?144*r/(i<<e):2===t?144*r/i:12*r/i*4,tt=(e,t)=>3===e?3===t?21:36:3===t?13:21,tr=(e,t)=>{let r,i=e>>>24,a=e>>>16&255,s=e>>>8&255,n=255&e;if(255!==i&&255!==a&&255!==s&&255!==n)return{header:null,bytesAdvanced:4};if(255!==i||(224&a)!=224)return{header:null,bytesAdvanced:1};let o=0,l=0;16&a?o=8&a?0:1:(o=1,l=1);let c=a>>3&3,u=a>>1&3,d=(s>>2&3)%3,h=e7[16*o*4+16*u+(s>>4&15)];if(-1===h)return{header:null,bytesAdvanced:1};let f=1e3*h,m=e5[d]>>o+l,p=e9(o,u,f,m,s>>1&1);return null!==t&&t<p?{header:null,bytesAdvanced:1}:(r=3===c?3===u?384:1152:3===u?384:2===u?1152:576,{header:{totalSize:p,mpegVersionId:c,lowSamplingFrequency:o,layer:u,bitrate:f,frequencyIndex:d,sampleRate:m,channel:n>>6&3,modeExtension:n>>4&3,copyright:n>>3&1,original:n>>2&1,emphasis:3&n,audioSamplesInFrame:r},bytesAdvanced:1})},ti=e=>{let t=0x7f000000,r=0;for(;0!==t;)r>>=1,r|=e&t,t>>=8;return r};!function(e){e[e.FrameCount=1]="FrameCount",e[e.FileSize=2]="FileSize",e[e.Toc=4]="Toc"}(i1||(i1={}));let ta=e=>3===e?1:2,ts=[48e3,44100,32e3],tn=[24e3,22050,16e3];!function(e){e[e.NON_IDR_SLICE=1]="NON_IDR_SLICE",e[e.SLICE_DPA=2]="SLICE_DPA",e[e.SLICE_DPB=3]="SLICE_DPB",e[e.SLICE_DPC=4]="SLICE_DPC",e[e.IDR=5]="IDR",e[e.SEI=6]="SEI",e[e.SPS=7]="SPS",e[e.PPS=8]="PPS",e[e.AUD=9]="AUD",e[e.SPS_EXT=13]="SPS_EXT"}(i2||(i2={})),function(e){e[e.RASL_N=8]="RASL_N",e[e.RASL_R=9]="RASL_R",e[e.BLA_W_LP=16]="BLA_W_LP",e[e.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",e[e.VPS_NUT=32]="VPS_NUT",e[e.SPS_NUT=33]="SPS_NUT",e[e.PPS_NUT=34]="PPS_NUT",e[e.AUD_NUT=35]="AUD_NUT",e[e.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",e[e.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT"}(i3||(i3={}));let to=function*(e){let t=0,r=-1;for(;t<e.length-2;){let i=e.indexOf(0,t);if(-1===i||i>=e.length-2)break;let a=0;if((t=i)+3<e.length&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]?a=4:0===e[t+1]&&1===e[t+2]&&(a=3),0===a){t++;continue}-1!==r&&t>r&&(yield{offset:r,length:t-r}),t=r=t+a}-1!==r&&r<e.length&&(yield{offset:r,length:e.length-r})},tl=function*(e,t){let r=0,a=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;r+t<=e.length;){let e;1===t?e=a.getUint8(r):2===t?e=a.getUint16(r,!1):3===t?e=O(a,r,!1):(i(4===t),e=a.getUint32(r,!1)),r+=t,yield{offset:r,length:e},r+=e}},tc=(e,t)=>t.description?tl(e,(3&c(t.description)[4])+1):to(e),tu=e=>31&e,td=e=>{let t=[],r=e.length;for(let i=0;i<r;i++)i+2<r&&0===e[i]&&0===e[i+1]&&3===e[i+2]?(t.push(0,0),i+=2):t.push(e[i]);return new Uint8Array(t)};new Uint8Array([0,0,0,1]);let th=(e,t)=>{let r=new Uint8Array(e.reduce((e,r)=>e+t+r.byteLength,0)),i=0;for(let a of e){let e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(i,a.byteLength);break;case 2:e.setUint16(i,a.byteLength,!1);break;case 3:z(e,i,a.byteLength,!1);break;case 4:e.setUint32(i,a.byteLength,!1)}i+=t,r.set(a,i),i+=a.byteLength}return r},tf=e=>{try{let t=[],r=[],a=[];for(let i of to(e)){let s=e.subarray(i.offset,i.offset+i.length),n=tu(s[0]);n===i2.SPS?t.push(s):n===i2.PPS?r.push(s):n===i2.SPS_EXT&&a.push(s)}if(0===t.length||0===r.length)return null;let s=t[0],n=tg(s);i(null!==n);let o=100===n.profileIdc||110===n.profileIdc||122===n.profileIdc||144===n.profileIdc;return{configurationVersion:1,avcProfileIndication:n.profileIdc,profileCompatibility:n.constraintFlags,avcLevelIndication:n.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:r,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?a:null}}catch(e){return eP._error("Error building AVC Decoder Configuration Record:",e),null}},tm=e=>{let t=[];for(let r of(t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.pu
1sh(224|31&e.sequenceParameterSets.length),e.sequenceParameterSets)){let e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}for(let r of(t.push(e.pictureParameterSets.length),e.pictureParameterSets)){let e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication)for(let r of(i(null!==e.chromaFormat),i(null!==e.bitDepthLumaMinus8),i(null!==e.bitDepthChromaMinus8),i(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length),e.sequenceParameterSetExt)){let e=r.byteLength;t.push(e>>8),t.push(255&e);for(let i=0;i<e;i++)t.push(r[i])}return new Uint8Array(t)},tp={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}},tg=e=>{try{let t=new e_(td(e));t.skipBits(1),t.skipBits(2);let r=t.readBits(5);if(7!==r)return null;let a=t.readAlignedByte(),n=t.readAlignedByte(),c=t.readAlignedByte();o(t);let u=1,d=0,h=0,f=0;if((100===a||110===a||122===a||244===a||44===a||83===a||86===a||118===a||128===a)&&(u=o(t),3===u&&(f=t.readBits(1)),d=o(t),h=o(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(3!==u?8:12);e++)if(t.readBits(1)){let r=e<6?16:64,i=8,a=8;for(let e=0;e<r;e++){if(0!==a){let e=l(t);a=(i+e+256)%256}i=0===a?i:a}}}o(t);let m=o(t);if(0===m)o(t);else if(1===m){t.skipBits(1),l(t),l(t);let e=o(t);for(let r=0;r<e;r++)l(t)}o(t),t.skipBits(1);let p=o(t),g=o(t),k=16*(p+1),b=16*(g+1),y=k,T=b,w=t.readBits(1);if(w||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e,r,i=o(t),a=o(t),s=o(t),n=o(t),l=0===f?u:0;if(0===l)e=1,r=2-w;else{let t=3===u?1:2,i=1===u?2:1;e=t,r=i*(2-w)}y-=e*(i+a),T-=r*(s+n)}let S=2,P=2,v=2,x=0,C={num:1,den:1},I=null,E=null;if(t.readBits(1)){if(t.readBits(1)){let e=t.readBits(8);if(255===e)C={num:t.readBits(16),den:t.readBits(16)};else{let t=tp[e];t&&(C=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),x=t.readBits(1),t.readBits(1)&&(S=t.readBits(8),P=t.readBits(8),v=t.readBits(8))),t.readBits(1)&&(o(t),o(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&tk(t);let r=t.readBits(1);r&&tk(t),(e||r)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),o(t),o(t),o(t),o(t),I=o(t),E=o(t))}if(null===I)if(i(null===E),(44===a||86===a||100===a||110===a||122===a||244===a)&&16&n)I=0,E=0;else{let e=eU.find(e=>e.level>=c)??s(eU),t=Math.min(Math.floor(e.maxDpbMbs/((2-w)*(g+1)*(p+1))),16);I=t,E=t}return i(null!==E),{profileIdc:a,constraintFlags:n,levelIdc:c,frameMbsOnlyFlag:w,chromaFormatIdc:u,bitDepthLumaMinus8:d,bitDepthChromaMinus8:h,codedWidth:k,codedHeight:b,displayWidth:y,displayHeight:T,pixelAspectRatio:C,colourPrimaries:S,matrixCoefficients:v,transferCharacteristics:P,fullRangeFlag:x,numReorderFrames:I,maxDecFrameBuffering:E}}catch(e){return eP._error("Error parsing AVC SPS:",e),null}},tk=e=>{let t=o(e);e.skipBits(4),e.skipBits(4);for(let r=0;r<=t;r++)o(e),o(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},tb=(e,t)=>t.description?tl(e,(3&c(t.description)[21])+1):to(e),ty=e=>e>>1&63,tT=e=>{try{let t=new e_(td(e));t.skipBits(16),t.readBits(4);let r=t.readBits(3),i=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:l,general_constraint_indicator_flags:c,general_level_idc:u}=tS(t,r);o(t);let d=o(t),h=0;3===d&&(h=t.readBits(1));let f=o(t),m=o(t),p=f,g=m;if(t.readBits(1)){let e=o(t),r=o(t),i=o(t),a=o(t),s=1,n=1,l=0===h?d:0;1===l?(s=2,n=2):2===l&&(s=2,n=1),p-=(e+r)*s,g-=(i+a)*n}let k=o(t),b=o(t);o(t);let y=t.readBits(1)?0:r,T=0;for(let e=y;e<=r;e++)o(t),T=o(t),o(t);o(t),o(t),o(t),o(t),o(t),o(t),t.readBits(1)&&t.readBits(1)&&tP(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),o(t),o(t),t.skipBits(1));let w=o(t);if(tv(t,w),t.readBits(1)){let e=o(t);for(let r=0;r<e;r++)o(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let S=2,P=2,v=2,x=0,C=0,I={num:1,den:1};if(t.readBits(1)){let e=tC(t,r);I=e.pixelAspectRatio,S=e.colourPrimaries,P=e.transferCharacteristics,v=e.matrixCoefficients,x=e.fullRangeFlag,C=e.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:I,colourPrimaries:S,transferCharacteristics:P,matrixCoefficients:v,fullRangeFlag:x,maxDecFrameBuffering:T+1,spsMaxSubLayersMinus1:r,spsTemporalIdNestingFlag:i,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:n,generalProfileCompatibilityFlags:l,generalConstraintIndicatorFlags:c,generalLevelIdc:u,chromaFormatIdc:d,bitDepthLumaMinus8:k,bitDepthChromaMinus8:b,minSpatialSegmentationIdc:C}}catch(e){return eP._error("Error parsing HEVC SPS:",e),null}},tw=e=>{try{let t=[],r=[],i=[],a=[];for(let s of to(e)){let n=e.subarray(s.offset,s.offset+s.length),o=ty(n[0]);
1o===i3.VPS_NUT?t.push(n):o===i3.SPS_NUT?r.push(n):o===i3.PPS_NUT?i.push(n):(o===i3.PREFIX_SEI_NUT||o===i3.SUFFIX_SEI_NUT)&&a.push(n)}if(0===r.length||0===i.length)return null;let s=tT(r[0]);if(!s)return null;let n=0;if(i.length>0){let e=i[0],t=new e_(td(e));t.skipBits(16),o(t),o(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),o(t),o(t),l(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&o(t),l(t),l(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let r=t.readBits(1),a=t.readBits(1);n=r||a?r&&!a?2:!r&&a?3:0:0}let c=[...t.length?[{arrayCompleteness:1,nalUnitType:i3.VPS_NUT,nalUnits:t}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:i3.SPS_NUT,nalUnits:r}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:i3.PPS_NUT,nalUnits:i}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:ty(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:n,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:c}}catch(e){return eP._error("Error building HEVC Decoder Configuration Record:",e),null}},tS=(e,t)=>{let r=e.readBits(2),i=e.readBits(1),a=e.readBits(5),s=0;for(let t=0;t<32;t++)s=s<<1|e.readBits(1);let n=new Uint8Array(6);for(let t=0;t<6;t++)n[t]=e.readBits(8);let o=e.readBits(8),l=[],c=[];for(let r=0;r<t;r++)l.push(e.readBits(1)),c.push(e.readBits(1));if(t>0)for(let r=t;r<8;r++)e.skipBits(2);for(let r=0;r<t;r++)l[r]&&e.skipBits(88),c[r]&&e.skipBits(8);return{general_profile_space:r,general_tier_flag:i,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},tP=e=>{for(let t=0;t<4;t++)for(let r=0;r<(3===t?2:6);r++)if(e.readBits(1)){let r=Math.min(64,1<<4+(t<<1));t>1&&l(e);for(let t=0;t<r;t++)l(e)}else o(e)},tv=(e,t)=>{let r=[];for(let i=0;i<t;i++)r[i]=tx(e,i,t,r)},tx=(e,t,r,i)=>{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){n=t===r?t-(o(e)+1):t-1,e.readBits(1),o(e);let s=i[n]??0;for(let t=0;t<=s;t++)e.readBits(1)||e.readBits(1);a=i[n]}else{let t=o(e),r=o(e);for(let r=0;r<t;r++)o(e),e.readBits(1);for(let t=0;t<r;t++)o(e),e.readBits(1);a=t+r}return a},tC=(e,t)=>{let r=2,i=2,a=2,s=0,n=0,l={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(255===t)l={num:e.readBits(16),den:e.readBits(16)};else{let e=tp[t];e&&(l=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(r=e.readBits(8),i=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(o(e),o(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(o(e),o(e),o(e),o(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&o(e),e.readBits(1)&&tI(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=o(e),o(e),o(e),o(e),o(e)),{pixelAspectRatio:l,colourPrimaries:r,transferCharacteristics:i,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},tI=(e,t,r)=>{let i=!1,a=!1,s=!1;t&&(i=1===e.readBits(1),a=1===e.readBits(1),(i||a)&&((s=1===e.readBits(1))&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5)));for(let t=0;t<=r;t++){let t=1===e.readBits(1),r=!0;t||(r=1===e.readBits(1));let n=!1;r?o(e):n=1===e.readBits(1);let l=1;n||(l=o(e)+1),i&&tE(e,l,s),a&&tE(e,l,s)}},tE=(e,t,r)=>{for(let i=0;i<t;i++)o(e),o(e),r&&(o(e),o(e)),e.readBits(1)},t_=e=>{let t=[];for(let r of(t.push(e.configurationVersion),t.push((3&e.generalProfileSpace)<<6|(1&e.generalTierFlag)<<5|31&e.generalProfileIdc),t.push(e.generalProfileCompatibilityFlags>>>24&255),t.push(e.generalProfileCompatibilityFlags>>>16&255),t.push(e.generalProfileCompatibilityFlags>>>8&255),t.push(255&e.generalProfileCompatibilityFlags),t.push(...e.generalConstraintIndicatorFlags),t.push(255&e.generalLevelIdc),t.push(240|e.minSpatialSegmentationIdc>>8&15),t.push(255&e.minSpatialSegmentationIdc),t.push(252|3&e.parallelismType),t.pu
1sh(252|3&e.chromaFormatIdc),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.avgFrameRate>>8&255),t.push(255&e.avgFrameRate),t.push((3&e.constantFrameRate)<<6|(7&e.numTemporalLayers)<<3|(1&e.temporalIdNested)<<2|3&e.lengthSizeMinusOne),t.push(255&e.arrays.length),e.arrays))for(let e of(t.push((1&r.arrayCompleteness)<<7|63&r.nalUnitType),t.push(r.nalUnits.length>>8&255),t.push(255&r.nalUnits.length),r.nalUnits)){t.push(e.length>>8&255),t.push(255&e.length);for(let r=0;r<e.length;r++)t.push(e[r])}return new Uint8Array(t)};!function(e){e[e.audAllowed=0]="audAllowed",e[e.beforeFirstVcl=1]="beforeFirstVcl",e[e.afterFirstVcl=2]="afterFirstVcl",e[e.eoBitstreamAllowed=3]="eoBitstreamAllowed",e[e.noMoreDataAllowed=4]="noMoreDataAllowed"}(i4||(i4={}));let tB=e=>{let t=new e_(e);if(2!==t.readBits(2))return null;let r=t.readBits(1),i=(t.readBits(1)<<1)+r;if(3===i&&t.skipBits(1),1===t.readBits(1)||0!==t.readBits(1)||(t.skipBits(2),4817730!==t.readBits(24)))return null;let a=8;i>=2&&(a=t.readBits(1)?12:10);let n=t.readBits(3),o=0,l=0;if(7!==n)if(l=t.readBits(1),1===i||3===i){let e=t.readBits(1),r=t.readBits(1);o=e||r?e&&!r?2:1:3,t.skipBits(1)}else o=1;else o=3,l=1;let c=t.readBits(16),u=(c+1)*(t.readBits(16)+1),d=s(eL).level;for(let e of eL)if(u<=e.maxPictureSize){d=e.level;break}return{profile:i,level:d,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:2===n?1:1===n?6:2,transferCharacteristics:2===n?1:1===n?6:2,matrixCoefficients:7===n?0:2===n?1:1===n?6:2}},tA=function*(e){let t=new e_(e),r=()=>{let e=0;for(let r=0;r<8;r++){let i=t.readAlignedByte();if(e|=(127&i)<<7*r,!(128&i))break;if(7===r&&128&i)return null}return e>=0x100000000-1?null:e};for(;t.getBitsLeft()>=8;){let a;t.skipBits(1);let s=t.readBits(4),n=t.readBits(1),o=t.readBits(1);if(t.skipBits(1),n&&t.skipBits(8),o){let e=r();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);i(t.pos%8==0),yield{type:s,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},tF=e=>{for(let{type:t,data:r}of tA(e)){if(1!==t)continue;let e=new e_(r),i=e.readBits(3);e.readBits(1);let a=e.readBits(1),s=0,n=0,o=0;if(a)s=e.readBits(5);else{if(e.readBits(1)&&(e.skipBits(32),e.skipBits(32),e.readBits(1)))return null;let t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));let r=e.readBits(5);for(let i=0;i<=r;i++){e.skipBits(12);let r=e.readBits(5);if(0===i&&(s=r),r>7){let t=e.readBits(1);0===i&&(n=t)}if(t&&e.readBits(1)){let t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}e.readBits(1)&&e.skipBits(4)}}let l=e.readBits(4),c=e.readBits(4),u=l+1;e.skipBits(u);let d=c+1;e.skipBits(d);let h=0;if((a?0:e.readBits(1))&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);let t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let r=e.readBits(1),i=0;(r?2:e.readBits(1))>0&&(e.readBits(1)||e.skipBits(1)),t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);let f=e.readBits(1),m=8;2===i&&f?m=e.readBits(1)?12:10:i<=2&&(m=f?10:8);let p=0;1!==i&&(p=e.readBits(1));let g=1,k=1,b=0;return!p&&(0===i?(g=1,k=1):1===i?(g=0,k=0):12===m&&(g=e.readBits(1))&&(k=e.readBits(1)),g&&k&&(b=e.readBits(2))),{profile:i,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:b}}return null},tM=e=>{let t=u(e),r=t.getUint8(9),i=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18),o=null;return n&&(o=e.subarray(19,21+r)),{outputChannelCount:r,preSkip:i,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}},tR=[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],tD=e=>{let t,r=e[0]>>3,i=3&e[0];return t=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:tR[r]*t}},tO=e=>{if(e.length<7)throw Error("Setup header is too short.");if(5!==e[0])throw Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw Error("Invalid packet signature in Setup header.");let t=e.length,r=new Uint8Array(t);for(let i=0;i<t;i++)r[i]=e[t-1-i];let i=new e_(r),a=0;for(;i.getBitsLeft()>97;)if(1===i.readBits(1)){a=i.pos;break}if(0===a)throw Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;i.getBitsLeft()>=97;){let e=i.pos,t=i.readBits(8),r=i.readBits(16),a=i.readBits(16);if(t>63||0!==r||0!==a){i.pos=e;break}if(i.skipBits(1),++s>64)break;
1i.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw Error("Invalid Setup header: mode header not found.");if(o>63)throw Error(`Unsupported mode count: ${o}.`);let l=o;i.pos=0,i.skipBits(a);let c=Array(l).fill(0);for(let e=l-1;e>=0;e--)i.skipBits(40),c[e]=i.readBits(1);return{modeBlockflags:c}},tN=(e,t,r)=>{switch(e){case"avc":for(let e of tc(r,t)){let t=tu(r[e.offset]);if(t>=i2.NON_IDR_SLICE&&t<=i2.SLICE_DPC)break;if(t===i2.IDR)return"key";if(t===i2.SEI&&(!ea()||en()>=144)){let t=td(r.subarray(e.offset,e.offset+e.length)),i=1;do{let e=0;for(;;){let r=t[i++];if(void 0===r||(e+=r,r<255))break}let r=0;for(;;){let e=t[i++];if(void 0===e||(r+=e,e<255))break}if(6===e){let e=new e_(t);e.pos=8*i;let r=o(e),a=e.readBits(1);if(0===r&&1===a)return"key"}i+=r}while(i<t.length-1)}}return"delta";case"hevc":for(let e of tb(r,t)){let t=ty(r[e.offset]);if(t<i3.BLA_W_LP)break;if(t<=i3.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 0==(1&r[0])?"key":"delta";case"vp9":{let e=new e_(r);if(2!==e.readBits(2))return null;let t=e.readBits(1);if(3===(e.readBits(1)<<1)+t&&e.skipBits(1),e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(let{type:t,data:i}of tA(r))if(1===t){let t=new e_(i);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";let t=new e_(i);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:D(e),i(!1)}};!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(i8||(i8={}));let tz=(e,t)=>{let r=u(e),i=0,a=r.getUint32(i,!0);i+=4;let s=d.decode(e.subarray(i,i+a));i+=a,a>0&&(t.raw??={},t.raw.vendor??=s);let n=r.getUint32(i,!0);i+=4;for(let a=0;a<n;a++){let a=r.getUint32(i,!0);i+=4;let s=d.decode(e.subarray(i,i+a));i+=a;let n=s.indexOf("=");if(-1===n)continue;let o=s.slice(0,n).toUpperCase(),l=s.slice(n+1);switch(t.raw??={},t.raw[o]??=l,o){case"TITLE":t.title??=l;break;case"DESCRIPTION":t.description??=l;break;case"ARTIST":t.artist??=l;break;case"ALBUM":t.album??=l;break;case"ALBUMARTIST":t.albumArtist??=l;break;case"COMMENT":t.comment??=l;break;case"LYRICS":t.lyrics??=l;break;case"TRACKNUMBER":{let e=l.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.trackNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.tracksTotal??=i)}break;case"TRACKTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{let e=l.split("/"),r=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(t.discNumber??=r),i&&Number.isInteger(i)&&i>0&&(t.discsTotal??=i)}break;case"DISCTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??=e)}break;case"DATE":{let e=new Date(l);Number.isNaN(e.getTime())||(t.date??=e)}break;case"GENRE":t.genre??=l;break;case"METADATA_BLOCK_PICTURE":{let e=eu(l),r=u(e),i=r.getUint32(0,!1),a=r.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=r.getUint32(8+a,!1),o=d.decode(e.subarray(12+a,12+a+n)),c=r.getUint32(a+n+28),h=e.subarray(a+n+32,a+n+32+c);t.images??=[],t.images.push({data:h,mimeType:s,kind:3===i?"coverFront":4===i?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},tU=[2,1,2,3,3,4,4,5],tL=e=>{if(e.length<7||11!==e[0]||119!==e[1])return null;let t=new e_(e);t.skipBits(16),t.skipBits(16);let r=t.readBits(2);if(3===r)return null;let i=t.readBits(6),a=t.readBits(5);if(a>8)return null;let s=t.readBits(3),n=t.readBits(3);return(1&n)!=0&&1!==n&&t.skipBits(2),(4&n)!=0&&t.skipBits(2),2===n&&t.skipBits(2),{fscod:r,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(i/2)}},tW=[128,138,192,128,140,192,160,174,240,160,176,240,192,208,288,192,210,288,224,242,336,224,244,336,256,278,384,256,280,384,320,348,480,320,350,480,384,416,576,384,418,576,448,486,672,448,488,672,512,556,768,512,558,768,640,696,960,640,698,960,768,834,1152,768,836,1152,896,974,1344,896,976,1344,1024,1114,1536,1024,1116,1536,1280,1392,1920,1280,1394,1920,1536,1670,2304,1536,1672,2304,1792,1950,2688,1792,1952,2688,2048,2228,3072,2048,2230,3072,2304,2506,3456,2304,2508,3456,2560,2786,3840,2560,2788,3840];
1new Uint8Array([5,4,65,67,45,51]),new Uint8Array([5,4,69,65,67,51]);let tq=[1,2,3,6],tV=e=>{let t,r;if(e.length<6||11!==e[0]||119!==e[1])return null;let i=new e_(e);i.skipBits(16);let a=i.readBits(2);if(i.skipBits(3),0!==a&&2!==a)return null;let s=i.readBits(11),n=i.readBits(2),o=0;3===n?(o=i.readBits(2),t=3):t=i.readBits(2);let l=i.readBits(3),c=i.readBits(1),u=i.readBits(5);if(u<11||u>16)return null;let d=tq[t];return{dataRate:Math.round((s+1)*(n<3?ts[n]/1e3:tn[o]/1e3)/(16*d)),substreams:[{fscod:n,fscod2:o,bsid:u,bsmod:0,acmod:l,lfeon:c,numDepSub:0,chanLoc:0}]}},tH=e=>{if(e.length<2)return null;let t=new e_(e),r=t.readBits(13),i=t.readBits(3),a=[];for(let r=0;r<=i&&!(Math.ceil(t.pos/8)+3>e.length);r++){let e=t.readBits(2),r=t.readBits(5);t.skipBits(1),t.skipBits(1);let i=t.readBits(3),s=t.readBits(3),n=t.readBits(1);t.skipBits(3);let o=t.readBits(4),l=0;o>0?l=t.readBits(9):t.skipBits(1),a.push({fscod:e,fscod2:null,bsid:r,bsmod:i,acmod:s,lfeon:n,numDepSub:o,chanLoc:l})}return 0===a.length?null:{dataRate:r,substreams:a}},tj=e=>{let t=e.substreams[0];return(i(t),t.fscod<3)?ts[t.fscod]:null!==t.fscod2&&t.fscod2<3?tn[t.fscod2]:null},t$=e=>{let t=e.substreams[0];i(t);let r=tU[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let i=0;i<9;i++)t.chanLoc&1<<8-i&&(r+=e[i])}return r};class tK{constructor(e){this.input=e}dispose(){}}let tX=new Uint8Array(0);class tG{constructor(e,t,r,i,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=r,this.duration=i,this.sequenceNumber=a,e===tX&&void 0===s)throw Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw TypeError('type must be either "key" or "delta".');if(!Number.isFinite(r))throw TypeError("timestamp must be a number.");if(!Number.isFinite(i)||i<0)throw TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!=typeof n||!n))throw TypeError("sideData, when provided, must be an object.");if(n?.alpha!==void 0&&!(n.alpha instanceof Uint8Array))throw TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(n?.alphaByteLength!==void 0&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===tX}get microsecondTimestamp(){return Math.trunc(Q*this.timestamp)}get microsecondDuration(){return Math.trunc(Q*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw Error("Your browser does not support EncodedVideoChunk.");
1return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"==typeof EncodedVideoChunk)throw 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 TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"==typeof EncodedAudioChunk)throw 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 TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");let r=new Uint8Array(e.byteLength);return e.copyTo(r),new tG(r,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!=typeof e||null===e))throw TypeError("options, when provided, must be an object.");if(e?.data!==void 0&&!(e.data instanceof Uint8Array))throw TypeError("options.data, when provided, must be a Uint8Array.");if(e?.type!==void 0&&"key"!==e.type&&"delta"!==e.type)throw TypeError('options.type, when provided, must be either "key" or "delta".');if(e?.timestamp!==void 0&&!Number.isFinite(e.timestamp))throw TypeError("options.timestamp, when provided, must be a number.");if(e?.duration!==void 0&&!Number.isFinite(e.duration))throw TypeError("options.duration, when provided, must be a number.");if(e?.sequenceNumber!==void 0&&!Number.isFinite(e.sequenceNumber))throw TypeError("options.sequenceNumber, when provided, must be a number.");if(e?.sideData!==void 0&&("object"!=typeof e.sideData||null===e.sideData))throw TypeError("options.sideData, when provided, must be an object.");return new tG(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}let tQ=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");if(e.codecStrings.length>0){let r=[...new Set(e.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t},tY=e=>{let t=u(e),r=0,i=t.getUint8(r);r+=4;let a=v(e.subarray(r,r+16));r+=16;let s=null;if(i>0){let i=t.getUint32(r);if(r+=4,i>0){s=[];for(let t=0;t<i;t++)s.push(v(e.subarray(r,r+16))),r+=16}}let n=t.getUint32(r);return r+=4,{systemId:a,keyIds:s,data:e.slice(r,r+n)}},tJ=(e,t)=>e.systemId===t.systemId&&ed(e.data,t.data),tZ=e=>{let t=s2(e),r=nr(e,4),i=8;1===t&&(t=s5(e),i=16);let a=t-i;return a<0?null:{name:r,totalSize:t,headerSize:i,contentSize:a}},t0=e=>s4(e)/65536,t1=e=>s4(e)/0x40000000,t2=e=>{let t=0;for(let r=0;r<4;r++){t<<=7;let r=sQ(e);if(t|=127&r,(128&r)==0)break}return t},t3=e=>{let t=sJ(e);return e.skip(2),t=Math.min(t,e.remainingLength),d.decode(sG(e,t))},t4=e=>{let t=tZ(e);if(!t||"data"!==t.name||e.remainingLength<8)return null;let r=s2(e);e.skip(4);let i=sG(e,t.contentSize-8);switch(r){case 1:return d.decode(i);case 2:return new TextDecoder("utf-16be").decode(i);case 13:return new ev(i,"image/jpeg");case 14:return new ev(i,"image/png");case 27:return new ev(i,"image/bmp");default:return i}},t8=new Uint32Array(256),t6=new Uint32Array(256),t5=new Uint32Array(256),t7=new Uint32Array(256),t9=new Uint32Array(256),re=new Uint32Array(256),rt=new Uint32Array(10),rr=!1,ri=()=>{let e=new Uint8Array(256),t=new Uint8Array(256),r=new Uint8Array(256);for(let e=0,i=1;e<256;e++)r[e]=i,t[i]=e,i=i^i<<1^(128&i?283:0);let i=(e,i)=>e&&i?r[(t[e]+t[i])%255]:0;e[0]=99;for(let i=1;i<256;i++){let a=r[255-t[i]],s=a^a<<1^a<<2^a<<3^a<<4;s=s>>>8^255&s^99,e[i]=s}for(let t=0;t<256;t++){let r=e[t],a=e.indexOf(t);t8[t]=r<<24|r<<16|r<<8|r,re[t]=a<<24|a<<16|a<<8|a;let s=i(a,14),n=i(a,9),o=s<<24|n<<16|i(a,13)<<8|i(a,11);t6[t]=o,t5[t]=o>>>8|o<<24,t7[t]=o>>>16|o<<16,t9[t]=o>>>24|o<<8}let a=1;for(let e=0;e<10;e++)rt[e]=a<<24,a=a<<1^(128&a?283:0);rr=!0};class ra{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(16/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(16),this.out=new Uint8Array(16),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){i(16===e.byteLength),i(16===t.byteLength),rr||ri();let r=new DataView(e.buffer,e.byteOffset,e.byteLength),a=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=r.getUint32(0,!1),this.roundkey[1]=r.getUint32(4,!1),this.roundkey[2]=r.getUint32(8,!1),this.roundkey[3]=r.getUint32(12,!1),this.iv[0]=a.getUint32(0,!1),this.iv[1]=a.getUint32(4,!1),this.iv[2]=a.getUint32(8,!1),this.iv[3]=a.getUint32(12,!1);for(let e=4;e<44;e+=4){let t=this.roundkey[e-1];this.roundkey[e]=this.roundkey[e-4]^0xff000000&t8[t>>>16&255]^0xff0000&t8[t>>>8&255]^65280&t8[t>>>0&255]^255&t8[t>>>24&255]^rt[e/4-1],this.roundkey[e+1]=this.roundkey[e-3]^this.roundkey[e],this.roundkey[e+2]=this.roundkey[e-2]^this.roundkey[e+1],this.roundkey[e+3]=this.roundkey[e-1]^this.roundkey[e+2]}for(let e=0,t=40;
1e<t;e+=4,t-=4)for(let r=0;r<4;r++){let i=this.roundkey[e+r];this.roundkey[e+r]=this.roundkey[t+r],this.roundkey[t+r]=i}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let r=this.roundkey[e+t];this.roundkey[e+t]=t6[255&t8[r>>>24&255]]^t5[255&t8[r>>>16&255]]^t7[255&t8[r>>>8&255]]^t9[255&t8[r>>>0&255]]}}decrypt(){let e,t,r,i,a=this.inView.getUint32(0,!1)^this.roundkey[0],s=this.inView.getUint32(4,!1)^this.roundkey[1],n=this.inView.getUint32(8,!1)^this.roundkey[2],o=this.inView.getUint32(12,!1)^this.roundkey[3],l=this.inView.getUint32(0,!1),c=this.inView.getUint32(4,!1),u=this.inView.getUint32(8,!1),d=this.inView.getUint32(12,!1);for(let l=1;l<10;l++){let c=4*l;e=t6[a>>>24]^t5[o>>>16&255]^t7[n>>>8&255]^t9[255&s]^this.roundkey[c],t=t6[s>>>24]^t5[a>>>16&255]^t7[o>>>8&255]^t9[255&n]^this.roundkey[c+1],r=t6[n>>>24]^t5[s>>>16&255]^t7[a>>>8&255]^t9[255&o]^this.roundkey[c+2],i=t6[o>>>24]^t5[n>>>16&255]^t7[s>>>8&255]^t9[255&a]^this.roundkey[c+3],a=e,s=t,n=r,o=i}let h=0xff000000&re[a>>>24&255]^0xff0000&re[o>>>16&255]^65280&re[n>>>8&255]^255&re[s>>>0&255]^this.roundkey[40],f=0xff000000&re[s>>>24&255]^0xff0000&re[a>>>16&255]^65280&re[o>>>8&255]^255&re[n>>>0&255]^this.roundkey[41],m=0xff000000&re[n>>>24&255]^0xff0000&re[s>>>16&255]^65280&re[a>>>8&255]^255&re[o>>>0&255]^this.roundkey[42],p=0xff000000&re[o>>>24&255]^0xff0000&re[n>>>16&255]^65280&re[s>>>8&255]^255&re[a>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=l,this.iv[1]=c,this.iv[2]=u,this.iv[3]=d}}let rs=(e,t,r)=>{let i=!1,a=0,s=new ra;return new ReadableStream({pull:async n=>{i||(s.init(await t()),i=!0);let o=e.requestSliceRange(a,0,65552);if(o instanceof Promise&&(o=await o),!o||0===o.length)throw Error("Invalid ciphertext.");let l=o.length;if(l%16!=0)throw Error("Invalid ciphertext.");let c=65552===l?l-16:l,u=sG(o,c),d=new Uint8Array(c);for(let e=0;e<c;e+=16)s.in.set(u.subarray(e,e+16)),s.decrypt(),d.set(s.out,e);if(c<l)n.enqueue(d),a+=c;else{let e=d[c-1];if(0===e||e>16)throw Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let t=d.subarray(0,c-e);n.enqueue(t),n.close(),r()}},cancel:()=>{r()}})};class rn extends tK{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();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return tQ({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>e.info?.type==="video"),hasAudio:this.tracks.some(e=>e.info?.type==="audio"),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??=(async()=>{let e=0,t=!1,r=!1;for(;;){let i=this.reader.requestSliceRange(e,8,16);if(i instanceof Promise&&(i=await i),!i)break;let a=e,s=tZ(i);if(!s)break;if("ftyp"===s.name||"styp"===s.name){let e=nr(i,4);this.isQuickTime="qt  "===e}else if("moov"===s.name){let e=this.reader.requestSlice(i.filePos,s.contentSize);if(e instanceof Promise&&(e=await e),!e)break;for(let t of(this.moovSlice=e,this.readContiguousBoxes(this.moovSlice),this.tracks)){let e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>a+s.totalSize,r=!0;break}else if("moof"===s.name){if(!this.input._initInput)throw Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),t=!1,r=!0;break}e=a+s.totalSize}if(!r&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){i(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),i(e);let t=s2(e),r=this.reader.fileSize-t;if(r>=0&&r<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(r,8,16);if(e instanceof Promise&&(e=await e),e){let t=tZ(e);if(t&&"mfra"===t.name){let r=this.reader.requestSlice(e.filePos,t.contentSize);r instanceof Promise&&(r=await r),r&&this.readContiguousBoxes(r)}}}}})()}async copyMetadataFromInitInput(e){let t=await e._getDemuxer();if(t.constructor!==rn)throw Error("Init input must match the input's format.");for(let e of(await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.pss
1hBoxes=t.psshBoxes,t.tracks)){let t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};e.trackBacking&&(i(t.info),"video"===t.info.type&&-1!==t.info.width?(t.trackBacking=new rl(t),this.tracks.push(t)):"audio"===t.info.type&&-1!==t.info.numberOfChannels&&(t.trackBacking=new rc(t),this.tracks.push(t)))}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;let t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,null===e.sampleTableByteOffset)return t;i(this.moovSlice);let r=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(r),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&eD.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){i(e.info?.type==="audio");let r=eG(e.info.codec),a=[],n=[];for(let i=0;i<t.sampleToChunk.length;i++){let o=t.sampleToChunk[i],l=t.sampleToChunk[i+1],c=(l?l.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let i=0;i<c;i++){let l=o.startSampleIndex+i*o.samplesPerChunk,c=l+o.samplesPerChunk,u=E(t.sampleTimingEntries,l,e=>e.startIndex),d=t.sampleTimingEntries[u],h=E(t.sampleTimingEntries,c,e=>e.startIndex),f=t.sampleTimingEntries[h],m=d.startDecodeTimestamp+(l-d.startIndex)*d.delta,p=f.startDecodeTimestamp+(c-f.startIndex)*f.delta-m,g=s(a);g&&g.delta===p?g.count++:a.push({startIndex:o.startChunkIndex+i,startDecodeTimestamp:m,count:1,delta:p});let k=o.samplesPerChunk*r.sampleSize*e.info.numberOfChannels;n.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=a,t.sampleSizes=n}if(t.sampleCompositionTimeOffsets.length>0){for(let e of(t.presentationTimestamps=[],t.sampleTimingEntries))for(let r=0;r<e.count;r++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+r*e.delta,sampleIndex:e.startIndex+r});for(let e of t.sampleCompositionTimeOffsets)for(let r=0;r<e.count;r++){let i=e.startIndex+r,a=t.presentationTimestamps[i];a&&(a.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),i(t);let r=tZ(t);i(r?.name==="moof");let a=this.reader.requestSlice(e,r.totalSize);a instanceof Promise&&(a=await a),i(a),this.traverseBox(a);let s=this.lastReadFragment;for(let[,t]of(i(s&&s.moofOffset===e),s.trackData)){let e=t.track,{fragmentPositionCache:r}=e;if(!t.startTimestampIsFinal){let i=e.fragmentLookupTable.find(e=>e.moofOffset===s.moofOffset);if(i)rm(t,i.timestamp);
1else{let e=E(r,s.moofOffset-1,e=>e.moofOffset);-1!==e&&rm(t,r[e].endTimestamp)}t.startTimestampIsFinal=!0}let i=E(r,t.startTimestamp,e=>e.startTimestamp);if((-1===i||r[i].moofOffset!==s.moofOffset)&&r.splice(i+1,0,{moofOffset:s.moofOffset,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp}),t.encryptionAuxInfo&&e.encryptionInfo){let r=await rb(this.reader,e.encryptionInfo,t.encryptionAuxInfo);for(let e=0;e<Math.min(t.samples.length,r.length);e++){let i=r[e];t.samples[e].encryption=i}}}return s}readContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8&&this.traverseBox(e););}*iterateContiguousBoxes(e){let t=e.filePos;for(;e.filePos-t<=e.length-8;){let t=e.filePos,r=tZ(e);if(!r)break;yield{boxInfo:r,slice:e},e.filePos=t+r.totalSize}}traverseBox(e){let t=e.filePos,r=tZ(e);if(!r)return!1;let n=e.filePos,o=t+r.totalSize;switch(r.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":case"wave":this.readContiguousBoxes(e.slice(n,r.contentSize));break;case"mvhd":{let t=sQ(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=s2(e),this.movieDurationInTimescale=s5(e)):(e.skip(8),this.movieTimescale=s2(e),this.movieDurationInTimescale=s2(e))}break;case"trak":{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...eI,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:"und",sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};this.currentTrack=t,this.readContiguousBoxes(e.slice(n,r.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info&&("video"===t.info.type&&-1!==t.info.width?(t.trackBacking=new rl(t),this.tracks.push(t)):"audio"===t.info.type&&-1!==t.info.numberOfChannels&&(t.trackBacking=new rc(t),this.tracks.push(t))),this.currentTrack=null}break;case"tkhd":{let t=this.currentTrack;if(!t)break;let r=sQ(e),s=sZ(e);if(t.disposition.default=!!(1&s),0===r)e.skip(8),t.id=s2(e),e.skip(4),t.durationInMovieTimescale=s2(e);else if(1===r)e.skip(16),t.id=s2(e),e.skip(4),t.durationInMovieTimescale=s5(e);else throw Error(`Incorrect track header version ${r}.`);e.skip(16);let n=a(H(rp([t0(e),t0(e),t1(e),t0(e),t0(e),t1(e),t0(e),t0(e),t1(e)]),90));i(0===n||90===n||180===n||270===n),t.rotation=n}break;case"elst":{let t=this.currentTrack;if(!t)break;let r=sQ(e);e.skip(3);let i=!1,a=0,s=s2(e);for(let n=0;n<s;n++){let s=1===r?s5(e):s2(e),n=1===r?s7(e):s4(e),o=t0(e);if(0!==s){if(i){eP._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1===n){a+=s;continue}if(1!==o){eP._warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=a,t.editListOffset=n,i=!0}}}break;case"mdhd":{let t=this.currentTrack;if(!t)break;let r=sQ(e);e.skip(3),0===r?(e.skip(8),t.timescale=s2(e),t.durationInMediaTimescale=s2(e)):1===r&&(e.skip(16),t.timescale=s2(e),t.durationInMediaTimescale=s5(e));let i=sJ(e);if(i>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&i))+t.languageCode,i>>=5;G(t.languageCode)||(t.languageCode="und")}}break;case"hdlr":{let t=this.currentTrack;if(!t)break;e.skip(8);let r=nr(e,4);"vide"===r?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,proresFormat:null}:"soun"===r&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let i=this.currentTrack;if(!i)break;i.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(n,r.contentSize))}break;case"stsd":{let t=this.currentTrack;if(!t||null===t.info||t.sampleTable)break;let r=sQ(e);e.skip(3);let i=s2(e);for(let a=0;a<i;a++){let i=e.filePos,a=tZ(e);if(!a)break;t.internalCodecId=a.name;let s=a.name.toLowerCase();if("video"===t.info.type){e.skip(24),t.info.width=sJ(e),t.info.height=sJ(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,i+a.totalSize-e.filePos));let r="encv"===s?t.frmaCodecString:s;t.frmaCodecString=null,"avc1"===r||"avc3"===r?(t.info.codec="avc",t.info.avcType="avc1"===r?1:3):"hvc1"===r||"hev1"===r?t.info.codec="hevc":"vp08"===r?t.info.codec="vp8":"vp09"===r?t.info.codec="vp9":"av01"===r?t.info.codec="av1":eV.includes(s)?(t.info.codec="prores",t.info.proresFormat=s):null===r?eP._warn("Unknown encrypted video codec due to missing frma box."):eP._warn(`Unsupported video codec (sample entry type '${a.name}').`)}else{e.skip(8);let n=sJ(e);e.skip(6);let o=sJ(e),l=sJ(e);e.skip(4);let c=s2(e)/65536,u=null;0===r&&n>0&&(1===n?(e.skip(4),l=8*s2(e),e.skip(8)):2===n&&(e.skip(4),c=nt(e),o=s2(e),e.skip(4),l=s2(e),u=s2(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=c,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,i+a.totalSize-e.filePos));let d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=48e3;else if("flac"===d)t.info.codec="flac";else if("ulaw"===d)t.info.codec="ulaw";else if("alaw"===d)t.info.codec="alaw";
1else if("ac-3"===d)t.info.codec="ac3";else if("ec-3"===d)t.info.codec="eac3";else if("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(eP._warn(`Unsupported sample size ${l} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec="pcm-s16":(eP._warn(`Unsupported sample size ${l} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(eP._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null):16===e?t.info.codec="pcm-s16be":24===e?t.info.codec="pcm-s24be":32===e?t.info.codec="pcm-s32be":(eP._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===d){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(eP._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(eP._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){let e=l+7>>3,r=!!(1&u),i=!!(2&u),a=4&u?-1:0;l>0&&l<=64&&(r?32===l&&(t.info.codec=i?"pcm-f32be":"pcm-f32"):a&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=i?"pcm-s16be":"pcm-s16":3===e?t.info.codec=i?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=i?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&eP._warn("Unsupported PCM format.")}else null===d?eP._warn("Unknown encrypted audio codec due to missing frma box."):eP._warn(`Unsupported audio codec (sample entry type '${a.name}').`)}e.filePos=i+a.totalSize}}break;case"frma":{let t=this.currentTrack;if(!t)break;t.frmaCodecString=nr(e,4).toLowerCase()}break;case"schm":{let t=this.currentTrack;if(!t)break;e.skip(4);let r=nr(e,4);"cenc"===r||"cens"===r||"cbcs"===r?t.encryptionInfo={scheme:r,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:eP._warn(`Unsupported encryption scheme '${r}'.`)}break;case"tenc":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let r=sQ(e);e.skip(3),e.skip(1);let i=sQ(e);if(r>0?(t.encryptionInfo.defaultCryptByteBlock=i>>4,t.encryptionInfo.defaultSkipByteBlock=15&i):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==sQ(e),t.encryptionInfo.defaultPerSampleIvSize=sQ(e),t.encryptionInfo.defaultKid=v(sG(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){let r=sQ(e),i=new Uint8Array(16);i.set(sG(e,r),0),t.encryptionInfo.defaultConstantIv=i}}break;case"avcC":{let t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=sG(e,r.contentSize)}break;case"hvcC":{let t=this.currentTrack;if(!t)break;i(t.info),t.info.codecDescription=sG(e,r.contentSize)}break;case"vpcC":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="video"),e.skip(4);let r=sQ(e),a=sQ(e),s=sQ(e),n=sQ(e),o=sQ(e),l=sQ(e);t.info.vp9CodecInfo={profile:r,level:a,bitDepth:s>>4,chromaSubsampling:s>>1&7,videoFullRangeFlag:1&s,colourPrimaries:n,transferCharacteristics:o,matrixCoefficients:l}}break;case"av1C":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="video"),e.skip(1);let r=sQ(e),a=r>>5,s=sQ(e),n=s>>6&1;t.info.av1CodecInfo={profile:a,level:31&r,tier:s>>7,bitDepth:2===a&&n?s>>5&1?12:10:n?10:8,monochrome:s>>4&1,chromaSubsamplingX:s>>3&1,chromaSubsamplingY:s>>2&1,chromaSamplePosition:3&s}}break;case"colr":{let t,r=this.currentTrack;if(!r)break;i(r.info?.type==="video");let a=nr(e,4);if("nclx"!==a&&"nclc"!==a)break;let s=sJ(e),n=sJ(e),o=sJ(e);
1"nclx"===a&&(t=!!(128&sQ(e))),r.info.colorSpace={primaries:p[s],transfer:k[n],matrix:y[o],fullRange:t}}break;case"pasp":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="video");let r=s2(e),a=s2(e);r>0&&a>0&&(r>a?t.info.squarePixelWidth=Math.round(t.info.width*r/a):t.info.squarePixelHeight=Math.round(t.info.height*a/r))}break;case"esds":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="audio"),e.skip(4),i(3===sQ(e)),t2(e),e.skip(2);let r=sQ(e);if((128&r)!=0&&e.skip(2),(64&r)!=0){let t=sQ(e);e.skip(t)}(32&r)!=0&&e.skip(2),i(4===sQ(e));let a=t2(e),s=e.filePos,n=sQ(e);if(64===n||103===n?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===n,objectType:null}):105===n||107===n?t.info.codec="mp3":221===n?t.info.codec="vorbis":eP._warn(`Unsupported audio codec (objectTypeIndication ${n}) - discarding track.`),e.skip(12),a>e.filePos-s){i(5===sQ(e));let r=t2(e);if(t.info.codecDescription=sG(e,r),"aac"===t.info.codec){let e=eF(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="audio"),t.info.pcmLittleEndian=!!(255&sJ(e))}break;case"pcmC":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="audio"),e.skip(4);let r=sQ(e);t.info.pcmLittleEndian=!!(1&r),t.info.pcmSampleSize=sQ(e)}break;case"dOps":{let t,r=this.currentTrack;if(!r)break;i(r.info?.type==="audio"),e.skip(1);let a=sQ(e),s=sJ(e),n=s2(e),o=s0(e),l=sQ(e);t=0!==l?sG(e,2+a):new Uint8Array(0);let c=new Uint8Array(19+t.byteLength),u=new DataView(c.buffer);u.setUint32(0,0x4f707573,!1),u.setUint32(4,0x48656164,!1),u.setUint8(8,1),u.setUint8(9,a),u.setUint16(10,s,!0),u.setUint32(12,n,!0),u.setInt16(16,o,!0),u.setUint8(18,l),c.set(t,19),r.info.codecDescription=c,r.info.numberOfChannels=a}break;case"dfLa":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="audio"),e.skip(4);let r=e.filePos;for(;e.filePos<o;){let r=sQ(e),i=sZ(e);if((127&r)===i8.STREAMINFO){e.skip(10);let r=s2(e),i=r>>>12,a=(r>>9&7)+1;t.info.sampleRate=i,t.info.numberOfChannels=a,e.skip(20)}else e.skip(i);if(128&r)break}let a=e.filePos;e.filePos=r;let s=sG(e,a-r),n=new Uint8Array(4+s.byteLength);new DataView(n.buffer).setUint32(0,0x664c6143,!1),n.set(s,4),t.info.codecDescription=n}break;case"dac3":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="audio");let r=new e_(sG(e,3)),a=r.readBits(2);r.skipBits(8);let s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=ts[a]),t.info.numberOfChannels=tU[s]+n}break;case"dec3":{let t=this.currentTrack;if(!t)break;i(t.info?.type==="audio");let a=tH(sG(e,r.contentSize));if(!a){eP._warn("Invalid dec3 box contents, ignoring.");break}let s=tj(a);null!==s&&(t.info.sampleRate=s),t.info.numberOfChannels=t$(a)}break;case"stts":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let r=s2(e),i=0,a=0;for(let s=0;s<r;s++){let r=s2(e),s=s2(e);t.sampleTable.sampleTimingEntries.push({startIndex:i,startDecodeTimestamp:a,count:r,delta:s}),i+=r,a+=r*s}}break;case"ctts":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let r=s2(e),i=0;for(let a=0;a<r;a++){let r=s2(e),a=s4(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:i,count:r,offset:a}),i+=r}}break;case"stsz":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let r=s2(e),i=s2(e);if(0===r)for(let r=0;r<i;r++){let r=s2(e);t.sampleTable.sampleSizes.push(r)}else t.sampleTable.sampleSizes.push(r)}break;case"stz2":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let r=sQ(e),i=s2(e),a=new e_(sG(e,Math.ceil(i*r/8)));for(let e=0;e<i;e++){let e=a.readBits(r);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let r=s2(e);for(let i=0;i<r;i++){let r=s2(e)-1;t.sampleTable.keySampleIndices.push(r)}0!==t.sampleTable.keySampleIndices[0]&&t.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let r=s2(e);for(let i=0;i<r;i++){let r=s2(e)-1,i=s2(e),a=s2(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:r,samplesPerChunk:i,sampleDescriptionIndex:a})}let i=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)t.sampleTable.sampleToChunk[e].startSampleIndex=i,e<t.sampleTable.sampleToChunk.length-1&&(i+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk)}break;case"stco":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let r=s2(e);for(let i=0;i<r;i++){let r=s2(e);t.sampleTable.chunkOffsets.push(r)}}break;case"co64":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let r=s2(e);for(let i=0;i<r;i++){let r=s5(e);t.sampleTable.chunkOffsets.push(r)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(n,r.contentSize));break;case"mehd":{let t=sQ(e);e.skip(3);let r=1===t?s5(e):s2(e);this.movieDurationInTimescale=r}break;case"trex":{e.skip(4);let t=s2(e),r=s2(e),i=s2(e),a=s2(e),s=s2(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:r,defaultSampleDuration:i,defaultSampleSize:a,defaultSampleFlags:s})}break;case"tfra":{let t=sQ(e);e.skip(3);let r=s2(e),i=this.tracks.find(e=>e.id===r);if(!i)break;let a=s2(e),s=[sQ,sJ,sZ,s2],n=s[(48&a)>>4],o=s[(12&a)>>2],l=s[3&a],c=s2(e);for(let r=0;r<c;r++){let r=1===t?s5(e):s2(e),a=1===t?s5(e):s2(e);n(e),o(e),l(e),i.fragmentLookupTable.push({timestamp:r,moofOffset:a})}i.fragmentLookupTable.sort((e,t)=>
1e.timestamp-t.timestamp);for(let e=0;e<i.fragmentLookupTable.length-1;e++){let t=i.fragmentLookupTable[e],r=i.fragmentLookupTable[e+1];t.timestamp===r.timestamp&&(i.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:r.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(n,r.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(i(this.currentFragment),this.readContiguousBoxes(e.slice(n,r.contentSize)),this.currentTrack){let e=this.currentFragment.trackData.get(this.currentTrack.id);e:if(e){if(0===e.samples.length){this.currentFragment.trackData.delete(this.currentTrack.id);break e}e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let t=0;t<e.presentationTimestamps.length;t++){let r=e.presentationTimestamps[t],i=e.samples[r.sampleIndex];null===e.firstKeyFrameTimestamp&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.presentationTimestamp),t<e.presentationTimestamps.length-1&&(i.duration=e.presentationTimestamps[t+1].presentationTimestamp-r.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],r=e.samples[s(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=r.presentationTimestamp+r.duration;let{currentFragmentState:a}=this.currentTrack;i(a),null!==a.startTimestamp&&(rm(e,a.startTimestamp),e.startTimestampIsFinal=!0),a.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=a.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=tY(sG(e,r.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case"tfhd":{i(this.currentFragment),e.skip(1);let t=sZ(e),r=s2(e),a=this.tracks.find(e=>e.id===r);if(!a)break;let s=this.fragmentTrackDefaults.find(e=>e.trackId===r);this.currentTrack=a,a.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:s?.defaultSampleDescriptionIndex??null,defaultSampleDuration:s?.defaultSampleDuration??null,defaultSampleSize:s?.defaultSampleSize??null,defaultSampleFlags:s?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},1&t?a.currentFragmentState.baseDataOffset=s5(e):131072&t&&(a.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),2&t&&(a.currentFragmentState.sampleDescriptionIndex=s2(e)),8&t&&(a.currentFragmentState.defaultSampleDuration=s2(e)),16&t&&(a.currentFragmentState.defaultSampleSize=s2(e)),32&t&&(a.currentFragmentState.defaultSampleFlags=s2(e)),65536&t&&(a.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let t=this.currentTrack;if(!t)break;i(t.currentFragmentState);let r=sQ(e);e.skip(3);let a=0===r?s2(e):s5(e);t.currentFragmentState.startTimestamp=a}break;case"trun":{let t,r=this.currentTrack;if(!r)break;i(this.currentFragment),i(r.currentFragmentState);let a=sQ(e),s=sZ(e),n=!!(256&s),o=!!(512&s),l=!!(1024&s),c=!!(2048&s),u=s2(e),d=null;1&s&&(d=s4(e));let h=null;4&s&&(h=s2(e)),this.currentFragment.trackData.has(r.id)?(t=this.currentFragment.trackData.get(r.id),null!==d&&(t.currentOffset=r.currentFragmentState.baseDataOffset+d)):(t={track:r,currentTimestamp:0,currentOffset:r.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(r.id,t));for(let s=0;s<u;s++){let u,d,f;n?u=s2(e):(i(null!==r.currentFragmentState.defaultSampleDuration),u=r.currentFragmentState.defaultSampleDuration),o?d=s2(e):(i(null!==r.currentFragmentState.defaultSampleSize),d=r.currentFragmentState.defaultSampleSize),l?f=s2(e):(i(null!==r.currentFragmentState.defaultSampleFlags),f=r.currentFragmentState.defaultSampleFlags),0===s&&null!==h&&(f=h);let m=0;c&&(m=0===a?s2(e):s4(e));let p=!(65536&f);t.samples.push({presentationTimestamp:t.currentTimestamp+m,duration:u,byteOffset:t.currentOffset,byteSize:d,isKeyFrame:p,encryption:null}),t.currentOffset+=d,t.currentTimestamp+=u}this.currentFragment.implicitBaseDataOffset=t.currentOffset}break;case"saiz":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),1&sZ(e)){let r=nr(e,4),i=s2(e);if(r!==t.encryptionInfo.scheme||0!==i)break}let r=sQ(e),i=s2(e),a=null;0===r&&i>0&&(a=sG(e,i));let s=rk(t);s.defaultSampleInfoSize=r,s.sampleSizes=a,s.sampleCount=i}break;case"saio":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let r=sQ(e);if(1&sZ(e)){let r=nr(e,4),i=s2(e);if(r!==t.encryptionInfo.scheme||0!==i)break}let i=s2(e);if(0===i)break;i>1&&eP._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===r?s2(e):Number(s5(e));this.currentFragment&&(a+=this.currentFragment.moofOffset),rk(t).offset=a}break;case"senc":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;i(this.currentFragment);let r=this.currentFragment.trackData.get(t.id);if(!r)break;e.skip(1);let a=!!(2&sZ(e)),s=s2(e),n=t.encryptionInfo.defaultPerSampleIvSize;i(null!==n);for(let i=0;i<Math.min(s,r.samples.length);i++){let s=new Uint8Array(16);n>0?s.set(sG(e,n),0):s.set(t.encryptionInfo.defaultConstantIv,0);let o=null;if(a){let t=sJ(e);o=[];for(let r=0;r<t;r++){let t=sJ(e),r=s2(e);o.push({clearLen:t,protectedLen:r})}}r.samples[i].encryption={iv:s,subsamples:o}}}break;case"udta":for(let{boxInfo:t,slice:i}of this.iterateContiguousBoxes(e.slice(n,r.contentSize))){if("meta"!==t.name&&!this.currentTrack){let e=i.filePos;this.metadataTags.raw??={},"\xa9"===t.name[0]?this.metadataTags.raw[t.name]??=t3(i):this.metadataTags.raw[t.name]??=sG(i,t.contentSize),i.filePos=e}switch(t.name){case"meta":i.skip(-t.headerSize),this.traverseBox(i);break;case"\xa9nam":case"name":this.currentTrack?this.currentTrack.name=d.decode(sG(i,t.contentSize)):this.metadataTags.title??=t3(i);break;case"\xa9des":this.currentTrack||(this.metadataTags.description??=t3(i));break;case"\xa9ART":this.currentTrack||(this.metadataTags.artist??=t3(i));break;
1case"\xa9alb":this.currentTrack||(this.metadataTags.album??=t3(i));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=t3(i));break;case"\xa9gen":this.currentTrack||(this.metadataTags.genre??=t3(i));break;case"\xa9day":if(!this.currentTrack){let e=new Date(t3(i));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"\xa9cmt":this.currentTrack||(this.metadataTags.comment??=t3(i));break;case"\xa9lyr":this.currentTrack||(this.metadataTags.lyrics??=t3(i))}}break;case"meta":{if(this.currentTrack)break;let t=s2(e);this.currentMetadataKeys=new Map,0!==t?this.readContiguousBoxes(e.slice(n,r.contentSize)):this.readContiguousBoxes(e.slice(n+4,r.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let t=s2(e);for(let r=0;r<t;r++){let t=s2(e);e.skip(4);let i=d.decode(sG(e,t-8));this.currentMetadataKeys.set(r+1,i)}}break;case"ilst":if(!this.currentMetadataKeys)break;for(let{boxInfo:t,slice:i}of this.iterateContiguousBoxes(e.slice(n,r.contentSize))){let e=t.name,r=(e.charCodeAt(0)<<24)+(e.charCodeAt(1)<<16)+(e.charCodeAt(2)<<8)+e.charCodeAt(3);this.currentMetadataKeys.has(r)&&(e=this.currentMetadataKeys.get(r));let a=t4(i);switch(this.metadataTags.raw??={},this.metadataTags.raw[e]??=a,e){case"\xa9nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof a&&(this.metadataTags.title??=a);break;case"\xa9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof a&&(this.metadataTags.description??=a);break;case"\xa9ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof a&&(this.metadataTags.artist??=a);break;case"\xa9alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof a&&(this.metadataTags.album??=a);break;case"aART":case"album_artist":"string"==typeof a&&(this.metadataTags.albumArtist??=a);break;case"\xa9cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof a&&(this.metadataTags.comment??=a);break;case"\xa9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof a&&(this.metadataTags.genre??=a);break;case"\xa9lyr":case"lyrics":"string"==typeof a&&(this.metadataTags.lyrics??=a);break;case"\xa9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof a){let e=new Date(a);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"covr":case"com.apple.quicktime.artwork":a instanceof ev?(this.metadataTags.images??=[],this.metadataTags.images.push({data:a.data,kind:"coverFront",mimeType:a.mimeType})):a instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:a,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof a){let e=a.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){let e=u(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),r>0&&(this.metadataTags.tracksTotal??=r)}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){let e=u(a),t=e.getUint16(2,!1),r=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),r>0&&(this.metadataTags.discsTotal??=r)}}}}return e.filePos=o,!0}}class ro{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),r=0;for(let i of e.tracks)if(i.trackBacking.getType()===t&&r++,i===this.internalTrack)break;return r}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;i(e.trackBacking);let t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return(t?.timestamp??0)+e.durationInMediaTimescale/e.timescale}
1async getLiveRefreshInterval(){return null}async getFirstPacket(e){let t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return V(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){let r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=ru(i,r),s=await this.fetchPacketForSampleIndex(a,t);return rg(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let i=E(t.presentationTimestamps,r,e=>e.presentationTimestamp);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):s}async getNextPacket(e,t){let r=this.packetToSampleIndex.get(e);if(void 0!==r)return this.fetchPacketForSampleIndex(r+1,t);let i=this.packetToFragmentLocation.get(e);if(void 0===i)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(i.fragment,e=>{if(e===i.fragment){let t=e.trackData.get(this.internalTrack.id);if(i.sampleIndex+1<t.samples.length)return{sampleIndex:i.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let r=this.mapTimestampIntoTimescale(e),i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=rd(i,r),s=await this.fetchPacketForSampleIndex(a,t);return rg(i)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let i=F(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=r);return{sampleIndex:-1!==i?t.presentationTimestamps[i].sampleIndex:-1,correctSampleFound:-1!==i&&r<t.endTimestamp}},r,r,t):s}async getNextKeyPacket(e,t){let r=this.packetToSampleIndex.get(e);if(void 0!==r){let e=rf(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r);return this.fetchPacketForSampleIndex(e,t)}let a=this.packetToFragmentLocation.get(e);if(void 0===a)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(a.fragment,e=>{if(e===a.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>a.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){let e=t.samples.findIndex(e=>e.isKeyFrame);return i(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){let r;if(-1===e)return null;let a=rh(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!a)return null;if(t.metadataOnly)r=tX;else{let t=this.internalTrack.demuxer.reader.requestSlice(a.sampleOffset,a.sampleSize);if(t instanceof Promise&&(t=await t),!t)return null;if(r=sG(t,a.sampleSize),this.internalTrack.encryptionAuxInfo){i(this.internalTrack.encryptionInfo);let t=await rb(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<t.length&&(r=await ry(this.internalTrack,t[e],r,null))}}let s=(a.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=a.duration/this.internalTrack.timescale,o=new tG(r,a.isKeyFrame?"key":"delta",s,n,e,a.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,r){let a;if(-1===t)return null;let s=e.trackData.get(this.internalTrack.id).samples[t];if(i(s),r.metadataOnly)a=tX;else{let t=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(t instanceof Promise&&(t=await t),!t)return null;a=sG(t,s.byteSize),s.encryption&&(a=await ry(this.internalTrack,s.encryption,a,e))}let n=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=s.duration/this.internalTrack.timescale,l=ne
1w tG(a,s.isKeyFrame?"key":"delta",n,o,e.moofOffset+t,s.byteSize);return this.packetToFragmentLocation.set(l,{fragment:e,sampleIndex:t}),l}async performFragmentedLookup(e,t,r,a,s){let n,o=this.internalTrack.demuxer,l=null,c=null,u=-1;if(e){let{sampleIndex:r,correctSampleFound:i}=t(e);if(i)return this.fetchPacketInFragment(e,r,s);-1!==r&&(c=e,u=r)}let d=E(this.internalTrack.fragmentLookupTable,r,e=>e.timestamp),h=-1!==d?this.internalTrack.fragmentLookupTable[d]:null,f=E(this.internalTrack.fragmentPositionCache,r,e=>e.startTimestamp),m=-1!==f?this.internalTrack.fragmentPositionCache[f]:null,p=Math.max(h?.moofOffset??0,m?.moofOffset??0)||null;for(e?null===p||e.moofOffset>=p?(n=e.moofOffset+e.moofSize,l=e):n=p:n=p??0;;){if(l){let e=l.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=o.reader.requestSliceRange(n,8,16);if(e instanceof Promise&&(e=await e),!e)break;let r=n,i=tZ(e);if(!i)break;if("moof"===i.name){let{sampleIndex:e,correctSampleFound:i}=t(l=await o.readFragment(r));if(i)return this.fetchPacketInFragment(l,e,s);-1!==e&&(c=l,u=e)}n=r+i.totalSize}if(h&&(!c||c.moofOffset<h.moofOffset)){let e=this.internalTrack.fragmentLookupTable[d-1];i(!e||e.timestamp<h.timestamp);let r=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,r,a,s)}return c?this.fetchPacketInFragment(c,u,s):null}}class rl extends ro{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}
1async canBeTransparent(){return"prores"===this.internalTrack.info.codec&&("ap4h"===this.internalTrack.info.proresFormat||"ap4x"===this.internalTrack.info.proresFormat)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){let e=await this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&tF(e.data)}}else{let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&tB(e.data)}let e={codec:ej(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 rc extends ro{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:eK(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}:null}}let ru=(e,t)=>{if(e.presentationTimestamps){let r=E(e.presentationTimestamps,t,e=>e.presentationTimestamp);return -1===r?-1:e.presentationTimestamps[r].sampleIndex}{let r=E(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===r)return -1;let i=e.sampleTimingEntries[r];return i.startIndex+Math.min(Math.floor((t-i.startDecodeTimestamp)/i.delta),i.count-1)}},rd=(e,t)=>{if(!e.keySampleIndices)return ru(e,t);if(e.presentationTimestamps){let r=E(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===r)return -1;for(let t=r;t>=0;t--){let r=e.presentationTimestamps[t].sampleIndex;if(-1!==I(e.keySampleIndices,r,e=>e))return r}return -1}{let r=ru(e,t),i=E(e.keySampleIndices,r,e=>e);return e.keySampleIndices[i]??-1}},rh=(e,t)=>{let r=E(e.sampleTimingEntries,t,e=>e.startIndex),a=e.sampleTimingEntries[r];if(!a||a.startIndex+a.count<=t)return null;let s=a.startDecodeTimestamp+(t-a.startIndex)*a.delta,n=E(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),o=e.sampleCompositionTimeOffsets[n];o&&t-o.startIndex<o.count&&(s+=o.offset);let l=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=E(e.sampleToChunk,t,e=>e.startSampleIndex),u=e.sampleToChunk[c];i(u);let d=u.startChunkIndex+Math.floor((t-u.startSampleIndex)/u.samplesPerChunk),h=e.chunkOffsets[d],f=u.startSampleIndex+(d-u.startChunkIndex)*u.samplesPerChunk,m=0,p=h;if(1===e.sampleSizes.length)p+=l*(t-f),m+=l*u.samplesPerChunk;else for(let r=f;r<f+u.samplesPerChunk;r++){let i=e.sampleSizes[r];r<t&&(p+=i),m+=i}let g=a.delta;if(e.presentationTimestamps){let r=e.presentationTimestampIndexMap[t];i(void 0!==r),r<e.presentationTimestamps.length-1&&(g=e.presentationTimestamps[r+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:p,sampleSize:l,chunkOffset:h,chunkSize:m,isKeyFrame:!e.keySampleIndices||-1!==I(e.keySampleIndices,t,e=>e)}},rf=(e,t)=>{if(!e.keySampleIndices)return t+1;let r=E(e.keySampleIndices,t,e=>e);return e.keySampleIndices[r+1]??-1},rm=(e,t)=>{for(let r of(e.startTimestamp+=t,e.endTimestamp+=t,e.samples))r.presentationTimestamp+=t;for(let r of e.presentationTimestamps)r.presentationTimestamp+=t},rp=e=>{let[t,r]=e,i=Math.atan2(r,t);return Number.isFinite(i)?180/Math.PI*i:0},rg=e=>0===e.sampleSizes.length,rk=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleC
1ount:0,offset:null,resolved:null},rb=async(e,t,r)=>{if(r.resolved)return r.resolved;if(null===r.offset||0===r.sampleCount)throw Error("Incomplete saiz/saio info; cannot resolve encryption data.");let a=0;if(r.defaultSampleInfoSize>0)a=r.defaultSampleInfoSize*r.sampleCount;else{i(r.sampleSizes);for(let e=0;e<r.sampleCount;e++)a+=r.sampleSizes[e]}let s=e.requestSlice(r.offset,a);if(s instanceof Promise&&(s=await s),!s)throw Error("Failed to read auxiliary encryption info.");let n=t.defaultPerSampleIvSize;i(null!==n);let o=[];for(let e=0;e<r.sampleCount;e++){let i=r.defaultSampleInfoSize>0?r.defaultSampleInfoSize:r.sampleSizes[e],a=new Uint8Array(16);n>0?a.set(sG(s,n),0):a.set(t.defaultConstantIv,0);let l=null;if(i>n){let e=sJ(s);l=[];for(let t=0;t<e;t++){let e=sJ(s),t=s2(s);l.push({clearLen:e,protectedLen:t})}}o.push({iv:a,subsamples:l})}return r.resolved=o,o},ry=async(e,t,r,a)=>{let s;i(e.encryptionInfo);let n=e.encryptionInfo;i(null!==n.defaultKid);let o=n.defaultKid,l=e.demuxer.decryptionKeyCache.get(o);if(l)s=await l;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");let t=(async()=>{let t=e.demuxer.psshBoxes;if(a){t=[...t,...a.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(o));for(let e=0;e<t.length-1;e++)for(let r=e+1;r<t.length;r++)tJ(t[e],t[r])&&(t.splice(r,1),r--)}let r=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:o,psshBoxes:t});if(!("string"==typeof r&&32===r.length&&P.test(r)||r instanceof Uint8Array&&16===r.byteLength))throw TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return r instanceof Uint8Array?r:x(r)})();e.demuxer.decryptionKeyCache.set(o,t),s=await t}return"cenc"===n.scheme||"cens"===n.scheme?rT(s,n,t,r):rw(s,n,t,r)},rT=async(e,t,r,a)=>{let s=new Uint8Array(16);s.set(r.iv,0);let n=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),o=async e=>new Uint8Array(await crypto.subtle.decrypt({name:"AES-CTR",counter:s,length:64},n,e));if(!r.subsamples)return o(a);i(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);let l=rS(r.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let e of l)for(let t of e.perSubsample)c+=t.length;let u=new Uint8Array(c),d=0;for(let e of l)for(let t of e.perSubsample)u.set(a.subarray(t.offset,t.offset+t.length),d),d+=t.length;let h=await o(u),f=new Uint8Array(a),m=0;for(let e of l)for(let t of e.perSubsample)f.set(h.subarray(m,m+t.length),t.offset),m+=t.length;return f},rw=(e,t,r,a)=>{let s=new ra;s.init({key:e,iv:r.iv});let n=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(i(null!==n&&null!==o),!r.subsamples){let e=new Uint8Array(a),t=Math.floor(a.length/16);for(let r=0;r<t;r++){let t=16*r;s.in.set(a.subarray(t,t+16)),s.decrypt(),e.set(s.out,t)}return e}if(0===n&&0===o)throw Error("cbcs with subsamples requires pattern encryption.");let l=new Uint8Array(a),c=rS(r.subsamples,n,o),u=new DataView(r.iv.buffer,r.iv.byteOffset,16);for(let e of c)for(let t of(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),e.perSubsample)){let e=t.length/16;for(let r=0;r<e;r++){let e=t.offset+16*r;s.in.set(a.subarray(e,e+16)),s.decrypt(),l.set(s.out,e)}}return l},rS=(e,t,r)=>{let i=[],a=0!==t||0!==r,s=0;for(let n of e){s+=n.clearLen;let e=[];
1if(a){let i=n.protectedLen,a=s;for(;i>0&&!(i<16*t);){let s=16*t;e.push({offset:a,length:s}),a+=s;let n=Math.min(16*r,i-=s);a+=n,i-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;i.push({perSubsample:e})}return i};!function(e){e[e.EBML=0x1a45dfa3]="EBML",e[e.EBMLVersion=17030]="EBMLVersion",e[e.EBMLReadVersion=17143]="EBMLReadVersion",e[e.EBMLMaxIDLength=17138]="EBMLMaxIDLength",e[e.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",e[e.DocType=17026]="DocType",e[e.DocTypeVersion=17031]="DocTypeVersion",e[e.DocTypeReadVersion=17029]="DocTypeReadVersion",e[e.Void=236]="Void",e[e.Segment=0x18538067]="Segment",e[e.SeekHead=0x114d9b74]="SeekHead",e[e.Seek=19899]="Seek",e[e.SeekID=21419]="SeekID",e[e.SeekPosition=21420]="SeekPosition",e[e.Duration=17545]="Duration",e[e.Info=0x1549a966]="Info",e[e.TimestampScale=2807729]="TimestampScale",e[e.MuxingApp=19840]="MuxingApp",e[e.WritingApp=22337]="WritingApp",e[e.Tracks=0x1654ae6b]="Tracks",e[e.TrackEntry=174]="TrackEntry",e[e.TrackNumber=215]="TrackNumber",e[e.TrackUID=29637]="TrackUID",e[e.TrackType=131]="TrackType",e[e.FlagEnabled=185]="FlagEnabled",e[e.FlagDefault=136]="FlagDefault",e[e.FlagForced=21930]="FlagForced",e[e.FlagOriginal=21934]="FlagOriginal",e[e.FlagHearingImpaired=21931]="FlagHearingImpaired",e[e.FlagVisualImpaired=21932]="FlagVisualImpaired",e[e.FlagCommentary=21935]="FlagCommentary",e[e.FlagLacing=156]="FlagLacing",e[e.Name=21358]="Name",e[e.Language=2274716]="Language",e[e.LanguageBCP47=2274717]="LanguageBCP47",e[e.CodecID=134]="CodecID",e[e.CodecPrivate=25506]="CodecPrivate",e[e.CodecDelay=22186]="CodecDelay",e[e.SeekPreRoll=22203]="SeekPreRoll",e[e.DefaultDuration=2352003]="DefaultDuration",e[e.Video=224]="Video",e[e.PixelWidth=176]="PixelWidth",e[e.PixelHeight=186]="PixelHeight",e[e.DisplayWidth=21680]="DisplayWidth",e[e.DisplayHeight=21690]="DisplayHeight",e[e.DisplayUnit=21682]="DisplayUnit",e[e.AlphaMode=21440]="AlphaMode",e[e.Audio=225]="Audio",e[e.SamplingFrequency=181]="SamplingFrequency",e[e.Channels=159]="Channels",e[e.BitDepth=25188]="BitDepth",e[e.SimpleBlock=163]="SimpleBlock",e[e.BlockGroup=160]="BlockGroup",e[e.Block=161]="Block",e[e.BlockAdditions=30113]="BlockAdditions",e[e.BlockMore=166]="BlockMore",e[e.BlockAdditional=165]="BlockAdditional",e[e.BlockAddID=238]="BlockAddID",e[e.BlockDuration=155]="BlockDuration",e[e.ReferenceBlock=251]="ReferenceBlock",e[e.Cluster=0x1f43b675]="Cluster",e[e.Timestamp=231]="Timestamp",e[e.Cues=0x1c53bb6b]="Cues",e[e.CuePoint=187]="CuePoint",e[e.CueTime=179]="CueTime",e[e.CueTrackPositions=183]="CueTrackPositions",e[e.CueTrack=247]="CueTrack",e[e.CueClusterPosition=241]="CueClusterPosition",e[e.Colour=21936]="Colour",e[e.MatrixCoefficients=21937]="MatrixCoefficients",e[e.TransferCharacteristics=21946]="TransferCharacteristics",e[e.Primaries=21947]="Primaries",e[e.Range=21945]="Range",e[e.Projection=30320]="Projection",e[e.ProjectionType=30321]="ProjectionType",e[e.ProjectionPoseRoll=30325]="ProjectionPoseRoll",e[e.Attachments=0x1941a469]="Attachments",e[e.AttachedFile=24999]="AttachedFile",e[e.FileDescription=18046]="FileDescription",e[e.FileName=18030]="FileName",e[e.FileMediaType=18016]="FileMediaType",e[e.FileData=18012]="FileData",e[e.FileUID=18094]="FileUID",e[e.Chapters=0x1043a770]="Chapters",e[e.Tags=0x1254c367]="Tags",e[e.Tag=29555]="Tag",e[e.Targets=25536]="Targets",e[e.TargetTypeValue=26826]="TargetTypeValue",e[e.TargetType=25546]="TargetType",e[e.TagTrackUID=25541]="TagTrackUID",e[e.TagEditionUID=25545]="TagEditionUID",e[e.TagChapterUID=25540]="TagChapterUID",e[e.TagAttachmentUID=25542]="TagAttachmentUID",e[e.SimpleTag=26568]="SimpleTag",e[e.TagName=17827]="TagName",e[e.TagLanguage=17530]="TagLanguage",e[e.TagString=17543]="TagString",e[e.TagBinary=17541]="TagBinary",e[e.ContentEncodings=28032]="ContentEncodings",e[e.ContentEncoding=25152]="ContentEncoding",e[e.ContentEncodingOrder=20529]="ContentEncodingOrder",e[e.ContentEncodingScope=20530]="ContentEncodingScope",e[e.ContentCompression=20532]="ContentCompression",e[e.ContentCompAlgo=16980]="ContentCompAlgo",e[e.ContentCompSettings=16981]="ContentCompSettings",e[e.ContentEncryption=20533]="ContentEncryption"}(i6||(i6={}));let rP=[i6.EBML,i6.Segment],rv=[i6.SeekHead,i6.Info,i6.Cluster,i6.Tracks,i6.Cues,i6.Attachments,i6.Chapters,i6.Tags],rx=[...rP,...rv],rC=e=>{if(e.remainingLength<1)return null;let t=sQ(e);if(e.skip(-1),0===t)return null;let r=1,i=128;for(;(t&i)==0;)r++,i>>=1;return e.remainingLength<r?null:r},rI=e=>{if(e.remainingLength<1)return null;let t=sQ(e);if(0===t)return null;let r=1,i=128;for(;(t&i)==0;)r++,i>>=1;if(e.remainingLength<r-1)return null;let a=t&i-1;for(let t=1;t<r;t++)a*=256,a+=sQ(e);return a},rE=(e,t)=>{if(t<1||t>8)throw Error("Bad unsigned int size "+t);let r=0;for(let i=0;i<t;i++)r*=256,r+=sQ(e);return r},r_=(e,t)=>
1{if(t<1)throw Error("Bad unsigned int size "+t);let r=0n;for(let i=0;i<t;i++)r<<=8n,r+=BigInt(sQ(e));return r},rB=e=>{let t=rC(e);return null===t||e.remainingLength<t?null:rE(e,t)},rA=e=>{if(e.remainingLength<1)return null;if(255===sQ(e))return;e.skip(-1);let t=rI(e);return null===t?null:0x100000000000000!==t?t:void 0},rF=e=>{i(e.remainingLength>=2);let t=rB(e);if(null===t)return null;let r=rA(e);return null===r?null:{id:t,size:r}},rM=(e,t)=>{let r=sG(e,t),i=0;for(;i<t&&0!==r[i];)i+=1;return String.fromCharCode(...r.subarray(0,i))},rR=(e,t)=>{let r=sG(e,t),i=0;for(;i<t&&0!==r[i];)i+=1;return d.decode(r.subarray(0,i))},rD=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw Error("Bad float size "+t);return 4===t?ne(e):nt(e)},rO=async(e,t,r,i)=>{let a=new Set(r),s=t;for(;null===i||s<i;){let t=e.requestSliceRange(s,2,16);if(t instanceof Promise&&(t=await t),!t)break;let r=rF(t);if(!r)break;if(a.has(r.id))return{pos:s,found:!0};rU(r.size),s=t.filePos+r.size}return{pos:null!==i&&i>s?i:s,found:!1}},rN=async(e,t,r,i)=>{let a=new Set(r),s=t;for(;s<i;){let t=e.requestSliceRange(s,0,Math.min(65536,i-s));if(t instanceof Promise&&(t=await t),!t||t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=s;let e=rB(t);if(null!==e&&a.has(e))return s;s++}}return null},rz={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3"};function rU(e){if(void 0===e)throw Error("Undefined element size is used in a place where it is not supported.")}let rL=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");if(e.codecStrings.length>0){let r=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${r.join(", ")}"`}return t};!function(e){e[e.None=0]="None",e[e.Xiph=1]="Xiph",e[e.FixedSize=2]="FixedSize",e[e.Ebml=3]="Ebml"}(i5||(i5={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(i7||(i7={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(i9||(i9={}));let rW=[{id:i6.SeekHead,flag:"seekHeadSeen"},{id:i6.Info,flag:"infoSeen"},{id:i6.Tracks,flag:"tracksSeen"},{id:i6.Cues,flag:"cuesSeen"}];class rq extends tK{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();let e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return rL({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>e.info?.type==="video")),hasAudio:this.segments.some(e=>e.tracks.some(e=>e.info?.type==="audio")),codecStrings:t.filter(Boolean)})}async getMetadataTags(){for(let e of(await this.readMetadata(),this.segments))e.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(e),e.metadataTagsCollected=!0);let e={};for(let t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,16);if(t instanceof Promise&&(t=await t),!t)break;let r=rF(t);if(!r)break;let i=r.id,a=r.size,n=t.filePos;if(i===i6.EBML){rU(a);let e=this.reader.requestSlice(n,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(i===i6.Segment){if(await this.readSegment(n,a),void 0===a||null===this.reader.fileSize)break}else if(i===i6.Cluster){if(null===this.reader.fileSize)break;void 0===a&&(a=(await rO(this.reader,n,rx,this.reader.fileSize)).pos-n);let e=s(this.segments);e&&(e.elementEndPos=n+a)}rU(a),e=n+a}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||r<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(r,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=r,i=rF(e);if(!i||!rv.includes(i.id)&&i.id!==i6.Void){let e=await rN(this.reader,t,rv,Math.min(this.currentSegment.elementEndPos??1/0,t+0xa00000));if(e){r=e;continue}break}let{id:a,size:s}=i,n=e.filePos,o=rW.findIndex(e=>e.id===a);if(-1!==o){let e=rW[o].flag;this.currentSegment[e]=!0,rU(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===i6.Tags||a===i6.Attachments){a===i6.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,rU(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===i6.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;r=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>
1e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(let t of this.currentSegment.seekEntries){let r=rW.find(e=>e.id===t.id);if(!r||this.currentSegment[r.flag])continue;let i=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(i instanceof Promise&&(i=await i),!i)continue;let a=rF(i);if(!a)continue;let{id:s,size:n}=a;if(s!==r.id)continue;rU(n),this.currentSegment[r.flag]=!0;let o=this.reader.requestSlice(i.filePos,n);o instanceof Promise&&(o=await o),o&&this.readContiguousElements(o)}for(let e of(-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3),this.currentSegment.tracks))null!==e.defaultDurationNs&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);let i=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=i.get(e.trackId);t&&t.cuePoints.push(e)}for(let e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){let r=e.cuePoints[t],i=e.cuePoints[t+1];r.time===i.time&&(e.cuePoints.splice(t+1,1),t--)}}let a=null,s=-1/0;for(let e of this.currentSegment.tracks)e.cuePoints.length>s&&(s=e.cuePoints.length,a=e);for(let e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,16);r instanceof Promise&&(r=await r),i(r);let a=rF(r);i(a),i(a.id===i6.Cluster);let n=a.size,o=r.filePos;void 0===n&&(n=(await rO(this.reader,o,rx,t.elementEndPos)).pos-o);let l=this.reader.requestSlice(o,n);l instanceof Promise&&(l=await l);let c={segment:t,elementStartPos:e,elementEndPos:o+n,dataStartPos:o,timestamp:-1,trackData:new Map};for(let[,t]of(this.currentCluster=c,l&&(c.elementEndPos=this.readContiguousElements(l,rx)),c.trackData)){let r=t.track;i(t.blocks.length>0);let a=!1;for(let e=0;e<t.blocks.length;e++){let r=t.blocks[e];r.timestamp+=c.timestamp,a||=r.lacing!==i5.None}t.presentationTimestamps=t.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<t.presentationTimestamps.length;e++){let i=t.presentationTimestamps[e],a=t.blocks[i.blockIndex];null===t.firstKeyFrameTimestamp&&a.isKeyFrame&&(t.firstKeyFrameTimestamp=a.timestamp),e<t.presentationTimestamps.length-1?a.duration=t.presentationTimestamps[e+1].timestamp-a.timestamp:0===a.duration&&null!=r.defaultDuration&&a.lacing===i5.None&&(a.duration=r.defaultDuration)}a&&(this.expandLacedBlocks(t.blocks,r),t.presentationTimestamps=t.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let n=t.blocks[t.presentationTimestamps[0].blockIndex],o=t.blocks[s(t.presentationTimestamps).blockIndex];t.startTimestamp=n.timestamp,t.endTimestamp=o.timestamp+o.duration;let l=E(r.clusterPositionCache,t.startTimestamp,e=>e.startTimestamp);(-1===l||r.clusterPositionCache[l].elementStartPos!==e)&&r.clusterPositionCache.splice(l+1,0,{elementStartPos:c.elementStartPos,startTimestamp:t.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let r=e.trackData.get(t);if(!r){let i=e.segment.tracks.find(e=>e.id===t);if(!i)return null;r={track:i,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,r)}return r}expandLacedBlocks(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(a.lacing===i5.None)continue;a.decoded||(a.data=this.decodeBlockData(t,a.data),a.decoded=!0);let s=sK.tempFromBytes(a.data),n=[],o=sQ(s)+1;switch(a.lacing){case i5.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;s.bufferPos<s.length;){let r=sQ(s);if(t+=r,r<255){n.push(t),e+=t;break}}}n.push(s.length-(s.bufferPos+e))}break;case i5.FixedSize:{let e=Math.floor((s.length-1)/o);for(let t=0;t<o;t++)n.push(e)}break;case i5.Ebml:{let e=rI(s);i(null!==e);let t=e;n.push(t);let r=t;for(let e=1;e<o-1;e++){let e=s.bufferPos,a=rI(s);i(null!==a),t+=a-((1<<7*(s.bufferPos-e)-1)-1),n.push(t),r+=t}n.push(s.length-(s.bufferPos+r))}break;default:i(!1)}i(n.length===o),e.splice(r,1);let l=a.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){let i=sG(s,n[t]),c=a.timestamp+l*t/o,u=l/o;e.splice(r+t,0,{timestamp:c,duration:u,isKeyFrame:a.isKeyFrame,data:i,lacing:i5.None,decoded:!0,postProcessed:!1,mainAdditional:a.mainAdditional})}r+=o,r--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if((t.id!==i6.Tags||e.tagsSeen)&&(t.id!==i6.Attachments||e.attachmentsSeen))continue;let r=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let a=rF(r);if(!a||a.id!==t.id)continue;let{size:s}=a;rU(s),i(!this.currentSegment),this.currentSegment=e;let n=this.reader.requestSlice(r.filePos,s);n instanceof Promise&&(n=await n),n&&this.readContiguousElements(n),this.currentSegment=null,t.id===i6.Tags?e.tagsSeen=!0:t.id===i6.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let r=e.filePos;if(!this.traverseElement(e,t))return r}return e.filePos}traverseElement(e,t){let r=rF(e);if(!r||t&&t.includes(r.id))return!1;let{id:s,size:n}=r,o=e.filePos;switch(rU(n),s){case i6.DocType:this.isWebM="webm"===rM(e,n);break;case i6.Seek:{if(!this.currentSegment)break;let t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(o,n)),(-1===t.id||-1===t.segmentPosition)&&this.currentSegment.seekEntries.pop()}break;case i6.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=rE(e,n)}break;case i6.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=rE(e,n)}break;case i6.TimestampScale:if(!this.currentSegment)break;
1this.currentSegment.timestampScale=rE(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case i6.Duration:if(!this.currentSegment)break;this.currentSegment.duration=rD(e,n);break;case i6.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...eI,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(o,n)),!this.currentTrack))break;if(this.currentTrack.decodingInstructions.some(e=>e.data?.type!=="decompress"||e.scope!==i7.Block||e.data.algorithm!==i9.HeaderStripping)&&(eP._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){let e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){let e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===rz.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===rz.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===rz.vp8)this.currentTrack.info.codec="vp8";else if(t===rz.vp9)this.currentTrack.info.codec="vp9";else if(t===rz.av1)this.currentTrack.info.codec="av1";else if(t===rz.prores){let e=this.currentTrack.codecPrivate?d.decode(this.currentTrack.codecPrivate):"";eV.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new rH(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===rz.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===rz.mp3?this.currentTrack.info.codec="mp3":t===rz.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=48e3):t===rz.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rz.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rz.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rz.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));let e=this.currentTrack;this.currentTrack.trackBacking=new rj(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case i6.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=rE(e,n);break;
1case i6.TrackType:{if(!this.currentTrack)break;let t=rE(e,n);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case i6.FlagEnabled:if(!this.currentTrack)break;rE(e,n)||(this.currentTrack=null);break;case i6.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!rE(e,n);break;case i6.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!rE(e,n);break;case i6.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!rE(e,n);break;case i6.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!rE(e,n);break;case i6.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!rE(e,n);break;case i6.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!rE(e,n);break;case i6.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=rM(e,n);break;case i6.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=sG(e,n);break;case i6.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=rE(e,n);break;case i6.Name:if(!this.currentTrack)break;this.currentTrack.name=rR(e,n);break;case i6.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=rM(e,n),G(this.currentTrack.languageCode)||(this.currentTrack.languageCode="und");break;case i6.LanguageBCP47:{if(!this.currentTrack)break;let t=rM(e,n).split("-")[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode="und",this.currentTrack.hasLanguageBcp47=!0}break;case i6.Video:if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,n));break;case i6.PixelWidth:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=rE(e,n);break;case i6.PixelHeight:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=rE(e,n);break;case i6.DisplayWidth:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=rE(e,n);break;case i6.DisplayHeight:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=rE(e,n);break;case i6.DisplayUnit:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=rE(e,n);break;case i6.AlphaMode:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=1===rE(e,n);break;case i6.Colour:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,n));break;case i6.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=y[rE(e,n)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case i6.Range:if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===rE(e,n);break;case i6.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=k[rE(e,n)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case i6.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=p[rE(e,n)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case i6.Projection:if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,n));break;case i6.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let t=rD(e,n);try{this.currentTrack.info.rotation=a(-t)}catch{}}break;case i6.Audio:if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(o,n));break;case i6.SamplingFrequency:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=rD(e,n);break;case i6.Channels:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=rE(e,n);break;case i6.BitDepth:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=rE(e,n);break;case i6.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;
1case i6.CueTime:this.currentCueTime=rE(e,n);break;case i6.CueTrackPositions:{if(null===this.currentCueTime)break;i(this.currentSegment);let t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(o,n)),(-1===t.trackId||-1===t.clusterPosition)&&this.currentSegment.cuePoints.pop()}break;case i6.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=rE(e,n)}break;case i6.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;i(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+rE(e,n)}break;case i6.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=rE(e,n);break;case i6.SimpleBlock:{if(!this.currentCluster)break;let t=rI(e);if(null===t)break;let r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;let i=s0(e),a=sQ(e),s=!!(128&a);r.track.info?.type==="audio"&&r.track.info.codec&&(s=!0);let l=sG(e,n-(e.filePos-o)),c=r.track.decodingInstructions.length>0;r.blocks.push({timestamp:i,duration:0,isKeyFrame:s,data:l,lacing:a>>1&3,decoded:!c,postProcessed:!1,mainAdditional:null})}break;case i6.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case i6.Block:{if(!this.currentCluster)break;let t=rI(e);if(null===t)break;let r=this.getTrackDataInCluster(this.currentCluster,t);if(!r)break;let i=s0(e),a=sQ(e),s=sG(e,n-(e.filePos-o)),l=r.track.decodingInstructions.length>0;this.currentBlock={timestamp:i,duration:0,isKeyFrame:!0,data:s,lacing:a>>1&3,decoded:!l,postProcessed:!1,mainAdditional:null},r.blocks.push(this.currentBlock)}break;case i6.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case i6.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(o,n)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case i6.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=sG(e,n);break;case i6.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=rE(e,n);break;case i6.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=rE(e,n);break;case i6.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case i6.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case i6.Targets:this.readContiguousElements(e.slice(o,n));break;case i6.TargetTypeValue:50!==rE(e,n)&&(this.currentTagTargetIsMovie=!1);break;case i6.TagTrackUID:case i6.TagEditionUID:case i6.TagChapterUID:case i6.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case i6.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case i6.TagName:this.currentSimpleTagName=rR(e,n);break;case i6.TagString:{if(!this.currentSimpleTagName)break;let t=rR(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case i6.TagBinary:{if(!this.currentSimpleTagName)break;let t=sG(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case i6.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(o,n));let t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??={},t.raw[this.currentAttachedFile.fileUid.toString()]=new ex(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){let e=this.currentAttachedFile.fileName,r="unknown";if(e){let t=e.toLowerCase();t.startsWith("cover.")?r="coverFront":t.startsWith("back.")&&(r="coverBack")}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:r,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case i6.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=r_(e,n);break;case i6.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=rR(e,n);break;case i6.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=rM(e,n);break;case i6.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=sG(e,n);break;case i6.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=rR(e,n);break;case i6.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,n)),this.currentTrack.decodingInstructions.sort((e,t)=>
1t.order-e.order);break;case i6.ContentEncoding:this.currentDecodingInstruction={order:0,scope:i7.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case i6.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=rE(e,n);break;case i6.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=rE(e,n);break;case i6.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:i9.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case i6.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=rE(e,n);break;case i6.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=sG(e,n);break;case i6.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,t){i(e.decodingInstructions.length>0);let r=t;for(let t of e.decodingInstructions)if(i(t.data),"decompress"===t.data.type&&t.data.algorithm===i9.HeaderStripping&&t.data.settings&&t.data.settings.length>0){let e=t.data.settings,i=new Uint8Array(e.length+r.length);i.set(e,0),i.set(r,e.length),r=i}return r}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let r=this.currentSegment.metadataTags;if(r.raw??={},r.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":r.title??=t;break;case"description":r.description??=t;break;case"artist":r.artist??=t;break;case"album":r.album??=t;break;case"album_artist":r.albumArtist??=t;break;case"genre":r.genre??=t;break;case"comment":r.comment??=t;break;case"lyrics":r.lyrics??=t;break;case"date":{let e=new Date(t);Number.isNaN(e.getTime())||(r.date??=e)}break;case"track_number":case"part_number":{let e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??=a)}break;case"disc_number":case"disc":{let e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??=i),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??=a)}}}}class rV{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){let e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType(),r=0;for(let i of e.segments)for(let e of i.tracks)if(e.trackBacking.getType()===t&&r++,e===this.internalTrack)break;return r}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.internalTrack.segment;if(e.duration<=0)return null;let t=e.duration/e.timestampFactor,r=await this.getFirstPacket({metadataOnly:!0});return t+(r?.timestamp??0)}
1async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return V(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let i=E(t.presentationTimestamps,r,e=>e.timestamp);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)}async getNextPacket(e,t){let r=this.packetToClusterLocation.get(e);if(void 0===r)throw Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){let t=e.trackData.get(this.internalTrack.id);if(r.blockIndex+1<t.blocks.length)return{blockIndex:r.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let r=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let i=F(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=r);return{blockIndex:-1!==i?t.presentationTimestamps[i].blockIndex:-1,correctBlockFound:-1!==i&&r<t.endTimestamp}},r,r,t)}async getNextKeyPacket(e,t){let r=this.packetToClusterLocation.get(e);if(void 0===r)throw Error("Packet was not created from this track.");return this.performClusterLookup(r.cluster,e=>{if(e===r.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>r.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){let e=t.blocks.findIndex(e=>e.isKeyFrame);return i(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,r){if(-1===t)return null;let a=e.trackData.get(this.internalTrack.id).blocks[t];if(i(a),a.decoded||(a.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,a.data),a.decoded=!0),!a.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(a.data.length>=8&&105===a.data[4]&&99===a.data[5]&&112===a.data[6]&&102===a.data[7])){let e=new Uint8Array(a.data.length+8);u(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(a.data,8),a.data=e}a.postProcessed=!0}let s=r.metadataOnly?tX:a.data,n=a.timestamp/this.internalTrack.segment.timestampFactor,o=a.duration/this.internalTrack.segment.timestampFactor,l={};a.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=r.metadataOnly?tX:a.mainAdditional,l.alphaByteLength=a.mainAdditional.byteLength);let c=new tG(s,a.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,a.data.byteLength,l);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,r,a,s){let n,{demuxer:o,segment:l}=this.internalTrack,c=null,u=null,d=-1;if(e){let{blockIndex:r,correctBlockFound:i}=t(e);if(i)return this.fetchPacketInCluster(e,r,s);-1!==r&&(u=e,d=r)}let h=E(this.internalTrack.cuePoints,r,e=>e.time),f=-1!==h?this.internalTrack.cuePoints[h]:null,m=E(this.internalTrack.clusterPositionCache,r,e=>e.startTimestamp),p=-1!==m?this.internalTrack.clusterPositionCache[m]:null,g=Math.max(f?.clusterPosition??0,p?.elementStartPos??0)||null;for(e?null===g||e.elementStartPos>=g?(n=e.elementEndPos,c=e):n=g:n=g??l.clusterSeekStartPos;null===l.elementEndPos||n<=l.elementEndPos-2;){if(c){let e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>a)break}let e=o.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let r=n,h=rF(e);if(!h||!rv.includes(h.id)&&h.id!==i6.Void){let e=await rN(o.reader,r,rv,Math.min(l.elementEndPos??1/0,r+0xa00000));if(e){n=e;continue}break}let f=h.id,m=h.size,p=e.filePos;if(f===i6.Cluster){m=(c=await o.readCluster(r,l)).elementEndPos-p;let{blockIndex:e,correctBlockFound:i}=t(c);if(i)return this.fetchPacketInCluster(c,e,s);-1!==e&&(u=c,d=e)}void 0===m&&(i(f!==i6.Cluster),m=(await rO(o.reader,p,rx,l.elementEndPos)).pos-p);let g=p+m;if(null===l.elementEndPos){let e=o.reader.requestSliceRange(g,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(rB(e)===i6.Segment){l.elementEndPos=g;break}}n=g}if(f&&(!u||u.elementStartPos<f.clusterPosition)){let e=this.internalTrack.cuePoints[h-1];i(!e||e.time<f.time);let r=e?.time??-1/0;return this.performClusterLookup(null,t,r,a,s)}return u?this.fetchPacketInCluster(u,d,s):null}}class rH extends rV{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"video"}getCodec(){return this.internalTrack.info.codec}getCodedWidth(){return this.internalTrack.info.width}getCodedHeight(){return this.internalTrack.info.height}getSquarePixelWidth(){return this.internalTrack.info.squarePixelWidth}getSquarePixelHeight(){return this.internalTrack.info.squarePixelHeight}getRotation(){return this.internalTrack.info.rotation}async getColorSpace(){return{primaries:this.internalTrack.info.colorSpace?.primaries,transfer:this.internalTrack.info.colorSpace?.transfer,matrix:this.internalTrack.info.colorSpace?.matrix,fullRange:this.internalTrack.info.colorSpace?.fullRange}}
1async canBeTransparent(){return this.internalTrack.info.alphaMode||"prores"===this.internalTrack.info.codec&&("ap4h"===this.internalTrack.info.proresFormat||"ap4x"===this.internalTrack.info.proresFormat)}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??=(async()=>{let e=null;"vp9"!==this.internalTrack.info.codec&&"av1"!==this.internalTrack.info.codec&&("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)&&("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)||(e=await this.getFirstPacket({}));let t={codec:ej({width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&e?tf(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?tw(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?tB(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?tF(e.data):null,proresFormat:this.internalTrack.info.proresFormat}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace??void 0};return(this.internalTrack.info.width!==this.internalTrack.info.squarePixelWidth||this.internalTrack.info.height!==this.internalTrack.info.squarePixelHeight)&&(t.displayAspectWidth=this.internalTrack.info.squarePixelWidth,t.displayAspectHeight=this.internalTrack.info.squarePixelHeight),t})():null}}class rj extends rV{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfig??={codec:eK({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}}let r$=async(e,t,r,i=null)=>{let a=t;for(;null===r||a<r;){let t=null!==r?Math.min(65536,r-a):65536,s=e.requestSliceRange(a,4,t);if(s instanceof Promise&&(s=await s),!s||s.length<4)break;for(;s.remainingLength>=4;){let t=s.filePos,r=tr(s2(s),null!==e.fileSize?e.fileSize-a:null);if(r.header&&(!i||r.header.sampleRate===i.sampleRate&&r.header.mpegVersionId===i.mpegVersionId&&r.header.layer===i.layer&&ta(r.header.channel)===ta(i.channel)))return{header:r.header,startPos:a};s.filePos=t+r.bytesAdvanced,a=s.filePos}}return null};class rK extends tK{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new S,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw Error("No valid MP3 frame found.");this.trackBackings=[new rX(this)]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,ns);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=nc(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await r$(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e){this.lastSampleLoaded=!0;return}let t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;let r=tt(t.mpegVersionId,t.channel),i=this.reader.requestSlice(e.startPos+r,4);if(i instanceof Promise&&(i=await i),i){let a=s2(i);if(0x58696e67===a||0x496e666f===a){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+r+4,12);if(t instanceof Promise&&(t=await t),t){let e=u(sG(t,12)),r=e.getUint32(0,!1);this.xingData={frameCount:r&i1.FrameCount?e.getUint32(4,!1):null,fileSize:r&i1.FileSize?e.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);let a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let r=this.reader.requestSlice(e,ns);if(r instanceof Promise&&(r=await r),!r)break;let i=nc(r);if(!i)break;t=!0;let a=this.reader.requestSlice(r.filePos,i.size);if(a instanceof Promise&&(a=await a),!a)break;nu(a,i,this.metadataTags),e=r.filePos+i.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=na){let e=this.reader.requestSlice(this.reader.fileSize-na,na);e instanceof Promise&&(e=await e),i(e);let t=nr(e,3);"TAG"===t&&no(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class rX{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){let e=this.demuxer;if(i(null!==e.firstFrameHeader),i(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){let t=te(e.firstFrameHeader.lowSamplingFrequency,e.firstFrameHeader.layer,e.firstFrameHeader.bitrate,e.firstFrameHeader.sampleRate);return Math.round((e.reader.fileSize-e.firstFrameHeaderPos)/t)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}return null}
1async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return"und"}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return i(this.demuxer.firstFrameHeader),ta(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...eI}}async getDecoderConfig(){return i(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:ta(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){let r;if(-1===e)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;if(t.metadataOnly)r=tX;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=sG(e,i.dataSize)}return new tG(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let r=I(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw Error("Packet was not created from this track.");let i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let r=E(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let rG=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=0x80000000&t?t<<1^0x4c11db7:t<<1;rG[e]=t>>>0}let rQ=e=>{let t=u(e),r=t.getUint32(22,!0);t.setUint32(22,0,!0);let i=0;for(let t=0;t<e.length;t++)i=(i<<8^rG[i>>>24^e[t]])>>>0;return t.setUint32(22,r,!0),i},rY=(e,t,r)=>{let a=0,s=null;if(e.length>0)if("vorbis"===t.codec){i(t.vorbisInfo);let n=(1<<K(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let l=r,c=t.vorbisInfo.modeBlockflags[o];if(s=t.vorbisInfo.blocksizes[c],1===c){let r=e[0]&(1|n)+1?1:0;l=t.vorbisInfo.blocksizes[r]}a=null!==l?l+s>>2:0}else"opus"===t.codec&&(a=tD(e).durationInSamples);return{durationInSamples:a,vorbisBlockSize:s}},rJ=e=>{let t="audio/ogg";if(e.codecStrings){let r=[...new Set(e.codecStrings)];t+=`; codecs="${r.join(", ")}"`}return t},rZ=e=>{let t=e.filePos;if(0x5367674f!==s3(e))return null;e.skip(1);let r=sQ(e),i=s9(e),a=s3(e),s=s3(e),n=s3(e),o=sQ(e),l=new Uint8Array(o);for(let t=0;t<o;t++)l[t]=sQ(e);let c=27+o,u=l.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:c+u,dataStartPos:t+c,dataSize:u,headerType:r,granulePosition:i,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:l}},r0=(e,t)=>{for(;e.filePos<t-3;){let t=s3(e),r=255&t,i=t>>>8&255,a=t>>>16&255,s=t>>>24&255;if(79===r||79===i||79===a||79===s){if(e.skip(-4),0x5367674f===t)return!0;e.skip(1)}}return!1};class r1 extends tK{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,27,282);if(t instanceof Promise&&(t=await t),!t)break;let r=rZ(t);if(!r||!(2&r.headerType))break;this.bitstreams.push({serialNumber:r.serialNumber,bosPage:r,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=r.headerStartPos+r.totalSize}for(let e of this.bitstreams){let t=await this.readPacket(e.bosPage,0);t&&(t.data.byteLength>=7&&1===t.data[0]&&118===t.data[1]&&111===t.data[2]&&114===t.data[3]&&98===t.data[4]&&105===t.data[5]&&115===t.data[6]?await this.readVorbisMetadata(t,e):t.data.byteLength>=8&&79===t.data[0]&&112===t.data[1]&&117===t.data[2]&&115===t.data[3]&&72===t.data[4]&&101===t.data[5]&&97===t.data[6]&&100===t.data[7]&&await this.readOpusMetadata(t,e),null!==e.codecInfo.codec&&this.trackBackings.push(new r2(e,this)))}})()}async readVorbisMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i||!(r=await this.findNextPacketStart(i)))return;let a=await this.readPacket(r.startPage,r.startSegmentIndex);if(!a||3!==i.data[0]||5!==a.data[0])return;let s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(i.data.length);let o=new Uint8Array(1+s.length+e.data.length+i.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(i.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+i.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;let l=u(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);let c=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&c),1<<(c>>4)],modeBlockflags:tO(a.data).modeBlockflags},tz(i.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let r=await this.findNextPacketStart(e);if(!r)return;let i=await this.readPacket(r.startPage,r.startSegmentIndex);if(!i)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=i;let a=tM(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=48e3,t.codecInfo.opusInfo={preSkip:a.preSkip},tz(i.data.subarray(8),this.metadataTags)}async readPacket(e,t){i(t<e.lacingValues.length);let r=0;for(let i=0;i<t;i++)r+=e.lacingValues[i];let a=e,s=r,n=t,o=[];t:for(;;){let t=this.reader.requestSlice(a.dataStartPos,a.dataSize);t instanceof Promise&&(t=await t),i(t);let l=sG(t,a.dataSize);for(;;){if(n===a.lacingValues.length){o.push(l.subarray(r,s));break}let e=a.lacingValues[n];if(s+=e,e<255){o.push(l.subarray(r,s));break t}n++}let c=a.headerStartPos+a.totalSize;
1for(;;){let t=this.reader.requestSliceRange(c,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let r=rZ(t);if(!r)return null;if((a=r).serialNumber===e.serialNumber)break;c=a.headerStartPos+a.totalSize}r=0,s=0,n=0}let l=o.reduce((e,t)=>e+t.length,0);if(0===l)return null;let c=new Uint8Array(l),u=0;for(let e=0;e<o.length;e++){let t=o[e];c.set(t,u),u+=t.length}return{data:c,endPage:a,endSegmentIndex:n}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(4&e.endPage.headerType)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let r=this.reader.requestSliceRange(t,27,282);if(r instanceof Promise&&(r=await r),!r)return null;let i=rZ(r);if(!i)return null;if(i.serialNumber===e.endPage.serialNumber)return{startPage:i,startSegmentIndex:0};t=i.headerStartPos+i.totalSize}}async getMimeType(){return await this.readMetadata(),rJ({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class r2{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new S,this.internalSampleRate="opus"===e.codecInfo.codec?48e3:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){let e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return i(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
1async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return i(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...eI,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(i(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,r){if(!e)return null;let{durationInSamples:i,vorbisBlockSize:a}=rY(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new tG(r.metadataOnly?tX:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,i/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:i,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),s}async getFirstPacket(e){i(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let r=0;"opus"===this.bitstream.codecInfo.codec&&(i(this.bitstream.codecInfo.opusInfo),r-=this.bitstream.codecInfo.opusInfo.preSkip);let a=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(a,{timestampInSamples:r,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let r=this.encodedPacketToMetadata.get(e);if(!r)throw Error("Packet was not created from this track.");let i=await this.demuxer.findNextPacketStart(r.packet);if(!i)return null;let a=r.timestampInSamples+r.durationInSamples,s=await this.demuxer.readPacket(i.startPage,i.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:r.vorbisBlockSize},t)}async getPacket(e,t){let r,a;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);let s=V(e*this.internalSampleRate);if(0===s)return this.getFirstPacket(t);if(s<0)return null;i(this.bitstream.lastMetadataPacket);let n=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!n)return null;let o=n.startPage,l=this.demuxer.reader.fileSize,c=[o];t:for(;o.headerStartPos+o.totalSize<l;){let e=Math.floor((o.headerStartPos+l)/2),t=e;for(;;){let r=Math.min(t+65307,l-27),a=this.demuxer.reader.requestSlice(t,r-t);if(a instanceof Promise&&(a=await a),i(a),!r0(a,r)){l=e+27;continue t}let n=this.demuxer.reader.requestSliceRange(a.filePos,27,282);n instanceof Promise&&(n=await n),i(n);let u=rZ(n);i(u);let d=!1;if(u.serialNumber===this.bitstream.serialNumber)d=!0;else{let e=this.demuxer.reader.requestSlice(u.headerStartPos,u.totalSize);e instanceof Promise&&(e=await e),i(e),d=rQ(sG(e,u.totalSize))===u.checksum}if(!d){t=u.headerStartPos+4;continue}if(d&&u.serialNumber!==this.bitstream.serialNumber||-1===u.granulePosition){t=u.headerStartPos+u.totalSize;continue}this.granulePositionToTimestampInSamples(u.granulePosition)>s?l=u.headerStartPos:(o=u,c.push(u));continue t}}let u=n.startPage;for(let e of c){if(e.granulePosition===o.granulePosition)break;(!u||e.headerStartPos>u.headerStartPos)&&(u=e)}let d=u,h=[d];for(;d.serialNumber!==this.bitstream.serialNumber||d.granulePosition!==o.granulePosition;){let e=d.headerStartPos+d.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),i(t);let r=rZ(t);i(r),(d=r).serialNumber===this.bitstream.serialNumber&&h.push(d)}i(-1!==d.granulePosition);let f=null,m=d,p=0;if(d.headerStartPos===n.startPage.headerStartPos)r=this.granulePositionToTimestampInSamples(0),a=!0,f=0;else{r=0,a=!1;for(let e=d.lacingValues.length-1;e>=0;e--)if(d.lacingValues[e]<255){f=e+1;break}if(null===f)throw Error("Invalid page with granule position: no packets end on this page.");let e={data:tX,endPage:m,endSegmentIndex:p=f-1};if(await this.demuxer.findNextPacketStart(e)){let e=r4(h,d,f);i(e);let t=r3(h,e.page,e.segmentIndex);t&&(d=t.page,f=t.segmentIndex)}else for(;;){let e=r4(h,d,f);if(!e)break;let t=r3(h,e.page,e.segmentIndex);if(!t)break;
1if(d=t.page,f=t.segmentIndex,e.page.headerStartPos!==m.headerStartPos){m=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==d;){i(null!==f);let e=await this.demuxer.readPacket(d,f);if(!e)break;if(!(d.headerStartPos===n.startPage.headerStartPos&&f<n.startSegmentIndex)){let n=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:r,vorbisLastBlocksize:k?.vorbisBlockSize??null},t);i(n);let o=this.encodedPacketToMetadata.get(n);if(i(o),a||e.endPage.headerStartPos!==m.headerStartPos||e.endSegmentIndex!==p?r+=o.durationInSamples:(r=this.granulePositionToTimestampInSamples(d.granulePosition),a=!0,i(n=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:r-o.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},t)),i(o=this.encodedPacketToMetadata.get(n))),g=n,k=o,a&&(Math.max(r,0)>s||Math.max(o.timestampInSamples,0)===s))break}let o=await this.demuxer.findNextPacketStart(e);if(!o)break;d=o.startPage,f=o.startSegmentIndex}return g}async getPacketSequential(e,t){let r=await this.sequentialScanMutex.acquire();try{let r,a=V(e*this.internalSampleRate);e=a/this.internalSampleRate;let n=E(this.sequentialScanCache,a,e=>e.timestampInSamples);if(-1!==n){let e=this.sequentialScanCache[n];r=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else r=await this.getFirstPacket(t);let o=0;for(;r&&r.timestamp<e;){let a=await this.getNextPacket(r,t);if(!a||a.timestamp>e)break;if(r=a,o++,100===o){o=0;let e=this.encodedPacketToMetadata.get(r);i(e),this.sequentialScanCache.length>0&&i(s(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return r}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let r3=(e,t,r)=>{let a=t,s=r;t:for(;;){for(s--;s>=0;s--)if(a.lacingValues[s]<255){s++;break t}if(i(-1===s),!(1&a.headerType)){s=0;break}let t=A(e,e=>e.headerStartPos<a.headerStartPos);if(!t)return null;s=(a=t).lacingValues.length}if(i(-1!==s),s===a.lacingValues.length){let t=e[e.indexOf(a)+1];i(t),a=t,s=0}return{page:a,segmentIndex:s}},r4=(e,t,r)=>{if(r>0)return{page:t,segmentIndex:r-1};let i=A(e,e=>e.headerStartPos<t.headerStartPos);return i?{page:i,segmentIndex:i.lacingValues.length-1}:null};!function(e){e[e.PCM=1]="PCM",e[e.IEEE_FLOAT=3]="IEEE_FLOAT",e[e.ALAW=6]="ALAW",e[e.MULAW=7]="MULAW",e[e.EXTENSIBLE=65534]="EXTENSIBLE"}(ae||(ae={}));class r8 extends tK{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,12);e instanceof Promise&&(e=await e),i(e);let t=nr(e,4),r="RIFX"!==t,a="RF64"===t,s=s1(e,r),n=a?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==nr(e,4))throw Error("Invalid WAVE file - wrong format");let o=0,l=null,c=e.filePos;for(;null===n||c<n;){let e=this.reader.requestSlice(c,8);if(e instanceof Promise&&(e=await e),!e)break;let t=nr(e,4),i=s1(e,r),s=e.filePos;if(a&&0===o&&"ds64"!==t)throw Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===t)await this.parseFmtChunk(s,i,r);else if("data"===t){if(l??=i,this.dataStart=e.filePos,this.dataSize=Math.min(l,(n??1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===t){let e=this.reader.requestSlice(s,i);if(e instanceof Promise&&(e=await e),!e)break;let t=s6(e,r);l=s6(e,r),n=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(s,i,r):("ID3 "===t||"id3 "===t)&&await this.parseId3Chunk(s,i);c=s+i+(1&i),o++}if(!this.audioInfo)throw Error('Invalid WAVE file - missing "fmt " chunk');if(-1===this.dataStart)throw Error('Invalid WAVE file - missing "data" chunk');let u=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/u)*u,this.trackBackings.push(new r6(this))})()}async parseFmtChunk(e,t,r){let i,a=this.reader.requestSlice(e,t);if(a instanceof Promise&&(a=await a),!a)return;let s=sY(a,r),n=sY(a,r),o=s1(a,r);a.skip(4);let l=sY(a,r);if((i=14===t?8:sY(a,r),t>=18&&357!==s)&&Math.min(t-18,sY(a,r))>=22&&s===ae.EXTENSIBLE){a.skip(6);let e=sG(a,16);s=e[0]|e[1]<<8}if((s===ae.MULAW||s===ae.ALAW)&&(i=8),s!==ae.PCM&&s!==ae.IEEE_FLOAT&&s!==ae.ALAW&&s!==ae.MULAW)throw Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and μ-law are supported.`);if(s===ae.PCM&&![8,16,24,32].includes(i))throw Error(`Unsupported WAVE PCM bit depth (${i}). Only 8, 16, 24, and 32 bits are supported.`);if(s===ae.IEEE_FLOAT&&![32,64].includes(i))throw Error(`Unsupported WAVE float bit depth (${i}). Only 32 and 64 bits are supported.`);this.audioInfo={format:s,numberOfChannels:n,sampleRate:o,sampleSizeInBytes:Math.ceil(i/8),blockSizeInBytes:l}}async parseListChunk(e,t,r){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let a=nr(i,4);if("INFO"!==a&&"INF0"!==a)return;let s=i.filePos;for(;s<=e+t-8;){i.filePos=s;let e=nr(i,4),t=s1(i,r),a=sG(i,t),n=0;for(let e=0;e<a.length&&0!==a[e];e++)n++;let o=String.fromCharCode(...a.subarray(0,n));switch(this.metadataTags.raw??={},this.metadataTags.raw[e]=o,e){case"INAM":case"TITL":this.metadataTags.title??=o;break;case"TIT3":this.metadataTags.description??=o;break;case"IART":this.metadataTags.artist??=o;break;case"IPRD":this.metadataTags.album??=o;break;case"IPRT":case"ITRK":case"TRCK":{let e=o.split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(this.metadataTags.tracksTotal??=r)}break;case"ICRD":case"IDIT":{let e=new Date(o);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"YEAR":{let e=Number.parseInt(o,10);Number.isInteger(e)&&e>
10&&(this.metadataTags.date??=new Date(e,0,1))}break;case"IGNR":case"GENR":this.metadataTags.genre??=o;break;case"ICMT":case"CMNT":case"COMM":this.metadataTags.comment??=o}s+=8+t+(1&t)}}async parseId3Chunk(e,t){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let i=nc(r);if(i){let a=t-ns;i.size=Math.min(i.size,a),i.size>0&&nu(r.slice(e+ns,i.size),i,this.metadataTags)}}getCodec(){if(i(this.audioInfo),this.audioInfo.format===ae.MULAW)return"ulaw";if(this.audioInfo.format===ae.ALAW)return"alaw";if(this.audioInfo.format===ae.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";else if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";else if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";else if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===ae.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";else if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}i(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class r6{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(i(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return i(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}
1async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...eI}}async getPacketAtIndex(e,t){let r;i(e>=0),i(this.demuxer.audioInfo);let a=2048*e*this.demuxer.audioInfo.blockSizeInBytes;if(a>=this.demuxer.dataSize)return null;let s=Math.min(2048*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-a);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,s);if(e instanceof Promise&&(e=await e),!e)return null}if(t.metadataOnly)r=tX;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+a,s);e instanceof Promise&&(e=await e),i(e),r=sG(e,s)}let n=2048*e/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 tG(r,"key",n,o,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){i(this.demuxer.audioInfo);let r=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/2048,(this.demuxer.dataSize-1)/(2048*this.demuxer.audioInfo.blockSizeInBytes)));if(r<0)return null;let a=await this.getPacketAtIndex(r,t);if(a)return a;if(0===r)return null;i(null===this.demuxer.reader.fileSize);let s=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;s;){let e=await this.getNextPacket(s,t);if(!e)break;s=e}return s}getNextPacket(e,t){i(this.demuxer.audioInfo);let r=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/2048);return this.getPacketAtIndex(r+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let r5=e=>{let t=e.filePos,r=new e_(sG(e,9));if(4095!==r.readBits(12)||(r.skipBits(1),0!==r.readBits(2)))return null;let i=r.readBits(1),a=r.readBits(2)+1,s=r.readBits(4);if(15===s)return null;r.skipBits(1);let n=r.readBits(3);if(0===n)throw Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);let o=r.readBits(13);r.skipBits(11);let l=r.readBits(2)+1;if(1!==l)throw Error("ADTS frames with more than one AAC frame are not supported.");let c=null;return 1===i?e.filePos-=2:c=r.readBits(16),{objectType:a,samplingFrequencyIndex:s,channelConfiguration:n,frameLength:o,numberOfAacFrames:l,crcCheck:c,startPos:t}};class r7 extends tK{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new S,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();i(this.firstFrameHeader),this.trackBackings=[new r9(this)]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,ns);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=nc(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=r5(e);if(!t||null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let r=eB[t.samplingFrequencyIndex];i(void 0!==r);let a={timestamp:this.nextTimestampInSamples/r,duration:1024/r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=1024,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){let e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,ns);if(t instanceof Promise&&(t=await t),!t)break;let r=nc(t);if(!r)break;let i=this.reader.requestSlice(t.filePos,r.size);
1if(i instanceof Promise&&(i=await i),!i)break;nu(i,r,this.metadataTags),e=t.filePos+r.size}return this.metadataTags}finally{e()}}}class r9{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/1024}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return"und"}getCodec(){return"aac"}getInternalCodecId(){return i(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){i(this.demuxer.firstFrameHeader);let e=eA[this.demuxer.firstFrameHeader.channelConfiguration];return i(void 0!==e),e}getSampleRate(){i(this.demuxer.firstFrameHeader);let e=eB[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return i(void 0!==e),e}getDisposition(){return{...eI}}async getDecoderConfig(){return i(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){let r;if(-1===e)return null;let i=this.demuxer.loadedSamples[e];if(!i)return null;if(t.metadataOnly)r=tX;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;r=sG(e,i.dataSize)}return new tG(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let r=I(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===r)throw Error("Packet was not created from this track.");let i=r+1;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{r()}}async getPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{for(;;){let r=E(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===r&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||r>=0&&r+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(r,t);await this.demuxer.advanceReader()}}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let ie=e=>{if(0===e)return null;if(1===e)return 192;if(e>=2&&e<=5)return 144*2**e;if(6===e)return"uncommon-u8";if(7===e)return"uncommon-u16";else if(e>=8&&e<=15)return 2**e;else return null},it=(e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}},ir=e=>{let t=0,r=new e_(sG(e,1));for(;1===r.readBits(1);)t++;if(0===t)return r.readBits(7);let i=[],a=t-1,s=new e_(sG(e,a)),n=8-t-1;for(let e=0;e<n;e++)i.unshift(r.readBits(1));for(let e=0;e<a;e++)for(let e=0;e<8;e++){let t=s.readBits(1);e<2||i.unshift(t)}return i.reduce((e,t,r)=>e|t<<r,0)},ii=(e,t)=>"uncommon-u16"===t?sJ(e)+1:"uncommon-u8"===t?sQ(e)+1:"number"==typeof t?t:void(D(t),i(!1)),ia=(e,t)=>"uncommon-u16"===t?sJ(e):"uncommon-u16-10"===t?10*sJ(e):"uncommon-u8"===t?sQ(e):"number"==typeof t?t:null,is=e=>{let t=0;for(let r of e){t^=r;for(let e=0;e<8;e++)(128&t)!=0?t=t<<1^7:t<<=1,t&=255}return t};class io extends tK{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 S,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),i(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??=(async()=>{let e=0;for(;;){let t=this.reader.requestSlice(e,ns);if(t instanceof Promise&&(t=await t),!t){this.lastSampleLoaded=!0;return}let r=nc(t);
1if(!r)break;let a=this.reader.requestSlice(t.filePos,r.size);a instanceof Promise&&(a=await a),i(a),nu(a,r,this.metadataTags),e=t.filePos+r.size}for(e+=4;null===this.reader.fileSize||e<this.reader.fileSize;){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),e+=4,null===t)throw Error(`Metadata block at position ${e} is too small! Corrupted file.`);i(t);let r=sQ(t),a=sZ(t),s=(128&r)!=0;switch(127&r){case i8.STREAMINFO:{let t=this.reader.requestSlice(e,a);if(t instanceof Promise&&(t=await t),i(t),null===t)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let r=sG(t,34),s=new e_(r),n=s.readBits(16),o=s.readBits(16),l=s.readBits(24),c=s.readBits(24),u=s.readBits(20),d=s.readBits(3)+1;s.readBits(5);let h=s.readBits(36);s.skipBits(128);let f=new Uint8Array(42);f.set(new Uint8Array([102,76,97,67]),0),f.set(new Uint8Array([128,0,0,34]),4),f.set(r,8),this.audioInfo={numberOfChannels:d,sampleRate:u,totalSamples:h,minimumBlockSize:n,maximumBlockSize:o,minimumFrameSize:l,maximumFrameSize:c,description:f},this.trackBacking=new il(this);break}case i8.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,a);t instanceof Promise&&(t=await t),i(t),tz(sG(t,a),this.metadataTags);break}case i8.PICTURE:{let t=this.reader.requestSlice(e,a);t instanceof Promise&&(t=await t),i(t);let r=s2(t),s=s2(t),n=d.decode(sG(t,s)),o=s2(t),l=d.decode(sG(t,o));t.skip(16);let c=s2(t),u=sG(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:u,mimeType:n,kind:3===r?"coverFront":4===r?"coverBack":"unknown",description:l})}}if(e+=a,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){i(this.audioInfo);let r=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,a=this.audioInfo.minimumFrameSize||10,s=this.audioInfo.maximumFrameSize||r,n=await this.reader.requestSliceRange(e,16,s+16);if(!n)return null;let o=this.readFlacFrameHeader({slice:n,isFirstPacket:t});if(!o)return null;for(n.filePos=e+a;;){if(n.filePos>n.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n.end-e,isLastFrame:!0};if(255===sQ(n)){let t=n.filePos;if(sQ(n)!==(1===this.blockingBit?249:248)){n.filePos=t;continue}n.skip(-2);let r=n.filePos-e,i=this.readFlacFrameHeader({slice:n,isFirstPacket:!1});if(!i){n.filePos=t;continue}if(0===this.blockingBit){if(i.num-o.num!=1){n.filePos=t;continue}}else if(i.num-o.num!==o.blockSize){n.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:r,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let r=e.filePos,a=new e_(sG(e,4));if(32764!==a.readBits(15))return null;if(null===this.blockingBit){i(t);let e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){if(i(!t),1!==a.readBits(1))return null}else if(0===this.blockingBit){if(i(!t),0!==a.readBits(1))return null}else throw Error("Invalid blocking bit");let s=ie(a.readBits(4));if(!s)return null;i(this.audioInfo);let n=it(a.readBits(4),this.audioInfo.sampleRate);if(!n||(a.readBits(4),a.readBits(3),0!==a.readBits(1)))return null;let o=ir(e),l=ii(e,s),c=ia(e,n);if(null===c||c!==this.audioInfo.sampleRate)return null;let u=e.filePos-r,d=sQ(e);return(e.skip(-u),e.skip(-1),d!==is(sG(e,u)))?null:{num:o,blockSize:l,sampleRate:c}}async advanceReader(){await this.readMetadata(),i(null!==this.lastLoadedPos),i(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t){this.lastSampleLoaded=!0;return}let r=this.loadedSamples[this.loadedSamples.length-1],a={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(a),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class il{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}
1getNumberOfChannels(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return"und"}getTimeResolution(){return i(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return(i(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples)?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...eI}}async getDecoderConfig(){return i(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(i(this.demuxer.audioInfo),e<0)return null;let r=await this.demuxer.readingMutex.acquire();try{for(;;){let r=E(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===r){await this.demuxer.advanceReader();continue}let i=this.demuxer.loadedSamples[r],a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;if(a+s<=e){if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader();continue}return this.getPacketAtIndex(r,t)}}finally{r()}}async getNextPacket(e,t){let r=await this.demuxer.readingMutex.acquire();try{let r=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&r>=this.demuxer.loadedSamples.length)return null;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{r()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let r,a=this.demuxer.loadedSamples[e];if(!a)return null;if(t.metadataOnly)r=tX;else{let e=this.demuxer.reader.requestSlice(a.byteOffset,a.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;r=sG(e,a.byteSize)}return i(this.demuxer.audioInfo),new tG(r,"key",a.blockOffset/this.demuxer.audioInfo.sampleRate,a.blockSize/this.demuxer.audioInfo.sampleRate,e,a.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}let ic=e=>{let t="video/MP2T",r=[...new Set(e.filter(Boolean))];return r.length>0&&(t+=`; codecs="${r.join(", ")}"`),t},iu="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.",id=new Set;class ih extends tK{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}async readMetadata(){return this.metadataPromise??=(async()=>{let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=await e),i(e);let t=sG(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=188;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else if(71===t[4]&&71===t[196])this.packetOffset=4,this.packetStride=192;else throw Error("Unreachable.");this.minReferencePointByteDistance=256*this.packetStride;let r=this.packetOffset,a=null,s=!1,n=!1;for(;;){let e=await this.readPacketHeader(r);if(!e)break;if(0===e.payloadUnitStartIndicator||n&&!this.elementaryStreams.some(t=>t.pid===e.pid)){r+=this.packetStride;continue}let t=await this.readSection(r,!0,!n);if(!t)break;let o=!1;if(!n&&0!==t.pid&&(0!==t.payload[0]||0!==t.payload[1]||1!==t.payload[2])){let e=new e_(t.payload),r=e.readAlignedByte();e.skipBits(8*r),o=2===e.readBits(8)}if(0!==t.pid||s)if((t.pid===a||o)&&!n){let e=new e_(t.payload),r=e.readAlignedByte();e.skipBits(8*r),e.skipBits(12);let i=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let a=e.readBits(10);for(e.skipBits(8*a);8*(i+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let r=e.readBits(13);e.skipBits(6);let i=e.readBits(10),a=e.pos+8*i,s=!1,n=!1;for(;e.pos<a;){let t=e.readBits(8),r=e.readBits(8);106===t?s=!0:(122===t||204===t)&&(n=!0),e.skipBits(8*r)}let o=null;switch(t){case 27:case 36:o={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let e;if(3===t||4===t)e="mp3";else if(15===t)e="aac";else if(129===t)e="ac3";else if(135===t)e="eac3";else throw Error("Unreachable.");o={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:n?o={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:s&&(o={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:id.has(t)||(eP._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),id.add(t))}o&&this.elementaryStreams.push({demuxer:this,pid:r,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:o,referencePesPackets:[]})}n=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);t:if(e&&!e.initialized){let r=ip(t,!0);if(!r)throw Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){let r=(await this.input._initInput._getDemuxer()).elementaryStreams.find(r=>r.pid===t.pid&&r.info.codec===e.info.codec);if(r){e.info=r.info,e.initialized=!0;break t}}let a=new iT(e,r);if("video"===e.info.type){for(;;){if(a.suppliedPacket=null,await a.markNextPacket(),"avc"===e.info.codec){if
1(!a.suppliedPacket)throw Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=tf(a.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];i(t);let r=tg(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight;let s=r.pixelAspectRatio.num,n=r.pixelAspectRatio.den;s>0&&n>0&&(s>n?(e.info.squarePixelWidth=Math.round(e.info.width*s/n),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*n/s))),e.info.colorSpace={primaries:p[r.colourPrimaries],transfer:k[r.transferCharacteristics],matrix:y[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!a.suppliedPacket)throw Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=tw(a.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===i3.SPS_NUT).nalUnits[0];i(t);let r=tT(t);e.info.width=r.displayWidth,e.info.height=r.displayHeight,r.pixelAspectRatio.num>r.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*r.pixelAspectRatio.num/r.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*r.pixelAspectRatio.den/r.pixelAspectRatio.num)),e.info.colorSpace={primaries:p[r.colourPrimaries],transfer:k[r.transferCharacteristics],matrix:y[r.matrixCoefficients],fullRange:!!r.fullRangeFlag},e.info.reorderSize=r.maxDecFrameBuffering;break}throw Error("Unhandled.")}e.info.decoderConfig={codec:ej({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},(e.info.width!==e.info.squarePixelWidth||e.info.height!==e.info.squarePixelHeight)&&(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await a.markNextPacket(),!a.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){let t=r5(sK.tempFromBytes(a.suppliedPacket.data));if(!t)throw Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");e.info.aacCodecInfo={isMpeg2:!1,objectType:t.objectType},e.info.numberOfChannels=eA[t.channelConfiguration],e.info.sampleRate=eB[t.samplingFrequencyIndex]}else if("mp3"===e.info.codec){let t=tr(s2(sK.tempFromBytes(a.suppliedPacket.data)),a.suppliedPacket.data.byteLength);if(!t.header)throw Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=ta(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if("ac3"===e.info.codec){let t=tL(a.suppliedPacket.data);if(!t)throw Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(3===t.fscod)throw Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=tU[t.acmod]+t.lfeon,e.info.sampleRate=ts[t.fscod]}else if("eac3"===e.info.codec){let t=tV(a.suppliedPacket.data);if(!t)throw Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let r=tj(t);if(null===r)throw Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=t$(t),e.info.sampleRate=r}else throw Error("Unhandled.");e.info.decoderConfig={codec:eK({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{let e=new e_(t.payload),r=e.readAlignedByte();e.skipBits(8*r),e.skipBits(14);let i=e.readBits(10);for(e.skipBits(40);8*(i+3)-e.pos>32;){let t=e.readBits(16);e.skipBits(3);let r=e.readBits(13);if(0!==t)if(null!==a)throw Error("Only files with a single program are supported.");else a=r}if(null===a)throw Error("Program Association Table must link to a Program Map Table.");s=!0}if(n&&this.elementaryStreams.every(e=>e.initialized))break;r+=this.packetStride}if(!n){if(!s)throw Error("No Program Association Table found in the file.");throw Error("No Program Map Table found in the file.")}for(let e of this.elementaryStreams)e.initialized&&("video"===e.info.type?this.trackBackingEntries.push(new ik(e)):this.trackBackingEntries.push(new ib(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),ic(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,r=!1){let i,a=e,s=e,n=[],o=0,l=null,c=!0,u=0;for(;;){let e=await this.readPacket(s);if(s+=this.packetStride,!e)break;if(l){if(e.pid!==l.pid)if(!r)continue;else break;if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;l=e}let i=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl),h=0;if(i&&(h=1+e.body[0],e===l&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(n.push(e.body),o+=e.body.byteLength):(n.push(e.body.subarray(h)),o+=e.body.byteLength-h)),a=s,
1!t&&o>=64||-1!==I(this.sectionEndPositions,a,e=>e)){c=!1;break}}if(c){let e=E(this.sectionEndPositions,a,e=>e);this.sectionEndPositions.splice(e+1,0,a)}if(!l)return null;if(1===n.length)i=n[0];else{i=new Uint8Array(n.reduce((e,t)=>e+t.length,0));let e=0;for(let t of n)i.set(t,e),e+=t.length}return{startPos:e,endPos:t?a:null,pid:l.pid,payload:i,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(71!==sQ(t))throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let r=sJ(t);return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:sQ(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let r=sG(t,188);if(71!==r[0])throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let i=(r[1]<<8)+r[2];return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:r[3]>>4&3,body:r.subarray(4)}}}let im=(e,t)=>{if(e.payload.byteLength<3)return null;let r=new e_(e.payload);if(1!==r.readBits(24))return null;let i=r.readBits(8);if(r.skipBits(16),188===i||190===i||191===i||240===i||241===i||255===i||242===i||248===i)return null;r.skipBits(8);let a=r.readBits(2);r.skipBits(14);let s=null;if(2===a||3===a)s=0,r.skipBits(4),s+=0x40000000*r.readBits(3),r.skipBits(1),s+=32768*r.readBits(15),r.skipBits(1),s+=r.readBits(15);else if(t)throw Error(iu);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},ip=(e,t)=>{i(null!==e.endPos);let r=im(e,t);if(!r)return null;let a=new e_(e.payload);a.skipBits(32);let s=a.readBits(16);a.skipBits(16);let n=a.readBits(8),o=a.pos+8*n;a.pos=o;let l=o/8;i(Number.isInteger(l));let c=e.payload.subarray(l,s>0?6+s:e.payload.byteLength);return{...r,data:c}};class ig{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){let e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type,r=0;for(let a of e.trackBackingEntries)if(a.getType()===t&&r++,i(a instanceof ig),a.elementaryStream===this.elementaryStream)break;return r}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...eI,primary:!1}}getTimeResolution(){return 9e4}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}
1async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,r){let i;return i=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new tG(r.metadataOnly?tX:e.data,i,e.pts/9e4,Math.max(t/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;i(t);let r=ip(t,!0);i(r);let a=new iw(this,new iT(this.elementaryStream,r)),s=await a.readNext();if(!s)return null;let n=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(n,a),this.packetSectionStarts.set(n,s.packet.sectionStartPos),n}async getNextPacket(e,t){let r=this.packetBuffers.get(e);if(r){let i=await r.readNext();if(!i)return null;this.packetBuffers.delete(e);let a=this.createEncodedPacket(i.packet,i.duration,t);return this.packetBuffers.set(a,r),this.packetSectionStarts.set(a,i.packet.sectionStartPos),a}let a=this.packetSectionStarts.get(e);if(void 0===a)throw Error("Packet was not created from this track.");let s=this.elementaryStream.demuxer,n=await s.readSection(a,!0);i(n);let o=ip(n,!0);i(o),r=new iw(this,new iT(this.elementaryStream,o));let l=e.sequenceNumber;for(;;){let e=await r.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){let i=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(i,r),this.packetSectionStarts.set(i,e.packet.sectionStartPos),i}}}async getNextKeyPacket(e,t){let r=e;for(;;){if(!(r=await this.getNextPacket(r,t)))return null;if("key"===r.type)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){let a,n=V(9e4*e),o=this.elementaryStream.demuxer,{reader:l,seekChunkSize:c}=o,u=this.elementaryStream.pid,d=async(e,t,r)=>{let i=e;for(;i<t;){let e=await o.readPacketHeader(i);if(!e)break;if(e.pid===u&&1===e.payloadUnitStartIndicator){let e=await o.readSection(i,r);if(!e)return null;let t=im(e,!1);if(t&&null!==t.pts)return{pesPacketHeader:t,section:e}}i+=o.packetStride}return null},h=this.elementaryStream.firstSection;i(h);let f=im(h,!0);if(i(f),n<f.pts)return null;let m=this.elementaryStream.referencePesPackets,p=E(m,n,e=>e.pts),g=-1!==p?m[p]:null;if(g&&n-g.pts<45e3)a=g.sectionStartPos;else{let e=0;if(null!==l.fileSize){let t=Math.ceil(l.fileSize/c);if(t>1){let r=0,i=t-1;for(e=0;r<=i;){let t=Math.floor((r+i)/2),a=$(t*c,o.packetStride)+f.sectionStartPos,s=a+c,l=await d(a,s,!1);if(!l){i=t-1;continue}l.pesPacketHeader.pts<=n?(e=t,r=t+1):i=t-1}}}a=$(e*c,o.packetStride)+f.sectionStartPos}let k=await d(a,l.fileSize??1/0,!1),b=k?.pesPacketHeader??null;b||(b=f);let y=this.getReorderSize(),T=async(e,t)=>{let a=await o.readSection(e,!0);i(a);let l=ip(a,!0);i(l);let c=new iw(this,new iT(this.elementaryStream,l));for(;!((s(c.presentationOrderPackets)?.pts??-1/0)>=n)&&await c.readNextPacket(););let u=F(c.presentationOrderPackets,t);if(-1===u)return null;let d=c.presentationOrderPackets[u],h=0===u?0:d.pts-c.presentationOrderPackets[u-1].pts;for(;c.decodeOrderPackets[0]!==d;)c.decodeOrderPackets.shift();c.lastDuration=h;let f=await c.readNext();i(f);let m=this.createEncodedPacket(f.packet,f.duration,r);return this.packetBuffers.set(m,c),this.packetSectionStarts.set(m,f.packet.sectionStartPos),m};if(!t||this.allPacketsAreKeyPackets()){t:for(;;){let e=b.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break t;if(t.pid===u&&1===t.payloadUnitStartIndicator){let t=await o.readSection(e,!1);if(t){let e=im(t,!1);if(e&&null!==e.pts){if(e.pts>n)break t;b=e,iy(this.elementaryStream,b);break}}}e+=o.packetStride}}t:for(let e=0;e<y+1;e++){let e=b.sectionStartPos-o.packetStride;for(;e>=o.packetOffset;){let t=await o.readPacketHeader(e);if(!t)break t;if(t.pid===u&&1===t.payloadUnitStartIndicator){let t=await o.readSection(e,!1);if(t){let e=im(t,!1);if(e&&null!==e.pts){b=e;break}}}e-=o.packetStride}}return T(b.sectionStartPos,e=>e.pts<=n)}{let e=a,t=null,r=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let a,s=null,m=e<=f.sectionStartPos,p=null;if(m)a=f,p=h;else{let t=await d(e,l.fileSize??1/0,r);a=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;t:for(;a&&(null===t||!(a.sectionStartPos>=t));){if(a.pts<=n){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===a.randomAccessIndicator;else{i(p);let t=ip(p,!0);i(t);let r=new iT(this.elementaryStream,t);await r.markNextPacket(),e=r.suppliedPacket?.randomAccessIndicator===1}e&&(s=a)}if(a.pts>n&&(g=!0),g&&++k>y)break;let e=a.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break t;if(t.pid===u&&1===t.payloadUnitStartIndicator){let t=await o.readSection(e,r);if(t){let e=im(t,!1);if(e&&null!==e.pts){a=e,p=t,iy(this.elementaryStream,a);break}}}e+=o.packetStride}}if(s){let e=s;if(0===k)t:for(let t=0;t<y;t++){let t=e.sectionStartPos-o.packetStride;for(;t>=o.packetOffset;){let i=await o.readPacketHeader(t);if(!i)break t;if(i.pid===u&&1===i.payloadUnitStartIndicator){let i=await o.readSection(t,r);if(i){let t=im(i,!1);if(t&&null!==t.pts){e=t;break}}}t-=o.packetStride}}let t=await T(e.sectionStartPos,e=>e.pts<=n&&1===e.randomAccessIndicator);return i(t),t}if(m)return null;t=e,e=Math.max($(e-f.sectionStartPos-c,o.packetStride)+f.sectionStartPos,f.sectionStartPos)}}}}class ik extends ig{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}
1async canBeTransparent(){return!1}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class ib extends ig{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return i(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}let iy=(e,t)=>{let r=e.referencePesPackets,i=E(r,t.sectionStartPos,e=>e.sectionStartPos);if(i>=0){let a=r[i];if(t.pts<=a.pts)return!1;let s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos<s)return!1;if(i<r.length-1){let e=r[i+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<s)return!1}}return r.splice(i+1,0,t),!0};class iT{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){let t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){let e=this.pesPackets[this.currentPesPacketIndex];return i(e),e}async bufferData(e){let t=this.endPos+e;for(;this.endPos<t;){let e;if(0===this.pesPackets.length)e=this.startingPesPacket;else{let t=s(this.pesPackets).sectionEndPos;for(i(null!==t);;){let r=await this.demuxer.readPacketHeader(t);if(!r)return;if(r.pid===this.pid){let r=await this.demuxer.readSection(t,!0);if(!r)return;let i=ip(r,!1);if(i){e=i;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),r=this.currentPos-this.currentPesPacketPos,i=r+e;if(this.currentPos+=e,i<=t.data.byteLength)return t.data.subarray(r,i);let a=new Uint8Array(e);a.set(t.data.subarray(r));let s=t.data.byteLength-r;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),r=e-s;if(r<=t.data.byteLength){a.set(t.data.subarray(0,r),s);break}a.set(t.data,s),s+=t.data.byteLength}return a}readU8(){let e=this.getCurrentPesPacket(),t=this.currentPos-this.currentPesPacketPos;return(this.currentPos++,t<e.data.byteLength)?e.data[t]:(this.advanceCurrentPacket(),(e=this.getCurrentPesPacket()).data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;let e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){let t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){i(!this.suppliedPacket);let e=this.elementaryStream;if("video"===e.info.type){let t=e.info.codec;if("avc"!==t&&"hevc"!==t)throw Error("Unhandled.");let r="avc"===t?1:2,i=null,a=!1,s=0;for(;;){let e=this.ensureBuffered(1024);if(e instanceof Promise&&(e=await e),0===e)break;let n=this.currentPos,l=this.readBytes(e),c=l.byteLength,u=0;for(;u<c;){let e,d,h,f=l.indexOf(0,u);if(-1===f||f>=c)break;let m=n+(u=f);if(u+3>=c){this.seekTo(m);break}let p=l[u+1],g=l[u+2],k=l[u+3],b=0;if(0===p&&0===g&&1===k?b=4:0===p&&1===g&&(b=3),0===b){u++;continue}i??=m;let y=u+b,T=y+r;if(T+("avc"===t?6:1)>c){this.seekTo(m);break}let w=l[y];if("avc"===t)d=(e=tu(w))===i2.NON_IDR_SLICE||e===i2.SLICE_DPA||e===i2.IDR,h=e===i2.SEI||e===i2.SPS||e===i2.PPS||e===i2.AUD;else{if(e=ty(w),((1&w)<<5|l[y+1]>>3)>0){u+=b;continue}d=e<=i3.RASL_R||e>=i3.BLA_W_LP&&e<=21,h=e>=i3.VPS_NUT&&e<=37||e===i3.PREFIX_SEI_NUT||e>=41&&e<=44||e>=48&&e<=55}let S=!1;if(d){let e;if("avc"===t){let t=o(new e_(l.subarray(T,T+6)));e=!a||t<=s,s=t}else e=l[T]>>7==1;e&&(a?S=!0:a=!0)}else h&&a&&(S=!0);if(S){let e=m-i;return this.seekTo(i),this.supplyPacket(e,0)}u+=b}if(e<1024)break}if(null!==i&&this.endPos>i){let e=this.endPos-i;return this.seekTo(i),this.supplyPacket(e,0)}}else{let t=e.info.codec;for(;;){let r=this.ensureBuffered(128);r instanceof Promise&&(r=await r);let a=this.currentPos;for(;this.currentPos-a<r;){let r=this.readU8();if("aac"===t){if(255!==r)continue;this.skip(-1);let t=this.currentPos,i=this.ensureBuffered(9);if(i instanceof Promise&&(i=await i),i<9)return;let a=this.readBytes(9),s=r5(sK.tempFromBytes(a));if(s){this.seekTo(t);let r=this.ensureBuffered(s.frameLength);return r instanceof Promise&&(r=await r),this.supplyPacket(r,Math.round(9216e4/e.info.sampleRate))}this.seekTo(t+1)}else if("mp3"===t){if(255!==r)continue;this.skip(-1);let t=this.currentPos,i=this.ensureBuffered(4);if(i instanceof Promise&&(i=await i),i<4)return;let a=tr(u(this.readBytes(4)).getUint32(0),null);if(a.header){this.seekTo(t);let r=this.ensureBuffered(a.header.totalSize);r instanceof Promise&&(r=await r);let i=9e4*a.header.audioSamplesInFrame/e.info.sampleRate;return this.supplyPacket(r,Math.round(i))}this.seekTo(t+1)}else if("ac3"===t){if(11!==r)continue;this.skip(-1);let t=this.currentPos,a=this.ensureBuffered(5);if(a instanceof Promise&&(a=await a),a<5)return;let s=this.readBytes(5);if(11!==s[0]||119!==s[1]){this.seekTo(t+1);continue}let n=s[4]>>6,o=63&s[4];if(3===n||o>37){this.seekTo(t+1);continue}let l=tW[3*o+n];i(void 0!==l),this.seekTo(t),(a=this.ensureBuffered(l))instanceof Promise&&(a=await a);let c=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(a,c)}else if("eac3"===t){if(11!==r)continue;this.skip(-1);let t=this.currentPos,i=this.ensureBuffered(5);if(i instanceof Promise&&(i=await i),i<5)return;let a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}let s=(((7&a[2])<<8|a[3])+1)*2,n=tq[3==a[4]>>6?3:a[4]>>4&3];this.seekTo(t),(i=this.ensureBuffered(s))instanceof Promise&&(i=await i);let o=Math.round(256*n*9e4/e.info.sampleRate);return this.supplyPacket(i,o)}else throw Error("Unhandled.")}if(r<128)break}}}supplyPacket(e,t){let r,a=this.getCurrentPesPacket();if(this.lastSuppliedPesPacket===a)i(null!==this.nextPts),r=this.nextPts;else{if(null===a.pts)throw Error(iu);r=a.pts,iy(this.elementaryStream,a)}this.lastSuppliedPesPacket=a,this.nextPts=r+t;let s=a.sectionStartPos,n=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),l=a.randomAccessIndicator;0===l&&!this.elementaryStream.canBeTrustedWithKeyPackets&&("audio"===this.elementaryStream.info.type?l=1:this.elementaryStream.info.decoderConfig&&(l=Number("key"===tN(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)))),this.suppliedPacket={pts:r,data:o,sequenceNumber:n,sectionStartPos:s,randomAccessIndicator:l},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class iw{constructor(e,t){this.decodeOrderPackets=[],this.reorderBuffer=[],this.presentationOrderPackets=[],this.reachedEnd=!1,this.lastDuration=0,this.backing=e,this.context=t,this.reorderSize=e.getReorderSize(),i(this.reorderSize>=0)}
1async readNext(){let e;if(0===this.decodeOrderPackets.length&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let t=this.decodeOrderPackets[0],r=this.presentationOrderPackets.indexOf(t);for(i(-1!==r),r===this.presentationOrderPackets.length-1?e=this.lastDuration:(e=this.presentationOrderPackets[r+1].pts-t.pts,this.lastDuration=e),this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){let e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:t,duration:e}}async readNextPacket(){let e;return!this.reachedEnd&&((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(){let e=this.decodeOrderPackets[0];for(i(e);;){let t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2||!await this.readNextPacket())break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let t=1;t<this.reorderBuffer.length;t++)this.reorderBuffer[t].pts<this.reorderBuffer[e].pts&&(e=t);let t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}let iS="application/vnd.apple.mpegurl",iP="#EXT-X-STREAM-INF:",iv="#EXT-X-I-FRAME-STREAM-INF:",ix="#EXT-X-MEDIA:",iC="#EXTINF:",iI="#EXT-X-MAP:",iE="#EXT-X-KEY:",i_="#EXT-X-MEDIA-SEQUENCE:",iB="#EXT-X-BYTERANGE:",iA="#EXT-X-PROGRAM-DATE-TIME:",iF="#EXT-X-TARGETDURATION:",iM="#EXT-X-PLAYLIST-TYPE:",iR=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class iD{constructor(e){this._attributes={};let t="",r="",i=!1,a=!1;for(let s=0;s<e.length;s++){let n=e[s];'"'===n?a=!a:"="!==n||i||a?","!==n||a?i?r+=n:t+=n:(t&&(this._attributes[t.trim().toLowerCase()]=r),t="",r="",i=!1):i=!0}t&&(this._attributes[t.trim().toLowerCase()]=r)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(null===t)return null;let r=Number(t);return Number.isFinite(r)?r:null}merge(e){Object.assign(this._attributes,e._attributes)}}class iO{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}
1async getDurationFromMetadata(e){let t=await this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null}async getUnixTimeForTimestamp(e){let t=await this.getSegmentAt(e,{});if(!(t??=await this.getFirstSegment({}))||null===t.unixEpochTimestamp)return null;let r=e-t.timestamp;return t.unixEpochTimestamp+r}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if("video"===t.type){let r=ep(e,e=>"video"===e.getType())+1;e.push(new iz(this,t,r))}else if("audio"===t.type){let r=ep(e,e=>"audio"===e.getType())+1;e.push(new iU(this,t,r))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let t=this.getInputForSegment(this.firstSegment);for(let r of(await t.getTracks()))if("video"===r.type){let t=ep(e,e=>"video"===e.getType())+1;e.push(new iz(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){let t=ep(e,e=>"audio"===e.getType())+1;e.push(new iU(this,{id:e.length+1,type:"audio"},t))}}return e})()}async getFirstTimestampForInput(e){let t=this.firstTimestampCache.get(e);if(void 0!==t)return t;let r=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,r),r}async getMediaOffset(e,t){let r,i=e.firstSegment??e;if(this.firstSegmentFirstTimestamps.has(i))r=this.firstSegmentFirstTimestamps.get(i);else{let e=this.getInputForSegment(i);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(i,r)}if(i===e)return i.timestamp-r;let a=await this.getFirstTimestampForInput(t),s=e.timestamp-i.timestamp;return Math.abs(a-r-s)<=Math.min(.25,s)?i.timestamp-r:e.timestamp-a}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class iN{constructor(e,t,r){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=r}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error("Missing first segment, can't retrieve track.");let e=this.segmentedInput.firstSegment,t=null;for(;e;){let r=this.segmentedInput.getInputForSegment(e);if(t=(await r.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null)break;e=await this.segmentedInput.getNextSegment(e,{})}if(!t)throw Error("No matching track found in underlying media data.");this.firstInputTrack=t,this.firstSegment=e})()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),i(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}
1getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,r){i(e.sequenceNumber>=0),i(this.segmentedInput.firstSegment);let a=await this.segmentedInput.getMediaOffset(t,r.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,n=e.clone({timestamp:j(e.timestamp+a,await r.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(n,{segment:t,track:r,sourcePacket:e}),n}async getFirstPacket(e){await this.hydrate(),i(this.firstInputTrack),i(this.firstSegment);let t=this.firstInputTrack,r=this.firstSegment;for(;;){if(t){let i=await t._backing.getFirstPacket(e);if(i)return this.createAdjustedPacket(i,r,t)}if(!(r=await this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait})))break;let i=this.segmentedInput.getInputForSegment(r);t=(await i.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,r){let i=this.packetInfos.get(e);if(!i)throw Error("Packet was not created from this track.");let a=r?await i.track._backing.getNextKeyPacket(i.sourcePacket,t):await i.track._backing.getNextPacket(i.sourcePacket,t);if(a)return this.createAdjustedPacket(a,i.segment,i.track);let s=i.segment;for(;;){let e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;let r=this.segmentedInput.getInputForSegment(e),a=(await r.getTracks()).find(e=>e.type===i.track.type&&e.number===i.track.number);if(!a){s=e;continue}let n=await a._backing.getFirstPacket(t);if(!n)return null;return this.createAdjustedPacket(n,e,a)}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,r){let i=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!i)return null;for(await this.hydrate();i;){let a=this.segmentedInput.getInputForSegment(i),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}let n=e-await this.segmentedInput.getMediaOffset(i,a),o=r?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(!o){i=await this.segmentedInput.getPreviousSegment(i,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(o,i,s)}return null}}class iz extends iN{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}
1async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class iU extends iN{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())}}r(47251),eh();let iL=1/0;"undefined"!=typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class iW extends ew{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!=typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new sj;return this._sizePromise??=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,iL),i(void 0!==(e=this._getFileSize()))),e})()}async getSize(){if(this._disposed)throw new sj;
1let e=await this.getSizeOrNull();if(null===e)throw Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw TypeError("length, when provided, must be a non-negative integer.");return new iQ(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new iq(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class iq{constructor(e){if(this._freed=!1,e._disposed)throw Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw Error("Illegal operation: double free on SourceRef.");let e=this.source;i(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class iV extends iW{constructor(e,t){if("string"!=typeof e)throw TypeError("rootPath must be a string.");if("function"!=typeof t)throw TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){let t=this.requestHandler(e),r=e=>{if(!(e instanceof iW||e instanceof iq))throw TypeError("requestHandler must return or resolve to a Source or SourceRef.");let t=e instanceof iW?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(r):r(t)}}let iH=(e,t)=>e.path===t.path;class ij extends iV{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,r,a){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{let t=e instanceof iW?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),i(this._root))}if(this._rootRequest)return this._rootRequest.then(i=>i.source._read(e,t,r,a))}return this._root.source._read(e,t,r,a)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class i$ extends iW{constructor(e,t={}){if(!(e instanceof Blob))throw TypeError("blob must be a Blob.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ef(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!=typeof t.useStreamReader)throw TypeError("options.useStreamReader, when provided, must be a boolean.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new iG({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:iX.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,r,i){return this._orchestrator.read(e,t,r,i)}async _runWorker(e){i(e.strictTarget);let t=this._readers.get(e);for(void 0===t&&(t=("stream"in this._blob)&&!ee()&&!1!==this._options.useStreamReader?this._blob.slice(e.currentPos).stream().getReader():null,this._readers.set(e,t));e.currentPos<e.targetPos&&!e.aborted;)if(t){let{done:r,value:i}=await t.read();if(r)throw this._orchestrator.onWorkerFinished(e),Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+i.length),this._orchestrator.supplyWorkerData(e,i)}else{let t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await t?.cancel()}_dispose(){this._orchestrator.dispose()}}class iK extends iW{constructor(e,t={}){if(!(e instanceof ReadableStream))throw TypeError("stream must be a ReadableStream.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ef(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.",this._stream=e,this._maxCacheSize=t.maxCacheSize??0x2000000}_getFileSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);let r=E(this._cache,e,e=>e.start),i=-1!==r?this._cache[r]:null;if(i&&i.start<=e&&t<=i.end)return{bytes:i.bytes,view:i.view,offset:i.start};let a=e,s=new Uint8Array(t-e);if(-1!==r)for(let i=r;i<this._cache.length;i++){let r=this._cache[i];if(r.start>=t)break;let n=Math.max(e,r.start);n>a&&this._throwDueToCacheMiss();let o=Math.min(t,r.end);n<o&&(s.set(r.bytes.subarray(n-r.start,o-r.start),n-e),a=o)}if(a===t)return{bytes:s,view:u(s),offset:e};this._currentIndex>a&&this._throwDueToCacheMiss();let{promise:n,resolve:o,reject:l}=_();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>
10)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else throw e})),n}_throwDueToCacheMiss(){throw Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??=this._stream.getReader();this._currentIndex<this._targetIndex&&!this._disposed;){let{done:e,value:t}=await this._reader.read();if(e){for(let e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}let r=this._currentIndex,i=this._currentIndex+t.byteLength;this._dispatchRead(r,i);for(let e=0;e<this._pendingSlices.length;e++){let a=this._pendingSlices[e],s=Math.max(r,a.start),n=Math.min(i,a.end);s<n&&(a.bytes.set(t.subarray(s-r,n-r),s-a.start),n===a.end&&(a.resolve({bytes:a.bytes,view:u(a.bytes),offset:a.start}),this._pendingSlices.splice(e,1),e--))}for(this._cache.push({start:r,end:i,bytes:t,view:u(t),age:0});this._cache.length>0;){let e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(let e of this._pendingSlices)e.reject(new sj);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}let iX={fileSystem:(e,t)=>({start:e=65536*Math.floor((e-65536)/65536),end:t=65536*Math.ceil((t+65536)/65536)})};class iG{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,r,a){i(!this.disposed);let s=this.options.prefetchProfile(e,t,this.workers),n=Math.max(s.start,r),o=Math.min(s.end,this.fileSize??1/0,a);i(n<=e&&t<=o);let l=null,c=E(this.cache,e,e=>e.start),d=-1!==c?this.cache[c]:null;d&&d.start<=e&&t<=d.end&&(d.age=this.nextAge++,l={bytes:d.bytes,view:d.view,offset:d.start});let h=E(this.cache,n,e=>e.start),f=l?null:new Uint8Array(t-e),m=0,p=n,g=[];if(-1!==h){for(let r=h;r<this.cache.length;r++){let a=this.cache[r];if(a.start>=o)break;if(a.end<=n)continue;let s=Math.max(n,a.start),l=Math.min(o,a.end);if(i(s<=l),p<s&&g.push({start:p,end:s}),p=l,f){let r=Math.max(e,a.start),i=Math.min(t,a.end);if(r<i){let t=r-e;f.set(a.bytes.subarray(r-a.start,i-a.start),t),t===m&&(m=i-e)}}a.age=this.nextAge++}p<o&&g.push({start:p,end:o})}else g.push({start:n,end:o});if(f&&m>=f.length&&(l={bytes:f,view:u(f),offset:e}),0===g.length)return i(l),l;let{promise:k,resolve:b,reject:y}=_(),T=[];for(let r of g){let i=Math.max(e,r.start),a=Math.min(t,r.end);i===r.start&&a===r.end?T.push(r):i<a&&T.push({start:i,end:a})}let w=f&&{start:e,bytes:f,holes:T,resolve:b,reject:y};t:for(let e of g){for(let t of this.workers)if(this.checkHoleAgainstWorker(t,e,w?[w]:[])){this.checkQueuedReadsAgainstWorker(t);continue t}let t=e.end<o||null!==this.fileSize,r=this.createWorker(e.start,e.end,t);if(r)w&&(r.pendingSlices=[w]),this.runWorker(r);else{let r=E(this.queuedReads,e.start,e=>e.hole.start),i=-1!==r?this.queuedReads[r]:null;for(i&&e.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,e.end),i.strictTarget&&=t,w&&i.pendingSlices.push(w)):(r++,i={hole:{start:e.start,end:e.end},strictTarget:t,pendingSlices:w?[w]:[],age:this.nextAge++},this.queuedReads.splice(r,0,i));r+1<this.queuedReads.length;){let e=this.queuedReads[r+1];if(e.hole.start>i.hole.end)break;i.hole.end=Math.max(i.hole.end,e.hole.end),i.pendingSlices.push(...e.pendingSlices),i.strictTarget&&=e.strictTarget,i.age=Math.min(i.age,e.age),this.queuedReads.splice(r+1,1)}}}return l?k.catch(e=>{if(!this.disposed)throw e}):(i(f),l=k.then(t=>t&&{bytes:t,view:u(t),offset:e})),l}checkHoleAgainstWorker(e,t,r){if(el(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t<r.length;t++){let i=r[t];e.pendingSlices.includes(i)||e.pendingSlices.push(i)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let r=0;r<this.queuedReads.length;r++){let i=this.queuedReads[r];if(this.checkHoleAgainstWorker(e,i.hole,i.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 e=null,t=null;for(let r=0;r<this.workers.length;r++){let i=this.workers[r];i.running||0!==i.pendingSlices.length||e&&!(i.age<e.age)||(t=r,e=i)}if(!e)return null;i(null!==t),i(0===e.pendingSlices.length),this.workers.splice(t,1)}let a={startPos:e,currentPos:e,targetPos:t,strictTarget:r,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(a),a}runWorker(e){i(!e.running),i(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).
1catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed)throw t}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let t=1;t<this.queuedReads.length;t++)this.queuedReads[t].age<this.queuedReads[e].age&&(e=t);let t=this.queuedReads[e],r=this.createWorker(t.hole.start,t.hole.end,t.strictTarget);r&&(this.queuedReads.splice(e,1),r.pendingSlices=t.pendingSlices,this.runWorker(r))}})}supplyWorkerData(e,t){i(!e.aborted);let r=e.currentPos,a=r+t.length;this.insertIntoCache({start:r,end:a,bytes:t,view:u(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let i=0;i<e.pendingSlices.length;i++){let s=e.pendingSlices[i],n=Math.max(r,s.start),o=Math.min(a,s.start+s.bytes.length);n<o&&s.bytes.set(t.subarray(n-r,o-r),n-s.start);for(let e=0;e<s.holes.length;e++){let t=s.holes[e];r<=t.start&&a>t.start&&(t.start=a),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(i,1),i--)}for(let t=0;t<this.workers.length;t++){let i=this.workers[t];e!==i&&!i.running&&el(r,a,i.currentPos,i.targetPos)&&(this.workers.splice(t,1),t--)}}supplyFileSize(e){for(let t of(i(null===this.fileSize),this.fileSize=e,this.workers)){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let r=0;r<t.pendingSlices.length;r++){let i=t.pendingSlices[r];for(let a of i.holes)if(a.end>e){i.resolve(null),t.pendingSlices.splice(r,1),r--;break}}}for(let t=0;t<this.queuedReads.length;t++){let r=this.queuedReads[t];if(r.hole.start>=e){for(let e of r.pendingSlices)e.resolve(null);this.queuedReads.splice(t,1),t--}else if(r.hole.end>e){r.hole.end=e,r.strictTarget=!0;for(let t=0;t<r.pendingSlices.length;t++){let i=r.pendingSlices[t];i.start>=e&&(i.resolve(null),r.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){let t=this.workers.indexOf(e);for(let r of(i(-1!==t),e.running=!1,this.workers.splice(t,1),null===this.fileSize&&this.supplyFileSize(e.currentPos),e.pendingSlices))r.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=E(this.cache,e.start,e=>e.start)+1;if(t>0){let r=this.cache[t-1];if(r.end>=e.end)return;if(r.end>e.start){let i=new Uint8Array(e.end-r.start);i.set(r.bytes,0),i.set(e.bytes,e.start-r.start),this.currentCacheSize+=e.end-r.end,r.bytes=i,r.view=u(i),r.end=e.end,t--,e=r}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let r=t+1;r<this.cache.length;r++){let t=this.cache[r];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(r,1),this.currentCacheSize-=t.bytes.length,r--;continue}let i=new Uint8Array(t.end-e.start);i.set(e.bytes,0),i.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=i,e.view=u(i),e.end=t.end,this.cache.splice(r,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let r=1;r<this.cache.length;r++){let i=this.cache[r];i.age<t.age&&(e=r,t=i)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers){for(let t of e.pendingSlices)t.reject(new sj);e.pendingSlices.length=0,e.aborted=!0}for(let e of this.queuedReads)for(let t of e.pendingSlices)t.reject(new sj);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class iQ extends iW{constructor(e,t,r){if(super(),this._ref=null,e._disposed)throw Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=r??null}_getFileSize(){let e=this._baseSource._getFileSize();if(void 0===e)return null!==this._length?this._length:void 0;if(null===e)if(null!==this._length)return this._length;else return null;return W(e-this._offset,0,this._length??1/0)}_read(e,t,r,i){if(null!==this._length&&t>this._length)return null;let a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+r,this._offset+i),s=e=>e?(e.offset-=this._offset,e):null;return a instanceof Promise?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??=this._baseSource.ref(),super.ref()}}var iY,iJ,iZ,i0,i1,i2,i3,i4,i8,i6,i5,i7,i9,ae,at,ar,ai=function(e,t,r){if(null!=t){var i,a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");
1if(r){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],r&&(a=i)}if("function"!=typeof i)throw TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:r})}else r&&e.stack.push({async:!0});return t},aa=(iY="function"==typeof SuppressedError?SuppressedError:function(e,t,r){var i=Error(r);return i.name="SuppressedError",i.error=e,i.suppressed=t,i},function(e){function t(t){e.error=e.hasError?new iY(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var r,i=0;return function a(){for(;r=e.stack.pop();)try{if(!r.async&&1===i)return i=0,e.stack.push(r),Promise.resolve().then(a);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(s).then(a,function(e){return t(e),a()})}else i|=1}catch(e){t(e)}if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()});let as=/^0[xX][0-9a-fA-F]+$/,an=/^data:.*;base64,/i;
1class ao extends iO{constructor(e,t,r,i){super(e.input,t,r),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=i}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await ey(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})()}getRemainingWaitTimeMs(){let 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){let t={stack:[],error:void 0,hasError:!1};try{let r=ai(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),a=new s$(r.source),s=await a.requestEntireFile();i(s),e=ni(s,s.length,{ignore:iR}),r.source instanceof iV&&(this.rootPath=r.source.rootPath)}catch(e){t.error=e,t.hasError=!0}finally{aa(t)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,r=!1,a=0,n=null,o=null,l=null,c=0,d=null,h=null,f=null,m=null,p=null,g=null,k=!1,b=s(this.segments)??null,y=e=>{let t=e.indexOf("@"),r=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(r)||r<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let i=null;if(-1!==t&&(!Number.isInteger(i=Number(e.slice(t+1)))||i<0))throw Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:r,offset:i}},T=e=>{c=e,b&&(i(null!==b.sequenceNumber),b.sequenceNumber<e&&(a=b.timestamp+b.duration,d=b.firstSegment,h=b.initSegment,p=b.lastProgramDateTimeSeconds,n=null!==b.unixEpochTimestamp?b.unixEpochTimestamp+b.duration:null,b=null))};for(let i=0;i<e.length;i++){let w=e[i];if(!r){if("#EXTM3U"!==w)throw Error("Invalid M3U8 file; expected first line to be #EXTM3U.");r=!0;continue}if(!w.startsWith("#")){if(!b){if(null===o)throw Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let e=l;if(e&&"AES-128"===e.method&&!e.iv){let t=new Uint8Array(16),r=u(t);r.setUint32(8,Math.floor(c/0x100000000)),r.setUint32(12,c),e={...e,iv:t}}let t={path:em(this.rootPath,w),offset:m?.offset??0,length:m?.length??null},r={timestamp:a,unixEpochTimestamp:n,firstSegment:d,sequenceNumber:c,location:t,duration:o,encryption:e,initSegment:h,lastProgramDateTimeSeconds:p};d??=r,a+=o,null!==n&&(n+=o),this.segments.push(r)}o=null,null===m?f=null:m=null,T(c+1)}if(w.startsWith(iC)){if(b){k=!0;continue}k||(null===p&&c>0&&null!==g&&(a=c*g),k=!0);let e=w.slice(iC.length),t=e.indexOf(","),r=-1===t?e:e.slice(0,t),i=Number(r);if(!Number.isFinite(i)||i<0)throw Error(`Invalid #EXTINF tag duration '${r}'.`);o=i}else if(w.startsWith(iI)){let e=new iD(w.slice(iI.length)),t=e.get("uri");if(!t)throw Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let r=e.get("byterange"),i=null;if(null!==r&&(i=y(r)),i&&null===i.offset)throw Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!b){let e={path:em(this.rootPath,t),offset:i?.offset??0,length:i?.length??null};if(l?.method==="AES-128"&&!l.iv)throw Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");h={timestamp:a,unixEpochTimestamp:n,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:l,initSegment:null,lastProgramDateTimeSeconds:p}}o=null,null===m?f=null:m=null}else if(w.startsWith(iE)){let e=new iD(w.slice(iE.length)),t=e.get("method");if("NONE"===t)l=null;else if("AES-128"===t){let t=e.get("uri");if(!t)throw Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let r=null,i=e.get("iv");if(i){if(!as.test(i))throw Error(`Unsupported IV format '${i}'.`);let e=i.slice(2);e=e.padStart(32,"0"),r=new Uint8Array(16);for(let t=0;t<16;t++){let i=-32+t;r[t]=parseInt(e.slice(i,i+2),16)}}let a=e.get("keyformat")??"identity";if("identity"!==a)throw Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");l={method:"AES-128",keyUri:em(this.rootPath,t),iv:r,keyFormat:a}}else if("SAMPLE-AES"===t||"SAMPLE-AES-CTR"===t){let r=e.get("uri");if(!r)throw Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if("identity"===(e.get("keyformat")??"identity"))throw 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(an.test(r)){let e=r.indexOf(","),t=eu(r.slice(e+1));if(t.length>=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){let e=u(t).getUint32(0);i=tY(t.subarray(8,Math.min(e,t.length)))}}l={method:t,psshBox:i}}else throw Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`)}else if(w.startsWith(i_)){let e=w.slice(i_.length),t=Number(e);if(!Number.isInteger(t)||t<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);T(t)}else if(w.startsWith(iB)){let e=y(w.slice(iB.length));if(null===e.offset){if(null===f)throw Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=f}m=e,f=e.offset+e.length}else if(w.startsWith(iA)){if(b)continue;let e=Date.parse(w.slice(iA.length));if(!Number.isFinite(e))continue;let r=e/1e3;if(p===r)continue;if(null===p&&this.segments.length>0){let e=s(this.segments),i=r-(e.timestamp+e.duration);for(let e of this.segments)e.unixEpochTimestamp=e.timestamp+i,t&&(e.timestamp=e.unixEpochTimestamp)}p=r,n=r,t&&(a=r)}
1else if("#EXT-X-DISCONTINUITY"===w)d=null;else if(w.startsWith(iF)){let e=w.slice(iF.length),t=Number(e);if(!Number.isFinite(t)||t<0)throw Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,g=t}else if("#EXT-X-ENDLIST"===w){this.streamHasEnded=!0;break}else w.startsWith(iM)&&"vod"===w.slice(iM.length).toLowerCase()&&(this.streamHasEnded=!0)}if(!r)throw Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return 0===this.segments.length&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){0===this.segments.length&&await this.runUpdateSegments();let r=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let i=E(this.segments,e,e=>e.timestamp);if(-1===i)return null;if(i<this.segments.length-1||this.streamHasEnded||r)return this.segments[i];let a=this.segments[i];if(e<a.timestamp+a.duration)return a;await this.runUpdateSegments(),t.skipLiveWait&&(r=!0)}}async getNextSegment(e,t){let r=this.segments.indexOf(e);i(-1!==r);let a=r+1,s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(a<this.segments.length)return this.segments[a];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return i(-1!==t),this.segments[t-1]??null}getInputForSegment(e){let t=this.inputCache.find(t=>t.segment===e);if(t)return t.age=this.nextInputCacheAge++,t.input;let r=null;(e.initSegment||e.firstSegment)&&(r=this.getInputForSegment(e.initSegment??e.firstSegment));let a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(t=>{if(!e.encryption||"SAMPLE-AES"!==e.encryption.method&&"SAMPLE-AES-CTR"!==e.encryption.method||!e.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(t);let r=t.psshBoxes,{psshBox:i}=e.encryption;return(null===i.keyIds||i.keyIds.includes(t.keyId))&&!r.some(e=>tJ(e,i))&&(r=[...r,i]),this.input._formatOptions.isobmff.resolveKeyId({...t,psshBoxes:r})})}},s=new sV({source:new ij(e.location.path,async t=>{let r;i(t.isRoot);let a={...t,isRoot:!1},s=e.location.offset>0||null!==e.location.length;if(e.encryption&&"SAMPLE-AES"!==e.encryption.method&&"SAMPLE-AES-CTR"!==e.encryption.method)if("AES-128"===e.encryption.method){let t=e.encryption;i(t.iv);let n=await this.input._getSourceCached(a);if(s){let t=n.source.slice(e.location.offset,e.location.length??void 0).ref();n.free(),n=t}r=new iK(rs(new s$(n.source),async()=>{let e={stack:[],error:void 0,hasError:!1};try{let r=ai(e,await this.input._getSourceCached({path:t.keyUri,isRoot:!1},sq),!1),i=new s$(r.source),a=await i.requestSlice(0,16);if(!a)throw Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:sG(a,16),iv:t.iv}}catch(t){e.error=t,e.hasError=!0}finally{aa(e)}},()=>{n.free()})).ref()}else i(!1);else if(r=await this.input._getSourceCached(a),s){let t=r.source.slice(e.location.offset,e.location.length??void 0).ref();r.free(),r=t}return r}),formats:this.input._formats.filter(e=>!(e instanceof aI)),initInput:r??void 0,formatOptions:a});if(s._onFormatDetermined=t=>{if((e.encryption?.method==="SAMPLE-AES"||e.encryption?.method==="SAMPLE-AES-CTR")&&!t._isIsobmff)throw Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:e,input:s,age:this.nextInputCacheAge++}),this.inputCache.length>4){let e=eg(this.inputCache,e=>e.age);i(-1!==e),this.inputCache.splice(e,1)}return s}
1async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class al extends tK{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{i(this.input._rootSource instanceof iV);let e=await this.input._reader.requestEntireFile();i(e);let t=ni(e,e.length,{ignore:iR}),{rootPath:r}=this.input._rootSource,a=[],s=[];for(let e=1;e<t.length;e++){let i=t[e];if(i.startsWith(iP)){let s=e,n=t[++e];if(void 0===n)throw Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");let o=em(r,n),l=new iD(i.slice(iP.length));if(null===l.getAsNumber("bandwidth"))throw Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");a.push({fullPath:o,attributes:l,lineNumber:s,hasOnlyKeyPackets:!1})}else if(i.startsWith(iv)){let t=new iD(i.slice(iv.length)),s=t.get("uri");if(null===s)throw Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(null===t.getAsNumber("bandwidth"))throw Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");let n=em(r,s);a.push({fullPath:n,attributes:t,lineNumber:e,hasOnlyKeyPackets:!0})}else if(i.startsWith(ix)){let t=new iD(i.slice(ix.length));if(null===t.get("type"))throw Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(null===t.get("group-id"))throw Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let a=null,n=t.get("uri");null!==n&&(a=em(r,n)),s.push({fullPath:a,attributes:t,lineNumber:e})}else if("#EXT-X-I-FRAMES-ONLY"===i);else if(i.startsWith(iC)){let e=new ao(this,r,null,t);this.segmentedInputs=[e],this.hasMasterPlaylist=!1,this.trackBackings=await e.getTrackBackings();return}}let n=[...new Set(s.filter(e=>"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=[...new Set(s.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],l=await Promise.all(a.map(async(e,t)=>{let a,l=[],c=e.attributes.get("codecs");if(c)a=c.split(",").map(e=>e.trim());else{let t=this.getSegmentedInputForPath(e.fullPath),r=await t.getTrackBackings(),i=await Promise.all(r.map(async e=>({track:e,codec:await e.getCodec()})));a=await Promise.all(i.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let u=e.attributes.get("video"),d=e.attributes.get("audio"),h=a.some(e=>eR.includes(eQ(e))),f=a.some(e=>eN.includes(eQ(e)));if(null!==u&&!h){if(!n.includes(u))throw Error(`Invalid M3U8 file; variant stream references video group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);let e=s.find(e=>{let t=e.attributes.get("group-id"),r=e.attributes.get("type");return t===u&&"video"===r.toLowerCase()});t:if(e){let t=e.attributes.get("uri");if(null===t)break t;let s=em(r,t),n=this.getSegmentedInputForPath(s),o=(await n.getTrackBackings()).find(e=>"video"===e.getType());if(!o||await o.getCodec()===null)break t;let l=await o.getDecoderConfig().then(e=>e?.codec??null);i(null!==l),a.push(l)}}if(null!==d&&!f){if(!o.includes(d))throw Error(`Invalid M3U8 file; variant stream references audio group "${d}" which is not defined in any #EXT-X-MEDIA tags.`);let e=s.find(e=>{let t=e.attributes.get("group-id"),r=e.attributes.get("type");return t===d&&"audio"===r.toLowerCase()});t:if(e){let t=e.attributes.get("uri");if(null===t)break t;let s=em(r,t),n=this.getSegmentedInputForPath(s),o=(await n.getTrackBackings()).find(e=>"audio"===e.getType());if(!o||await o.getCodec()===null)break t;let l=await o.getDecoderConfig().then(e=>e?.codec??null);i(null!==l),a.push(l)}}
1a=[...new Set(a)];let m=null,p=null,g=e.attributes.getAsNumber("bandwidth");i(null!==g);let k=e.attributes.getAsNumber("average-bandwidth"),b=e.attributes.get("name");for(let r of a){let i=eQ(r);if(null!==i){if(eR.includes(i)){if(null!==m)throw Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");m=r;let i=e.attributes.get("video");if(null===i){let r=e.attributes.get("resolution"),i=null,a=null;if(r){let e=r.match(/^(\d+)x(\d+)$/);e&&(i=Number(e[1]),a=Number(e[2]))}l.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:"und",lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:g,averageBitrate:k,name:b,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"video",width:i,height:a}})}else{if(!n.includes(i))throw Error(`Invalid M3U8 file; variant stream references video group "${i}" which is not defined in any #EXT-X-MEDIA tags.`);for(let r of s){let a=r.attributes.get("group-id"),s=r.attributes.get("type");if(a!==i||"video"!==s.toLowerCase())continue;let n=r.attributes.get("resolution")??e.attributes.get("resolution"),o=null,c=null;if(n){let e=n.match(/^(\d+)x(\d+)$/);e&&(o=Number(e[1]),c=Number(e[2]))}l.push({id:-1,demuxer:this,backingTrack:null,default:ah(r.attributes),autoselect:ah(r.attributes)||af(r.attributes),languageCode:am(r.attributes.get("language")),lineNumber:r.lineNumber,fullPath:r.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:r.attributes.get("name"),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"video",width:o,height:c}})}}}else if(eN.includes(i)){if(null!==p)throw Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");p=r;let i=e.attributes.get("audio");if(null===i){let r=e.attributes.get("channels"),i=null!==r?Number(r.split("/")[0]):null;l.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:"und",lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:g,averageBitrate:k,name:b,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==i&&Number.isInteger(i)&&i>0?i:null}})}else{if(!o.includes(i))throw Error(`Invalid M3U8 file; variant stream references audio group "${i}" which is not defined in any #EXT-X-MEDIA tags.`);for(let r of s){let a=r.attributes.get("group-id"),s=r.attributes.get("type");if(a!==i||"audio"!==s.toLowerCase())continue;let n=r.attributes.get("channels")??e.attributes.get("channels"),o=null!==n?Number(n.split("/")[0]):null;l.push({id:-1,demuxer:this,backingTrack:null,default:ah(r.attributes),autoselect:ah(r.attributes)||af(r.attributes),languageCode:am(r.attributes.get("language")),lineNumber:r.lineNumber,fullPath:r.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:r.attributes.get("name"),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==o&&Number.isInteger(o)&&o>0?o:null}})}}}}}return l})),c=[],u=e=>{let t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||=e.default,t.autoselect||=e.autoselect,t.lineNumber=Math.min(t.lineNumber,e.lineNumber),null!==e.peakBitrate&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),null!==e.averageBitrate&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),"und"===t.languageCode&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(let e of l)for(let t of e)u(t);for(let e of(c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[],c))"video"===e.info.type?this.trackBackings.push(new au(e)):this.trackBackings.push(new ad(e));this.internalTracks=c})()}async getTrackBackings(){return await this.readMetadata(),i(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let r=null;return this.internalTracks&&(r=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))),t=new ao(this,e,r,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return iS}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class ac{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,r=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===r.length)t=r[0];else if(this instanceof au){for(let e of r)if(await e.getCodec()===this.getCodec()){t=e;break}}else for(let e of(i(this instanceof ad),r))if(await e.getCodec()===this.getCodec()){t=e;break}if(!t)throw 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 Error("Not implemented on base class.")}getDisposition(){return{...eI,default:this.internalTrack.autoselect,primary:this.internalTrack.default}}getId(){return this.internalTrack.id}getPairingMask(){return this.internalTrack.pairingMask}getInternalCodecId(){return null}getLanguageCode(){return this.internalTrack.languageCode}getName(){return this.internalTrack.name}getNumber(){i(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let 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())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}
vendor: 1,594 bytes, line 1
1async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class au extends ac{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return eQ(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}
1async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class ad extends ac{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return eQ(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}let ah=e=>{let t=e.get("default");if(null===t)return!1;let r=t.toUpperCase();if("YES"===r)return!0;if("NO"===r)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},af=e=>{let t=e.get("autoselect");if(null===t)return!1;let r=t.toUpperCase();if("YES"===r)return!0;if("NO"===r)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},am=e=>{if(null===e)return"und";let t=e.split("-")[0];return t||"und"};class ap{constructor(){this._isIsobmff=!1}}class ag extends ap{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);let r=nr(t,4);return"ftyp"!==r&&"styp"!==r?null:nr(t,4)}_createDemuxer(e){return new rn(e)}}class ak extends ag{async _canReadInput(e){let t=await this._getMajorBrand(e);if(null!==t)return"qt  "!==t;let r=e._reader.requestSlice(4,4);if(r instanceof Promise&&(r=await r),!r)return!1;let i=nr(r,4);return"moof"===i||"sidx"===i}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class ab extends ag{async _canReadInput(e){return"qt  "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class ay extends ap{async isSupportedEBMLOfDocType(e,t){let r=e._reader.requestSlice(0,16);if(r instanceof Promise&&(r=await r),!r)return!1;let i=rC(r);if(null===i||i<1||i>8||rE(r,i)!==i6.EBML)return!1;let a=rA(r);if("number"!=typeof a)return!1;let s=e._reader.requestSlice(r.filePos,a);if(s instanceof Promise&&(s=await s),!s)return!1;let n=r.filePos;for(;s.filePos<=n+a-2;){let e=rF(s);if(!e)break;let{id:r,size:i}=e,a=s.filePos;if(void 0===i)return!1;switch(r){case i6.EBMLVersion:case i6.EBMLReadVersion:if(1!==rE(s,i))return!1;break;case i6.DocType:if(rM(s,i)!==t)return!1;break;case i6.DocTypeVersion:if(rE(s,i)>4)return!1}s.filePos=a+i}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new rq(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class aT extends ay{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class aw extends ap{async _canReadInput(e){let t=0;for(;;){let r=e._reader.requestSlice(t,ns);if(r instanceof Promise&&(r=await r),!r)break;let i=nc(r);if(!i)break;t=r.filePos+i.size}let r=await r$(e._reader,t,t+4096);if(!r)return!1;let i=r.header,a=tt(i.mpegVersionId,i.channel),s=e._reader.requestSlice(r.startPos+a,4);if(s instanceof Promise&&(s=await s),!s)return!1;let n=s2(s);if(0x58696e67===n||0x496e666f===n)return!0;t=r.startPos+r.header.totalSize;let o=await r$(e._reader,t,t+4);if(!o)return!1;let l=o.header;return i.channel===l.channel&&i.sampleRate===l.sampleRate}_createDemuxer(e){return new rK(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class aS extends ap{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let r=nr(t,4);return("RIFF"===r||"RIFX"===r||"RF64"===r)&&(t.skip(4),"WAVE"===nr(t,4))}_createDemuxer(e){return new r8(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}
1class aP extends ap{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===nr(t,4)}_createDemuxer(e){return new r1(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class av extends ap{async _canReadInput(e){let t=0;for(;;){let r=e._reader.requestSlice(t,ns);if(r instanceof Promise&&(r=await r),!r)break;let i=nc(r);if(!i)break;t=r.filePos+i.size}let r=e._reader.requestSlice(t,4);return r instanceof Promise&&(r=await r),!!r&&"fLaC"===nr(r,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new io(e)}}class ax extends ap{async _canReadInput(e){let t=0;for(;;){let r=e._reader.requestSlice(t,ns);if(r instanceof Promise&&(r=await r),!r)break;let i=nc(r);if(!i)break;t=r.filePos+i.size}let r=e._reader.requestSliceRange(t,7,9);if(r instanceof Promise&&(r=await r),!r)return!1;let i=r5(r);if(!i||(t+=i.frameLength,(r=e._reader.requestSliceRange(t,7,9))instanceof Promise&&(r=await r),!r))return!1;let a=r5(r);return!!a&&i.objectType===a.objectType&&i.samplingFrequencyIndex===a.samplingFrequencyIndex&&i.channelConfiguration===a.channelConfiguration}_createDemuxer(e){return new r7(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class aC extends ap{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let r=sG(t,205);return 71===r[0]&&71===r[188]||71===r[0]&&71===r[204]||71===r[4]&&71===r[196]||!1}_createDemuxer(e){return new ih(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class aI extends ap{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||"#EXTM3U"!==nr(t,7))return!1;if(!(e._rootSource instanceof iV))throw 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 al(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return iS}}let aE=new ak,a_=new ab,aB=new ay,aA=new aT,aF=new aw,aM=new aS,aR=new aP,aD=new ax,aO=new av,aN=new aC,az=[new aI,aE,a_,aB,aA,aM,aR,aO,aF,aD,aN],aU=(e,t)=>{if(!e||"object"!=typeof e)throw TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!=typeof e.isobmff)throw TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!=typeof e.isobmff.resolveKeyId)throw TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!=typeof e.hls)throw TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!=typeof e.hls.offsetTimestampsByDateTime)throw TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}},aL=[],aW=[],aq=[],aV=e=>{let t=e,r=4096,i=0,a=12,s=0;for(t<0&&(t=-t,i=128),(t+=33)>8191&&(t=8191);(t&r)!==r&&a>=5;)r>>=1,a--;return s=t>>a-4&15,255&~(i|a-5<<4|s)},aH=e=>{let t=0,r=0,i=~e;128&i&&(i&=-129,t=-1);let a=(1<<(r=((240&i)>>4)+5)|(15&i)<<r-4|1<<r-5)-33;return 0===t?a:-a},aj=e=>{let t=2048,r=0,i=11,a=0,s=e;for(s<0&&(s=-s,r=128),s>4095&&(s=4095);(s&t)!==t&&i>=5;)t>>=1,i--;return a=s>>(4===i?1:i-4)&15,(r|i-4<<4|a)^85},a$=e=>{let t=0,r=0,i=85^e;128&i&&(i&=-129,t=-1);let a=0;return a=4!=(r=((240&i)>>4)+4)?1<<r|(15&i)<<r-4|1<<r-5:i<<1|1,0===t?a:-a};var aK=function(e,t,r){if(null!=t){var i,a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");if(r){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");i=t[Symbol.asyncDispose]}if(void 0===i){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");i=t[Symbol.dispose],r&&(a=i)}if("function"!=typeof i)throw TypeError("Object not disposable.");a&&(i=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:i,async:r})}else r&&e.stack.push({async:!0});return t},aX=(iJ="function"==typeof SuppressedError?SuppressedError:function(e,t,r){var i=Error(r);return i.name="SuppressedError",i.error=e,i.suppressed=t,i},function(e){function t(t){e.error=e.hasError?new iJ(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var r,i=0;return function a(){for(;r=e.stack.pop();)try{if(!r.async&&1===i)return i=0,e.stack.push(r),Promise.resolve().then(a);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return i|=2,Promise.resolve(s).then(a,function(e){return t(e),a()})}else i|=1}catch(e){t(e)}
1if(1===i)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()});eh();let aG=-1/0,aQ=-1/0,aY=null;"undefined"!=typeof FinalizationRegistry&&(aY=new FinalizationRegistry(e=>{let t=performance.now();"video"===e.type?(t-aG>=1e3&&(eP._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."),aG=t),"undefined"!=typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-aQ>=1e3&&(eP._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."),aQ=t),"undefined"!=typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class aJ{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}let aZ=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],a0=new Set(aZ);class a1{get codedWidth(){return this.visibleRect.width}get codedHeight(){return this.visibleRect.height}get displayWidth(){return this.rotation%180==0?this.squarePixelWidth:this.squarePixelHeight}get displayHeight(){return this.rotation%180==0?this.squarePixelHeight:this.squarePixelWidth}get microsecondTimestamp(){return Math.trunc(Q*this.timestamp)}get microsecondDuration(){return Math.trunc(Q*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0===t.format||!a0.has(t.format))throw TypeError("init.format must be one of: "+aZ.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw TypeError("init.layout, when provided, must be an array.");for(let e of t.layout){if(!e||"object"!=typeof e||Array.isArray(e))throw TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.visibleRect&&eb(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!=(void 0!==t.displayHeight))throw TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;let r=t.layout??st(t.format,t.codedWidth,t.codedHeight),i=t.colorSpace??null;null===i&&(i="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180==0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180==0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotC
1opy?c(e):c(e).slice(),this._layout=r,this.colorSpace=new a6(i)}else if("undefined"!=typeof VideoFrame&&e instanceof VideoFrame){if(t?.rotation!==void 0&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(t?.timestamp!==void 0&&!Number.isFinite(t?.timestamp))throw TypeError("init.timestamp, when provided, must be a number.");if(t?.duration!==void 0&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");t?.visibleRect!==void 0&&eb(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new a6(e.colorSpace)}else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&eb(t.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new a1(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Q),duration:Math.trunc((t.duration??0)*Q)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let r=0,i=0;if("naturalWidth"in e?(r=e.naturalWidth,i=e.naturalHeight):"videoWidth"in e?(r=e.videoWidth,i=e.videoHeight):"width"in e&&(r=Number(e.width),i=Number(e.height)),!r||!i)throw TypeError("Could not determine dimensions.");let a=t.visibleRect??{left:0,top:0,width:r,height:i},s=new OffscreenCanvas(a.width,a.height),n=s.getContext("2d",{alpha:er(),willReadFrequently:!0});if(!n)throw Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");n.drawImage(e,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new a6({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof aJ){if(!t||"object"!=typeof t)throw TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!aZ.includes(this.format))throw 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 TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace
1=e.getColorSpace()}else throw TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=ek({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),aY?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");return(i(null!==this._data),this._data instanceof aJ)?new a1(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):a5(this._data)?new a1(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(i(this._layout),new a1(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new a1(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(aY?.unregister(this),this._data instanceof aJ?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):a5(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(se(e),this._closed)throw Error("VideoSample is closed.");if((e.format??this.format)==null)throw Error("Cannot get allocation size when format is null.");return a5(this._data)?this._data.allocationSize(e):si(this,e).allocationSize}async copyTo(e,t={}){let r;if(!w(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(se(t),this._closed)throw Error("VideoSample is closed.");if((t.format??this.format)==null)throw Error("Cannot copy video sample data when format is null.");if(i(null!==this._data),a5(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 aJ){let r={stack:[],error:void 0,hasError:!1};try{let i=aK(r,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(i instanceof a1))throw TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(i.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${i.format}' instead.`);return await i.copyTo(e,t)}catch(e){r.error=e,r.hasError=!0}finally{aX(r)}}else{if("undefined"==typeof VideoFrame)throw Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");let r=this.toVideoFrame(),i=await r.copyTo(e,t);return r.close(),i}let a=si(this,t);i(this.format);let s=c(e);if(s.byteLength<a.allocationSize)throw TypeError(`Destination buffer too small. Required: ${a.allocationSize}, Available: ${s.byteLength}`);let n=sr(this.format);if(this._data instanceof aJ){let e=this._data.getDataPlanes();if(e instanceof Promise&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');r=e}else if(this._data instanceof Uint8Array)i(this._layout),i(this._layout.length===n.length),r=this._layout.map((e,t)=>{let r=Math.ceil(this.codedHeight/n[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*r),stride:e.stride}});else{let e=this._data.getContext("2d");i(e),r=[{data:c(e.getImageData(0,0,this.codedWidth,this.codedHeight).data),stride:4*this.codedWidth}]}let o=[],l=n.length;for(let e=0;e<l;e++){let t=a.computedLayouts[e],i=r[e].stride,n=r[e].data,l=t.sourceTop*i;l+=t.sourceLeftBytes;
1let c=t.destinationOffset,u=t.sourceWidthBytes,d={offset:c,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(l+u>n.byteLength)throw Error("Source buffer OOB read.");if(c+u>s.byteLength)throw Error("Destination buffer OOB write.");let e=n.subarray(l,l+u);s.set(e,c),l+=i,c+=t.destinationStride}o.push(d)}if(void 0!==t.format){let e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),r=this.format.includes("X")&&t.format.includes("A");if(e||r)for(let t=0;t<a.allocationSize;t+=4){if(e){let e=s[t],r=s[t+2];s[t]=r,s[t+2]=e}r&&(s[t+3]=255)}}return o}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(i(null!==this._data),this._data instanceof aJ){if(null===this.format)throw Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");let e=this._data.getDataPlanes();if(e instanceof Promise)throw Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");let t=new Uint8Array(e.reduce((e,t)=>e+t.data.byteLength,0)),r=0,i=[];for(let a of e)t.set(a.data,r),i.push(r),r+=a.data.byteLength;return new VideoFrame(t,{format:this.format,layout:e.map((e,t)=>({offset:i[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return a5(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(i(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,r,i,a,s,n,o,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(c=t,u=r,d=i,h=a,f=s,m=n,void 0!==o?(p=o,g=l):(p=d,g=h)):(f=t,m=r,void 0!==i&&(p=i,g=a)),!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw TypeError("sx must be a number.");if(!Number.isFinite(u))throw TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw TypeError("dx must be a number.");if(!Number.isFinite(m))throw TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw TypeError("dHeight must be a non-negative number.");if(this._closed)throw Error("VideoSample is closed.");({sx:c,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(c,u,d,h,this.rotation));let k=this.toCanvasImageSource();e.save();let b=f+p/2,y=m+g/2;e.translate(b,y),e.rotate(this.rotation*Math.PI/180);let T=this.rotation%180==0?1:p/g;e.scale(1/T,T),e.drawImage(k,c,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){let r,i,a,s;if(!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&a9(t.crop,"options.");let n=e.canvas.width,o=e.canvas.height,l=t.rotation??this.rotation,[c,u]=l%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],d=t.crop;d&&(d=a7(d,c,u));let{sx:h,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??c,t.crop?.height??u,l);if("fill"===t.fit)r=0,i=0,a=n,s=o;else{let[e,l]=t.crop?[t.crop.width,t.crop.height]:[c,u],d="contain"===t.fit?Math.min(n/e,o/l):Math.max(n/e,o/l);a=e*d,s=l*d,r=(n-a)/2,i=(o-s)/2}e.save();let g=l%180==0?1:a/s;e.translate(n/2,o/2),e.rotate(l*Math.PI/180),e.scale(1/g,g),e.translate(-n/2,-o/2),e.drawImage(this.toCanvasImageSource(),h,f,m,p,r,i,a,s),e.restore(
1)}_rotateSourceRegion(e,t,r,i,a){return 90===a?[e,t,r,i]=[t,this.squarePixelHeight-e-r,i,r]:180===a?[e,t]=[this.squarePixelWidth-e-r,this.squarePixelHeight-t-i]:270===a&&([e,t,r,i]=[this.squarePixelWidth-t-i,e,i,r]),{sx:e,sy:t,sWidth:r,sHeight:i}}_drawWithFitAndMipmapping(e,t,r){let i=e.width,a=e.height,[s,n]=r.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=r.crop?r.crop.width:s,l=r.crop?r.crop.height:n,c=0;2*i<o&&2*a<l&&(c=Math.floor(Math.log2(Math.min(o/i,l/a))));let u=i*2**c,d=a*2**c,{canvas:h,context:f,isNew:m}=c>0?a8(u,d):{canvas:e,context:t,isNew:r.targetIsFresh};f.imageSmoothingQuality="high",r.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:r.fit,rotation:r.rotation,crop:r.crop}),f.globalCompositeOperation="copy";for(let e=c;e>1;e--){let t=i*2**e,r=a*2**e;f.drawImage(h,0,0,t,r,0,0,t/2,r/2)}f.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*i,2*a,0,0,i,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(i(null!==this._data),!(this._data instanceof aJ||this._data instanceof Uint8Array))return this._data;{let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}}async transform(e){let t,r;if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&a9(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let i=a(this.rotation+(e.rotate??0)),[s,n]=i%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=e.crop;o&&(o=a7(o,s,n));let l=o?o.width:s,c=o?o.height:n,u=l/c;void 0!==e.width&&void 0===e.height?r=(t=e.width)/u:void 0===e.width&&void 0!==e.height?t=(r=e.height)*u:void 0!==e.width&&void 0!==e.height?(t=e.width,r=e.height):(t=l,r=c);let d={width:t=H(t,e.roundDimensionsTo??1),height:r=H(r,e.roundDimensionsTo??1),fit:e.fit??"fill",rotation:i,crop:o??{left:0,top:0,width:s,height:n},alpha:e.alpha??"keep"};for(let e of a2){let t=e(this,d);if(t instanceof Promise&&(t=await t),null!==t)return t}let{canvas:h,context:f,isNew:m}=a8(d.width,d.height);return this._drawWithFitAndMipmapping(h,f,{fit:d.fit,rotation:d.rotation,crop:d.crop,targetIsFresh:m,fillBlack:"discard"===d.alpha}),new a1(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!=typeof e)throw TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}let a2=[],a3=[],a4=0,a8=(e,t)=>{let r;for(let r of a3)if(r.canvas.width===e&&r.canvas.height===t)return r.age=a4++,{canvas:r.canvas,context:r.context,isNew:!1};if("undefined"!=typeof OffscreenCanvas)r=new OffscreenCanvas(e,t);else{if("undefined"==typeof window||"undefined"==typeof document)throw Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");(r=document.createElement("canvas")).width=e,r.height=t}let i=r.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!i)throw Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return a3.length>=3&&a3.splice(eg(a3,e=>e.age),1),a3.push({canvas:r,context:i,age:a4++}),{canvas:r,context:i,isNew:!0}};class a6{constructor(e){if(void 0!==e){if(!e||"object"!=typeof e)throw TypeError("init.colorSpace, when provided, must be an object.");let t=Object.keys(m);if(null!=e.primaries&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);let r=Object.keys(g);if(null!=e.transfer&&!r.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${r.join(", ")}.`);let i=Object.keys(b);if(null!=e.matrix&&!i.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${i.join(", ")}.`);
1if(null!=e.fullRange&&"boolean"!=typeof e.fullRange)throw TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}let a5=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,a7=(e,t,r)=>{let a=Math.min(e.left,t),s=Math.min(e.top,r),n=Math.min(e.width,t-a),o=Math.min(e.height,r-s);return i(n>=0),i(o>=0),{left:a,top:s,width:n,height:o}},a9=(e,t)=>{if(!e||"object"!=typeof e)throw TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw TypeError(t+"crop.height must be a non-negative integer.")},se=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw TypeError("options.colorSpace, when provided, must be 'dis
1play-p3' or 'srgb'.");if(void 0!==e.format&&"string"!=typeof e.format)throw TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw TypeError("options.layout, when provided, must be an array.");for(let t of e.layout){if(!t||"object"!=typeof t)throw TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!=typeof e.rect)throw TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw TypeError("options.rect.height, when provided, must be a non-negative integer.")}},st=(e,t,r)=>{let i=sr(e),a=[],s=0;for(let e of i){let i=Math.ceil(t/e.widthDivisor),n=Math.ceil(r/e.heightDivisor),o=i*e.sampleBytes,l=o*n;a.push({offset:s,stride:o}),s+=l}return a},sr=e=>{let t=(e,t,r,i,a)=>{let s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:r,heightDivisor:i},{sampleBytes:t,widthDivisor:r,heightDivisor:i}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:D(e),i(!1)}},si=(e,t)=>{let r,i=sa({left:0,top:0,width:e.codedWidth,height:e.codedHeight},t.rect,e.codedWidth,e.codedHeight,e.format),a=t.layout;if(t.format&&t.format!==e.format)if(["RGBA","RGBX","BGRA","BGRX"].includes(t.format))r=t.format;else throw Error("NotSupportedError: Invalid destination format.");else r=e.format;return sn(i,r,a)},sa=(e,t,r,i,a)=>{let s={...e};if(void 0!==t){if(0===t.width||0===t.height)throw TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>r)throw TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>i)throw TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!ss(a,s))throw TypeError("visibleRect alignment is invalid for the format.");return s},ss=(e,t)=>{if(null===e)return!0;let r=sr(e);for(let e=0;e<r.length;e++){let i=r[e],a=i.widthDivisor,s=i.heightDivisor;if((t.x||0)%a!=0||(t.y||0)%s!=0)return!1}return!0},sn=(e,t,r)=>{let i=sr(t),a=i.length;if(void 0!==r&&r.length!==a)throw TypeError(`Layout must have ${a} planes.`);let s=0,n=[],o=[];for(let t=0;t<a;t++){let a=i[t],l=a.sampleBytes,c=a.widthDivisor,u=a.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/c)*l,d.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/c)*l,void 0!==r){let e=r[t];if(e.stride<d.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=s,d.destinationStride=d.sourceWidthBytes;let h=d.destinationStride*d.sourceHeight+d.destinationOffset;if(h>0xffffffff)throw TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let e=0;e<t;e++){let r=n[e];if(!(o[t]<=r.destinationOffset)&&!(o[e]<=d.destinationOffset))throw TypeError("Planes overlap.")}n.push(d)}return{allocationSize:s,computedLayouts:n}},so=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class sl{constructor(){this._referenceCount=0}}class sc{get microsecondTimestamp(){return Math.trunc(Q*this.timestamp)}get microsecondDuration(){return Math.trunc(Q*this.duration)}constructor(e){if(this._closed=!1,sm(e)){if(null===e.format)throw 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 sl){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!so.has(this.format))throw TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{let t;if(!e||"object"!=typeof e)throw TypeError("Invalid AudioDataInit: must be an object.");if(!so.has(e.format))throw TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw TypeError("init.timestamp must be a number.");let r=e.data.byteLength/(su(e.format)*e.numberOfChannels);if(!Number.isInteger(r))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=r,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=r/e.sampleRate,e.data instanceof ArrayBuffer)t=new Uint8Array(e.data);else if(ArrayBuffer.isView(e.data))t=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength);else throw TypeError("Invalid AudioDataInit: data is not a BufferSource.");let i=this.numberOfFrames*this.numberOfChannels*su(this.format);if(t.byteLength<i)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=t}aY?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!so.has(e.format))throw TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let t=e.format??this.format,r=e.frameOffset??0;if(r>=this.numberOfFrames)throw RangeError("frameOffset out of range");let i=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-r;if(i>this.numberOfFrames-r)throw RangeError("frameCount out of range");let a=su(t),s=sd(t);if(s&&e.planeIndex>=this.numberOfChannels||!s&&0!==e.planeIndex)throw RangeError("planeIndex out of range");return(s?i:i*this.numberOfChannels)*a}copyTo(e,t){if(!w(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!so.has(t.format))throw TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw TypeError("frameCount must be a non-negative integer.");if(this._closed)throw Error("AudioSample is closed.");let{format:r,frameCount:i,frameOffset:a}=t,{planeIndex:s}=t,n=this.format,o=r??this.format;if(!o)throw Error("Destination format not determined");let l=this.numberOfFrames,c=this.numberOfChannels,d=a??0;if(d>=l)throw RangeError("frameOffset out of range");let h=void 0!==i?i:l-d;if(h>l-d)throw RangeError("frameCount out of range");let f=su(o),m=sd(o);if(m&&s>=c||!m&&0!==s)throw RangeError("planeIndex out of range");let p=m?h:h*c;if(e.byteLength<p*f)throw RangeError("Destination buffer is too small");let g=u(e),k=sf(o);if(sm(this._data))ee()&&c>
12&&o!==n?sg(this._data,g,n,o,c,s,d,h):this._data.copyTo(e,{planeIndex:s,frameOffset:d,frameCount:h,format:o});else{let e,t=sh(n),r=su(n),i=sd(n);if(this._data instanceof sl){let t=e=>{let t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw TypeError("getDataPlane() must return a Uint8Array.");let a=l*r*(i?1:c);if(t.byteLength!==a)throw TypeError(`Data plane ${e} has invalid size. Expected exactly ${a} bytes, got ${t.byteLength} bytes.`);return t};if(i)if(m)e=t(s),s=0;else{e=new Uint8Array(l*r*c);for(let i=0;i<c;i++){let a=t(i);e.set(a,i*l*r)}}else e=t(0)}else e=this._data;let a=u(e);for(let e=0;e<h;e++)if(m){let n;k(g,e*f,t(a,i?(s*l+(e+d))*r:((e+d)*c+s)*r))}else for(let s=0;s<c;s++){let n;k(g,(e*c+s)*f,t(a,i?(s*l+(e+d))*r:((e+d)*c+s)*r))}}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(this._data instanceof sl){let e=new sc(this._data);return e.setTimestamp(this.timestamp),e}if(!sm(this._data))return new sc({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data});{let e=new sc(this._data.clone());return e.setTimestamp(this.timestamp),e}}trim(e,t=this.numberOfFrames){let r;if(!Number.isInteger(e)||e<0)throw TypeError("startSample must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw TypeError("endSample must be a non-negative integer.");if(e>this.numberOfFrames)throw RangeError("startSample out of range.");if(t>this.numberOfFrames)throw RangeError("endSample out of range.");if(t<e)throw RangeError("endSample must not be less than startSample.");if(this._closed)throw Error("AudioSample is closed.");let i=t-e,a=su(this.format);if(sd(this.format)){let t=i*a;if(r=new Uint8Array(t*this.numberOfChannels),i>0)for(let a=0;a<this.numberOfChannels;a++)this.copyTo(r.subarray(a*t,(a+1)*t),{planeIndex:a,format:this.format,frameOffset:e,frameCount:i})}else r=new Uint8Array(i*this.numberOfChannels*a),i>0&&this.copyTo(r,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new sc({data:r,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(aY?.unregister(this),this._data instanceof sl?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):sm(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw Error("AudioSample is closed.");return this._data instanceof sl?this._createAudioDataFromData():sm(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(sd(this.format)){let 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})}{let 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 Error("AudioSample is closed.");let 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 TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let r=e.numberOfChannels,i=e.sampleRate,a=e.length,s=Math.floor(24e4/r),n=0,o=a;for(;o>0;){let a=Math.min(s,o),l=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(l.subarray(t*a,(t+1)*a),t,n);yield new sc({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:l}),n+=a,o-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let r=e.numberOfChannels,i=e.sampleRate,a=e.length,s=Math.floor(24e4/r),n=0,o=a,l=[];for(;o>0;){let a=Math.min(s,o),c=new Float32Array(r*a);for(let t=0;t<r;t++)e.copyFromChannel(c.subarray(t*a,(t+1)*a),t,n);let u=new sc({format:"f32-planar",sampleRate:i,numberOfFrames:a,numberOfChannels:r,timestamp:t+n/i,data:c});l.push(u),n+=a,o-=a}return l}}let su=e=>{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw Error("Unknown AudioSampleFormat")}},sd=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},sh=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/0x80000000;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},sf=e=>{switch(e){case"u8":case"u8-planar":return(e,t,r)=>e.setUint8(t,W((r+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,r)=>e.setInt16(t,W(Math.round(32767*r),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,r)=>e.setInt32(t,W(Math.round(0x7fffffff*r),-0x80000000,0x7fffffff),
1!0);case"f32":case"f32-planar":return(e,t,r)=>e.setFloat32(t,r,!0)}},sm=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,sp=e=>{switch(e){case"u8-planar":return"u8";case"s16-planar":return"s16";case"s32-planar":return"s32";case"f32-planar":return"f32";default:return e}},sg=(e,t,r,i,a,s,n,o)=>{let l=sh(r),c=sf(i),d=su(r),h=su(i),f=sd(r);if(sd(i))if(f){let i=new ArrayBuffer(o*d),a=u(i);e.copyTo(i,{planeIndex:s,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){let r=e*d;c(t,e*h,l(a,r))}}else{let i=new ArrayBuffer(o*a*d),f=u(i);e.copyTo(i,{planeIndex:0,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){let r=(e*a+s)*d;c(t,e*h,l(f,r))}}else if(f){let i=new ArrayBuffer(o*d),s=u(i);for(let u=0;u<a;u++){e.copyTo(i,{planeIndex:u,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++){let r=e*d;c(t,(e*a+u)*h,l(s,r))}}}else{let i=new ArrayBuffer(o*a*d),s=u(i);e.copyTo(i,{planeIndex:0,frameOffset:n,frameCount:o,format:r});for(let e=0;e<o;e++)for(let r=0;r<a;r++){let i=e*a+r,n=i*d;c(t,i*h,l(s,n))}}},sk=(e,t)=>{let r=new ArrayBuffer(e.allocationSize({format:t,planeIndex:0}));return e.copyTo(r,{format:t,planeIndex:0}),new sc({data:r,format:t,numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,timestamp:e.timestamp,duration:e.duration})},sb=e=>{if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!=typeof e.metadataOnly)throw TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!=typeof e.verifyKeyPackets)throw TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(void 0!==e.skipLiveWait&&"boolean"!=typeof e.skipLiveWait)throw TypeError("options.skipLiveWait, when defined, must be a boolean.")},sy=e=>{if(!ef(e))throw TypeError("timestamp must be a number.")},sT=(e,t,r)=>r.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;let r=await e.determinePacketType(t);return r&&(t.type=r),t}):t;class sw{constructor(e){if(!(e instanceof s_))throw TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(sb(e),this._track.input._disposed)throw new sj;return sT(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){sb(e);let t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(sy(e),sb(t),this._track.input._disposed)throw new sj;return sT(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof tG))throw TypeError("packet must be an EncodedPacket.");if(sb(t),this._track.input._disposed)throw new sj;return sT(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(sy(e),sb(t),this._track.input._disposed)throw new sj;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let r=await this._track._backing.getKeyPacket(e,t);return r&&(i("key"===r.type),"delta"===await this._track.determinePacketType(r))?this.getKeyPacket(r.timestamp-1/await this._track.getTimeResolution(),t):r}async getNextKeyPacket(e,t={}){if(!(e instanceof tG))throw TypeError("packet must be an EncodedPacket.");if(sb(t),this._track.input._disposed)throw new sj;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let r=await this._track._backing.getNextKeyPacket(e,t);return r&&(i("key"===r.type),"delta"===await this._track.determinePacketType(r))?this.getNextKeyPacket(r,t):r}packets(e,t,r={}){if(void 0!==e&&!(e instanceof tG))throw TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!r?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof tG))throw TypeError("endPacket must be an EncodedPacket.");if(sb(r),this._track.input._disposed)throw new sj;let i=[],{promise:a,resolve:s}=_(),{promise:n,resolve:o}=_(),l=!1,c=!1,u=null,d=!1,h=[],f=()=>Math.max(2,h.length);(async()=>{let u=e??await this.getFirstPacket(r);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);){if(i.length>f()){({promise:n,resolve:o}=_()),await n;continue}i.push(u),s(),({promise:a,resolve:s}=_()),u=await this.getNextPacket(u,r)}l=!0,s()})().catch(e=>{d||(u=e,d=!0,s())});let m=this._track;return{async next(){for(;;)if(m.input._disposed)throw new sj;else if(c)return{value:void 0,done:!0};else if(d)throw u;else if(i.length>0){let e=i.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}else{if(l)return{value:void 0,done:!0};await a}},return:async()=>(c=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class sS{constructor(e,t){this.onSample=e,this.onError=t}}class sP{mediaSamplesInRange(e=-1/0,t=1/0,r){sy(e),sy(t);let i=[],a=!1,s=null,{promise:n,resolve:o}=_(),{promise:l,resolve:c}=_(),u=!1,d=!1,h=!1,f=null,m=null,p=!1,g={...r,verifyKeyPackets:!0,metadataOnly:!1};(async()=>
1{f=await this._createDecoder(r=>{if(c(),r.timestamp>=t&&(d=!0),d)return void r.close();s&&(r.timestamp>e?(i.push(s),a=!0):s.close()),r.timestamp>=e&&(i.push(r),a=!0),s=a?null:r,i.length>0&&(o(),{promise:n,resolve:o}=_())},e=>{p||(m=e,p=!0,o())});let r=this._createPacketSink(),k=await r.getKeyPacket(e,g)??await r.getFirstKeyPacket(g),b=k,y=r.packets(k??void 0,void 0,g);for(await y.next();b&&!d&&!this._track.input._disposed;){let e=sv(i.length);if(i.length+f.getDecodeQueueSize()>e){({promise:l,resolve:c}=_()),await l;continue}f.decode(b);let t=await y.next();if(t.done)break;b=t.value}await y.return(),h||this._track.input._disposed||await f.flush(),!a&&s&&i.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});let k=this._track,b=()=>{for(let e of(s?.close(),i))e.close()};return{async next(){for(;;)if(k.input._disposed)throw b(),new sj;else if(h)return{value:void 0,done:!0};else if(p)throw b(),m;else if(i.length>0){let e=i.shift();return c(),{value:e,done:!1}}else{if(u)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,d=!0,c(),o(),b(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){R(e);let r=M(e),a=[],s=[],{promise:n,resolve:o}=_(),{promise:l,resolve:c}=_(),u=!1,d=!1,h=null,f=null,m=!1,p=e=>{s.push(e),o(),{promise:n,resolve:o}=_()},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),d)return void e.close();let t=0;for(;a.length>0&&e.timestamp-a[0]>-1e-10;)t++,a.shift();if(t>0)for(let r=0;r<t;r++)p(r<t-1?e.clone():e);else e.close()},e=>{m||(f=e,m=!0,o())});let e=this._createPacketSink(),t=null,n=null,k=-1,b=async()=>{i(n),i(h);let t=n;for(h.decode(t);t.sequenceNumber<k;){let r=sv(s.length);for(;s.length+h.getDecodeQueueSize()>r&&!d;)({promise:l,resolve:c}=_()),await l;if(d)break;let a=await e.getNextPacket(t,g);i(a),h.decode(a),t=a}k=-1},y=async()=>{i(h),await h.flush();for(let e=0;e<a.length;e++)p(null);a.length=0};for await(let i of r){if(sy(i),d||this._track.input._disposed)break;let r=await e.getPacket(i,g),s=r&&await e.getKeyPacket(i,g);if(!s){-1!==k&&(await b(),await y()),p(null),t=null;continue}t&&(s.sequenceNumber!==n.sequenceNumber||r.timestamp<t.timestamp)&&(await b(),await y()),a.push(r.timestamp),k=Math.max(r.sequenceNumber,k),t=r,n=s}d||this._track.input._disposed||(-1!==k&&await b(),await y()),u=!0,o()})().catch(e=>{m||(f=e,m=!0,o())}).finally(()=>{h?.close()});let k=this._track,b=()=>{for(let e of s)e?.close()};return{async next(){for(;;)if(k.input._disposed)throw b(),new sj;else if(d)return{value:void 0,done:!0};else if(m)throw b(),f;else if(s.length>0){let e=s.shift();return i(void 0!==e),c(),{value:e,done:!1}}else{if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,c(),o(),b(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}let sv=e=>0===e?40:8;
1class sx extends sS{constructor(e,t,r,i){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new J,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let a=t=>{let r=t.timestamp;this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-r),r+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(r-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=r);let a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();let s=i.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=aW.find(e=>e.supports(r,i));if(s)this.customDecoder=new s,this.customDecoder.codec=r,this.customDecoder.config=i,this.customDecoder.onSample=e=>{if(!(e instanceof sc))throw TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{let e=Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new sc(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(i)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(i(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(i(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(i(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(i(this.decoder),this.decoder.close())}}class sC extends sS{constructor(e,t,r){super(e,t),this.decoderConfig=r,this.currentTimestamp=null,i(eD.includes(r.codec)),this.codec=r.codec;let{dataType:a,sampleSize:s,littleEndian:n}=eG(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===a?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===a?this.readInputValue=(e,t)=>aH(e.getUint8(t)):"alaw"===a?this.readInputValue=(e,t)=>a$(e.getUint8(t)):i(!1);break;case 2:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===a?this.readInputValue=(e,t)=>e.getInt16(t,n):i(!1);break;case 3:"unsigned"===a?this.readInputValue=(e,t)=>O(e,t,n)-8388608:"signed"===a?this.readInputValue=(e,t)=>N(e,t,n):i(!1);break;case 4:"unsigned"===a?this.readInputValue=(e,t)=>e.getUint32(t,n)-0x80000000:"signed"===a?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===a?this.readInputValue=(e,t)=>e.getFloat32(t,n):i(!1);break;case 8:"float"===a?this.readInputValue=(e,t)=>e.getFloat64(t,n):i(!1);break;default:D(s),i(!1)}switch(s){case 1:"ulaw"===a||"alaw"===a?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,r)=>e.setUint8(t,r+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,r)=>e.setInt16(t,r,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r<<8,!0);break;case 4:this.outputSampleSize=4,"float"===a?(this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,r)=>e.setInt32(t,r,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,!0);break;default:D(s),i(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=u(e.data),r=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,i=new ArrayBuffer(r*this.decoderConfig.numberOfChannels*this.outputSampleSize),a=new DataView(i);for(let e=0;e<r*this.decoderConfig.numberOfChannels;e++){let r=e*this.inputSampleSize,i=e*this.outputSampleSize,s=this.readInputValue(t,r);this.writeOutputValue(a,i,s)}let s=r/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=s)&&(this.currentTimestamp=e.timestamp);let n=this.currentTimestamp;this.currentTimestamp+=s;let o=new sc({format:this.outputFormat,data:i,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:r,timestamp:n});this.onSample(o)}async flush(){}close(){}}class sI extends sP{constructor(e){if(!(e instanceof sM))throw TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");let r=await this._track.getCodec(),a=await this._track.getDecoderConfig();return(i(r&&a),eD.includes(a.codec))?new sC(e,t,a):new sx(e,t,r,a)}_createPacketSink(){return new sw(this._track)}async getSample(e,t={}){for await(let r of(sy(e),this.mediaSamplesAtTimestamps([e],t)))return r;throw 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 sE{constructor(e){if(!(e instanceof sM))throw TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new sI(e)}_audioSampleToWrappedArrayBuffer(e){let t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){sy(e);let r=await this._audioSampleSink.getSample(e,t);return r&&this._audioSampleToWrappedArrayBuffer(r)}buffers(e,t,r){return L(this._audioSampleSink.samples(e,t,r),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return L(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class s_{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof sF}isAudioTrack(){return this instanceof sM}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return sB(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return sB(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return sB(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return sB(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())!==null}async getDisposition(){return this._backing.getDisposition()}get disposition(){return sB(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){let e=await this._backing.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async computeDuration(e){let t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return j((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let r=new sw(this),i=1/0,a=-1/0,s=0,n=0;for await(let o of r.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;i=Math.min(i,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-i)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-i)).toPrecision(16)):0}}
1async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof s_))throw TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&(this._backing.getPairingMask()&e._backing.getPairingMask())!==0n}async getPairableTracks(e){return this.input.getTracks(sN({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(sN({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(sN({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(sN({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(sN({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){for(let t of(e&&=sA(e),await this.input.getTracks()))if(this.canBePairedWith(t)&&(!e||await e(t)))return!0;return!1}hasPairableVideoTrack(e){return e&&=sA(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=sA(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}let sB=(e,t,r)=>{if(e instanceof Promise)throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${r}()' instead.`);return e},sA=e=>{if(void 0!==e&&"function"!=typeof e)throw TypeError("predicate, when provided, must be a function.");return e?t=>{let r=e=>{if("boolean"!=typeof e)throw TypeError("predicate must return or resolve to a boolean value.");return e},i=e(t);return i instanceof Promise?i.then(r):r(i)}:void 0};class sF extends s_{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 sB(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??await this._backing.getCodec()==="prores"}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return sB(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return sB(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return sB(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return sB(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return sB(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=ek({num:await this.get
1SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=ek({num:sB(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*sB(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:sB(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*sB(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}async getDisplayWidth(){let e=await this._backing.getMetadataDisplayWidth?.();return null!=e?e:await this.getRotation()%180==0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){let e=this._backing.getMetadataDisplayWidth?.();if(void 0!==e){let t=sB(e,"displayWidth","getDisplayWidth");if(null!==t)return t}let t=sB(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return sB(t,"displayWidth","getDisplayWidth")}async getDisplayHeight(){let e=await this._backing.getMetadataDisplayHeight?.();return null!=e?e:await this.getRotation()%180==0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){let e=this._backing.getMetadataDisplayHeight?.();if(void 0!==e){let t=sB(e,"displayHeight","getDisplayHeight");if(null!==t)return t}let t=sB(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return sB(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){let e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}
1async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();if(null!=e)return e;let t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();if(i(null!==t),aL.some(r=>r.supports(t,e)))return!0;if("undefined"==typeof VideoDecoder)return!1;let r=await VideoDecoder.isConfigSupported(e);return!0===r.supported}catch(e){return eP._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof tG))throw TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw TypeError("packet must not be metadata-only to determine its type.");let t=await this.getCodec();if(null===t)return null;let r=await this.getDecoderConfig();return i(r),tN(t,r,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!Number.isFinite(e.targetPacketCount)||e.targetPacketCount<0))throw TypeError("options.targetPacketCount must be a non-negative number.");let t=await this.getTimeResolution(),r=e.targetPacketCount??256,i=new sw(this),a=[],s=-1/0,n=0;for await(let e of i.packets(void 0,void 0,{metadataOnly:!0})){if(a.length>=r&&e.timestamp>=s)break;a.push(e.timestamp),s=Math.max(s,e.timestamp),n++}let o=new Float64Array(a.length);for(let e=0;e<a.length;e++)o[e]=Math.round(a[e]*t);o.sort();let l=1;for(let e=1;e<o.length;e++)o[e]!==o[l-1]&&(o[l++]=o[e]);if(l<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:n};let c=o.subarray(0,l),u=sU(c,t),d=u??t,h=null!==u?t/u:null,f=new Map,m=1/0,p=-1/0,g=0;for(let e=1;e<l;e++){let t=c[e]-c[e-1],r=null!==h?Math.max(1,Math.round(t/h)):t;f.set(r,(f.get(r)??0)+1),m=Math.min(m,r),p=Math.max(p,r),g+=r}let k=l-1,b=[...f.keys()].sort((e,t)=>e-t),y=k-1>>1,T=k>>1,w=0,S=0,P=0;for(let e of b)if(P+=f.get(e),0===w&&P>y&&(w=e),P>T){S=e;break}let v=(d/w+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:sW(v),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:v,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class sM extends s_{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return sB(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return sB(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return sB(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){let e=await this._backing.getMetadataCodecParameterString?.();if(null!=e)return e;let t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{let e=await this._backing.getDecoderConfig();if(!e)return!1;let t=await this._backing.getCodec();if(i(null!==t),aW.some(r=>r.supports(t,e))||e.codec.startsWith("pcm-"))return!0;{if("undefined"==typeof AudioDecoder)return!1;let t=await AudioDecoder.isConfigSupported(e);return!0===t.supported}}catch(e){return eP._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof tG))throw TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}let sR=e=>-(e??-1/0),sD=e=>-e,sO=e=>{if("object"!=typeof e||!e)throw TypeError("query must be an object.");if(void 0!==e.filter&&"function"!=typeof e.filter)throw TypeError("query.filter, when provided, must be a function.");if(void 0!==e.sortBy&&"function"!=typeof e.sortBy)throw TypeError("query.sortBy, when provided, must be a function.");return{filter:e.filter?t=>{let r=e=>{if("boolean"!=typeof e)throw TypeError("query.filter must return or resolve to a boolean.");return e},i=e.filter(t);return i instanceof Promise?i.then(r):r(i)}:void 0,sortBy:e.sortBy?t=>{let r=e=>{if("number"!=typeof e&&(!Array.isArray(e)||!e.every(e=>"number"==typeof e)))throw TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},i=e.sortBy(t);return i instanceof Promise?i.then(r):r(i)}:void 0}},sN=(e,t)=>({filter:e?.filter||t?.filter?r=>{let i=e?.filter?.(r)??!0,a=e=>!1!==e&&(t?.filter?.(r)??!0);return i instanceof Promise?i.then(a):a(i)}:void 0,sortBy:e?.sortBy||t?.sortBy?r=>{let i=e?.sortBy?.(r)??[],a=t?.sortBy?.(r)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return i instanceof Promise||a instanceof Promise?Promise.all([i,a]
1).then(([e,t])=>s(e,t)):s(i,a)}:void 0}),sz=async(e,t)=>{let r=e;if(t?.filter){let i=e.map(e=>t.filter(e));if(i.some(e=>e instanceof Promise)){let t=await Promise.all(i);r=e.filter((e,r)=>t[r])}else r=e.filter((e,t)=>i[t])}if(!t?.sortBy)return r;let i=r.map(e=>t.sortBy(e)),a=i.some(e=>e instanceof Promise)?await Promise.all(i):i;return r.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{let r=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],i=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(r.length,i.length);for(let e=0;e<a;e++){let t=r[e]??0,a=i[e]??0;if(t!==a)return t-a}return 0}).map(e=>e.track)},sU=(e,t)=>{let r=1+1e-9;if(e.length<2)return null;let i=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let r=e[t]-e[t-1];if(!(r>0))return null;i[t-1]=r}let a=i.slice();a.sort();let s=a[Math.floor(.05*a.length)];for(let e=0;e<6;e++){let e=0,t=0;for(let a of i){let i=Math.max(1,Math.round(a/s));Math.abs(a-i*s)>=r||(e+=a,t+=i)}if(0===t)return null;let a=e/t;if(Math.abs(a-s)<=1e-12*Math.max(1,s)){s=a;break}s=a}let n=0,o=0,l=0;for(let e of i){let t=Math.max(1,Math.round(e/s));Math.abs(e-t*s)>=r||(n++,o+=e,l+=t)}if(n/i.length<.98)return null;s=o/l;let c=1/Math.min(l,1e3),u=Math.max(Number.EPSILON,s-c),d=s+c,h=t/d,f=t/u,m=t/s,p=null,g=1/0;for(let e of[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240]){if(e<h||e>f)continue;let t=Math.abs(e/m-1);t<g&&(p=e,g=t)}if(null===p){let e=sL(u,d,1e6),r=sL(h,f,1e6);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))p=r.num/r.den;else{if(!e)return null;p=t*e.den/e.num}}let k=t/p,b=0;for(let e of i){let t=Math.max(1,Math.round(e/k));Math.abs(e-t*k)<r&&b++}return b/i.length<.98?null:p},sL=(e,t,r)=>{for(let i=1;i<=r;i++){let r=Math.floor(e*i)+1;if(r/i<t)return ek({num:r,den:i})}return null},sW=e=>{for(let t of[24/1.001,30/1.001,60/1.001,120/1.001])if(5e-4>=Math.abs(t/e-1))return t;let t=e,r=1/0;for(let i of[12,15,20,24,25,30,48,50,60,100,120,144,240]){let a=Math.abs(i/e-1);a<=.025&&a<r&&(t=i,r=a)}return t};eh();let sq=2;class sV extends ew{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||"object"!=typeof e)throw TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof ap)))throw TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof iW||e.source instanceof iq))throw TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof iW&&e.source._disposed)throw TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof sV))throw TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&aU(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof iW?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){i(this._rootSource instanceof iV);let t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){let r=this._sourceCache.find(r=>r.cacheGroup===t&&iH(r.request,e));if(r)return r.age++,Promise.resolve(r.sourceRef.source.ref());let a=this._sourceCachePromises.find(r=>r.cacheGroup===t&&iH(r.request,e));if(a)return a.promise.then(e=>e.sourceRef.source.ref());let s=(async()=>{let r=await this._getSourceUncached(e);if(ep(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){let e=eg(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);i(-1!==e);let r=this._sourceCache[e];this._sourceCache.splice(e,1),r.sourceRef.free(),B(this._sourceRefs,r.sourceRef)}this._sourceRefs.push(r);let a=this._sourceCachePromises.findIndex(t=>t.request===e);return i(-1!==a),this._sourceCachePromises.splice(a,1),{request:e,sourceRef:r,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:s}),s.then(e=>{let t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??=(async()=>{for(let e of(this._reader=new s$(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0}
1),this._formats))if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this);throw new sH})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),i(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof sH)return!1;throw e}}async getFirstTimestamp(e){let t=(e??=await this.getTracks()).filter(e=>null!==e);if(0===t.length)return 0;let r=Math.min(...(await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0})))).map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){let r=(e??=await this.getTracks()).filter(e=>null!==e);return 0===r.length?0:Math.max(...await Promise.all(r.map(e=>e.computeDuration(t))))}async getDurationFromMetadata(e,t){let r=(e??=await this.getTracks()).filter(e=>null!==e),i=(await Promise.all(r.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===i.length?null:Math.max(...i)}async getTracks(e){return e&&=sO(e),sz((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=sO(e),sz((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=sO(e),sz((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){let t=sN(e&&=sO(e),{sortBy:async e=>[sD((await e.getDisposition()).default),sD(await e.hasPairableAudioTrack()),sD(!await e.hasOnlyKeyPackets()),sR(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=sO(e);let t=await this.getPrimaryVideoTrack(),r=sN(e,{sortBy:async e=>[sD(!t||e.canBePairedWith(t)),sD((await e.getDisposition()).default),sR(await e.getBitrate())]});return(await this.getAudioTracks(r))[0]??null}async _getTrackBackings(){let e=await this._getDemuxer();return this._trackBackingsCache??=await e.getTrackBackings()}_wrapBackingAsTrack(e){let t=this._backingToTrack.get(e);if(t)return t;let r="video"===e.getType()?new sF(this,e):new sM(this,e);return this._backingToTrack.set(e,r),r}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){for(let e of(this._disposed=!0,this._sourceRefs))e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class sH extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}
1class sj extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class s${constructor(e){this.source=e}get fileSize(){let e=this.source._getFileSize();if(void 0===e)throw 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 sj;if(e<0||null!==this.fileSizeNonStrict&&e+t>this.fileSizeNonStrict)return null;if(0===t){let t=new Uint8Array(0);return new sK(t,u(t),0,e,e)}let r=e+t,i=this.source._read(e,r,0,iL);return i instanceof Promise?i.then(t=>t?new sK(t.bytes,t.view,t.offset,e,r):null):i?new sK(i.bytes,i.view,i.offset,e,r):null}requestSliceRange(e,t,r){if(this.source._disposed)throw new sj;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,W(this.fileSizeNonStrict-e,t,r));{let a=this.requestSlice(e,r),s=a=>a||(i(null!==this.fileSizeNonStrict),this.requestSlice(e,W(this.fileSizeNonStrict-e,t,r)));return a instanceof Promise?a.then(s):s(a)}}requestEntireFile(){return null!==this.fileSizeNonStrict?this.requestSlice(0,this.fileSizeNonStrict):(async()=>{let e=[],t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let r=this.requestSliceRange(t,0,1024);if(r instanceof Promise&&(r=await r),!r||0===r.length)break;let i=sG(r,r.length);e.push(i),t+=r.length}let r=new Uint8Array(t),i=0;for(let t of e)r.set(t,i),i+=t.length;return new sK(r,u(r),0,0,t)})()}}class sK{constructor(e,t,r,i,a){this.bytes=e,this.view=t,this.offset=r,this.start=i,this.end=a,this.bufferPos=i-r}static tempFromBytes(e){return new sK(e,u(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 RangeError("Slicing outside of original slice.");return new sK(this.bytes,this.view,this.offset,e,e+t)}}let sX=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},sG=(e,t)=>{sX(e,t);let r=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,r},sQ=e=>(sX(e,1),e.view.getUint8(e.bufferPos++)),sY=(e,t)=>{sX(e,2);let r=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,r},sJ=e=>{sX(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},sZ=e=>{sX(e,3);let t=O(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},s0=e=>{sX(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},s1=(e,t)=>{sX(e,4);let r=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,r},s2=e=>{sX(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},s3=e=>{sX(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},s4=e=>{sX(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},s8=e=>{sX(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t},s6=(e,t)=>{let r,i;return t?(r=s1(e,!0),i=s1(e,!0)):(i=s1(e,!1),r=s1(e,!1)),0x100000000*i+r},s5=e=>0x100000000*s2(e)+s2(e),s7=e=>0x100000000*s4(e)+s2(e),s9=e=>{let t=s3(e);return 0x100000000*s8(e)+t},ne=e=>{sX(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},nt=e=>{sX(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},nr=(e,t)=>{sX(e,t);let r="";for(let i=0;i<t;i++)r+=String.fromCharCode(e.bytes[e.bufferPos++]);return r},ni=(e,t,r)=>d.decode(sG(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!r?.ignore?.(e));!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}(at||(at={})),function(e){e[e.ISO_8859_1=0]="ISO_8859_1",e[e.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",e[e.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",e[e.UTF_8=3]="UTF_8"}(ar||(ar={}));let na=128,ns=10,nn=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","S
1ound 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"],no=(e,t)=>{let r,i=e.filePos;t.raw??={},t.raw.TAG??=sG(e,na-3),e.filePos=i;let a=nl(e,30);a&&(t.title??=a);let s=nl(e,30);s&&(t.artist??=s);let n=nl(e,30);n&&(t.album??=n);let o=Number.parseInt(nl(e,4),10);Number.isInteger(o)&&o>0&&(t.date??=new Date(String(o)));let l=sG(e,30);if(0===l[28]&&0!==l[29]){let i=l[29];i>0&&(t.trackNumber??=i),e.skip(-30),r=nl(e,28),e.skip(2)}else e.skip(-30),r=nl(e,30);r&&(t.comment??=r);let c=sQ(e);c<nn.length&&(t.genre??=nn[c])},nl=(e,t)=>{let r=sG(e,t),i=eo(r.indexOf(0),r.length),a=r.subarray(0,i),s="";for(let e=0;e<a.length;e++)s+=String.fromCharCode(a[e]);return s.trimEnd()},nc=e=>{let t=e.filePos,r=nr(e,3),i=sQ(e),a=sQ(e),s=sQ(e),n=s2(e);if("ID3"!==r||255===i||255===a||(0x80808080&n)!=0)return e.filePos=t,null;let o=ti(n);return s&at.Footer&&(o+=ns),{majorVersion:i,revision:a,flags:s,size:o}},nu=(e,t,r)=>{if(![2,3,4].includes(t.majorVersion))return void eP._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);let i=sG(e,t.flags&at.Footer?t.size-ns:t.size),a=new nd(t,i);if(t.flags&at.Unsynchronisation&&3===t.majorVersion&&a.ununsynchronizeAll(),t.flags&at.ExtendedHeader){let e=a.readU32();3===t.majorVersion?a.pos+=e:a.pos+=e-4}for(;a.pos<=a.bytes.length-a.frameHeaderSize();){let e=a.readId3V2Frame();if(!e)break;let i=a.pos,s=a.pos+e.size,n=!1,o=!1,l=!1;if(3===t.majorVersion?(n=!!(64&e.flags),o=!!(128&e.flags)):4===t.majorVersion&&(n=!!(4&e.flags),o=!!(8&e.flags),l=!!(2&e.flags)||!!(t.flags&at.Unsynchronisation)),n){eP._warn(`Skipping encrypted ID3v2 frame ${e.id}`),a.pos=s;continue}if(o){eP._warn(`Skipping compressed ID3v2 frame ${e.id}`),a.pos=s;continue}if(l&&a.ununsynchronizeRegion(a.pos,s),r.raw??={},"TXXX"===e.id){let e=r.raw.TXXX??={},t=a.readId3V2TextEncoding(),i=a.readId3V2Text(t,s),n=a.readId3V2Text(t,s);e[i]??=n}else"T"===e.id[0]?r.raw[e.id]??=a.readId3V2EncodingAndText(s):r.raw[e.id]??=a.readBytes(e.size);switch(a.pos=i,e.id){case"TIT2":case"TT2":r.title??=a.readId3V2EncodingAndText(s);break;case"TIT3":case"TT3":r.description??=a.readId3V2EncodingAndText(s);break;case"TPE1":case"TP1":r.artist??=a.readId3V2EncodingAndText(s);break;case"TALB":case"TAL":r.album??=a.readId3V2EncodingAndText(s);break;case"TPE2":case"TP2":r.albumArtist??=a.readId3V2EncodingAndText(s);break;case"TRCK":case"TRK":{let e=a.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.tracksTotal??=i)}break;case"TPOS":case"TPA":{let e=a.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(r.discNumber??=t),i&&Number.isInteger(i)&&i>0&&(r.discsTotal??=i)}break;case"TCON":case"TCO":{let e=a.readId3V2EncodingAndText(s),t=/^\((\d+)\)/.exec(e);if(t){let e=Number.parseInt(t[1]);if(void 0!==nn[e]){r.genre??=nn[e];break}}if(t=/^\d+$/.exec(e)){let e=Number.parseInt(t[0]);if(void 0!==nn[e]){r.genre??=nn[e];break}}r.genre??=e}break;case"TDRC":case"TDAT":{let e=new Date(a.readId3V2EncodingAndText(s));Number.isNaN(e.getTime())||(r.date??=e)}break;case"TYER":case"TYE":{let e=Number.parseInt(a.readId3V2EncodingAndText(s),10);Number.isInteger(e)&&(r.date??=new Date(String(e)))}break;case"USLT":case"ULT":{let e=a.readU8();a.pos+=3,a.readId3V2Text(e,s),r.lyrics??=a.readId3V2Text(e,s)}break;case"COMM":case"COM":{let e=a.readU8();a.pos+=3,a.readId3V2Text(e,s),r.comment??=a.readId3V2Text(e,s)}break;case"APIC":case"PIC":{let e,i=a.readId3V2TextEncoding();if(2===t.majorVersion){let t=a.readAscii(3);e="PNG"===t?"image/png":"JPG"===t?"image/jpeg":"image/*"}else e=a.readId3V2Text(i,s);let n=a.readU8(),o=a.readId3V2Text(i,s).trimEnd(),l=s-a.pos;if(l>=0){let t=a.readBytes(l);r.images||(r.images=[]),r.images.push({data:t,mimeType:e,kind:3===n?"coverFront":4===n?"coverBack":"unknown",de
1scription:o})}}break;default:a.pos+=e.size}a.pos=s}};class nd{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){let e=[];for(let t=0;t<this.bytes.length;t++){let r=this.bytes[t];e.push(r),255===r&&t!==this.bytes.length-1&&0===this.bytes[t]&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let r=[];for(let i=e;i<t;i++){let e=this.bytes[i];r.push(e),255===e&&i!==t-1&&0===this.bytes[i+1]&&i++}let i=this.bytes.subarray(0,e),a=this.bytes.subarray(t);this.bytes=new Uint8Array(i.length+r.length+a.length),this.bytes.set(i,0),this.bytes.set(r,i.length),this.bytes.set(a,i.length+r.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){let t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){let e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){let e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){let e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,256*e+t}readU32(){let e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let r=0;r<e;r++)t+=String.fromCharCode(this.view.getUint8(this.pos+r));return this.pos+=e,t}readId3V2Frame(){if(2===this.header.majorVersion){let e=this.readAscii(3);return"\0\0\0"===e?null:{id:e,size:this.readU24(),flags:0}}{let e=this.readAscii(4);if("\0\0\0\0"===e)return null;let t=this.readU32(),r=4===this.header.majorVersion?ti(t):t,i=this.readU16(),a=this.pos,s=e=>{let t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;let t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!s(r)){let e=4===this.header.majorVersion?t:ti(t);s(e)&&(r=e)}return this.pos=a,{id:e,size:r,flags:i}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let r=this.pos,i=this.readBytes(t-this.pos);switch(e){case ar.ISO_8859_1:{let e="";for(let t=0;t<i.length;t++){let a=i[t];if(0===a){this.pos=r+t+1;break}e+=String.fromCharCode(a)}return e}case ar.UTF_16_WITH_BOM:if(255===i[0]&&254===i[1]){let e=new TextDecoder("utf-16le"),t=eo(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}if(254===i[0]&&255===i[1]){let e=new TextDecoder("utf-16be"),t=eo(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(2,t))}{let e=eo(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),d.decode(i.subarray(0,e))}case ar.UTF_16_BE_NO_BOM:{let e=new TextDecoder("utf-16be"),t=eo(i.findIndex((e,t)=>0===e&&0===i[t+1]&&t%2==0),i.length);return this.pos=r+Math.min(t+2,i.length),e.decode(i.subarray(0,t))}case ar.UTF_8:{let e=eo(i.findIndex(e=>0===e),i.length);return this.pos=r+Math.min(e+1,i.length),d.decode(i.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class nh{constructor(e){this.mutex=new S,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,r){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let i=this.trackTimestampInfo.get(e);if(i){if(r&&(i.maxTimestampBeforeLastKeyPacket=i.maxTimestamp),null!==i.maxTimestampBeforeLastKeyPacket&&t<i.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${i.maxTimestampBeforeLastKeyPacket}s.`);i.maxTimestamp=Math.max(i.maxTimestamp,t)}else{if(!r)throw Error("First packet must be a key packet.");i={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,i)}}}let nf=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g,nm=e=>{let t=Math.floor(e/36e5),r=Math.floor(e%36e5/6e4),i=Math.floor(e%6e4/1e3);return t.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+"."+(e%1e3).toString().padStart(3,"0")};
1class np{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/0x100000000),!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{let t=this.writer.getPos();if(this.writeBoxHeader(e,0),e.contents&&this.writer.write(e.contents),e.children)for(let t of e.children)t&&this.writeBox(t);let r=this.writer.getPos(),i=e.size??r-t;this.writer.seek(t),this.writeBoxHeader(e,i),this.writer.seek(r)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+8*!!e.largeSize}patchBox(e){let t=this.offsets.get(e);i(void 0!==t);let 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(let r of e.children)r&&(t+=this.measureBox(r));return t}}}let ng=new Uint8Array(8),nk=new DataView(ng.buffer),nb=e=>[(e%256+256)%256],ny=e=>(nk.setUint16(0,e,!1),[ng[0],ng[1]]),nT=e=>(nk.setInt16(0,e,!1),[ng[0],ng[1]]),nw=e=>(nk.setUint32(0,e,!1),[ng[1],ng[2],ng[3]]),nS=e=>(nk.setUint32(0,e,!1),[ng[0],ng[1],ng[2],ng[3]]),nP=e=>(nk.setInt32(0,e,!1),[ng[0],ng[1],ng[2],ng[3]]),nv=e=>(nk.setUint32(0,Math.floor(e/0x100000000),!1),nk.setUint32(4,e,!1),[ng[0],ng[1],ng[2],ng[3],ng[4],ng[5],ng[6],ng[7]]),nx=e=>(nk.setInt32(0,Math.floor(e/0x100000000),!1),nk.setUint32(4,e,!1),[ng[0],ng[1],ng[2],ng[3],ng[4],ng[5],ng[6],ng[7]]),nC=e=>(nk.setInt16(0,256*e,!1),[ng[0],ng[1]]),nI=e=>(nk.setInt32(0,65536*e,!1),[ng[0],ng[1],ng[2],ng[3]]),nE=e=>(nk.setInt32(0,0x40000000*e,!1),[ng[0],ng[1],ng[2],ng[3]]),n_=(e,t)=>{let r=[],i=e;do{let e=127&i;i>>=7,r.length>0&&(e|=128),r.push(e),void 0!==t&&t--}while(i>0||t);return r.reverse()},nB=(e,t=!1)=>{let r=Array(e.length).fill(null).map((t,r)=>e.charCodeAt(r));return t&&r.push(0),r},nA=e=>{let t=Math.PI/180*e,r=Math.round(Math.cos(t)),i=Math.round(Math.sin(t));return[r,i,0,-i,r,0,0,0,1]},nF=nA(0),nM=e=>[nI(e[0]),nI(e[1]),nE(e[2]),nI(e[3]),nI(e[4]),nE(e[5]),nI(e[6]),nI(e[7]),nE(e[8])],nR=(e,t,r)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:r}),nD=(e,t,r,i,a)=>nR(e,[nb(t),nw(r),i??[]],a),nO=e=>{if(e.isQuickTime)return nR("ftyp",[nB("qt  "),nS(512),nB("qt  ")]);if(e.fragmented)if(e.cmaf)return nR("ftyp",[nB("iso5"),nS(512),nB("iso5"),nB("iso6"),nB("mp41"),nB("cmfc"),nB("dash")]);else return nR("ftyp",[nB("iso5"),nS(512),nB("iso5"),nB("iso6"),nB("mp41")]);return nR("ftyp",[nB("isom"),nS(512),nB("isom"),e.holdsAvc?nB("avc1"):[],nB("mp41")])},nN=()=>nR("styp",[nB("iso5"),nS(0),nB("iso5"),nB("iso6"),nB("mp41"),nB("cmfc"),nB("dash")]),nz=(e,t)=>{let r=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(r)||(r=0),nD("sidx",1,0,[nS(1),nS(oJ),nv(o0(e.minWrittenTimestamp,oJ)),nv(0),ny(0),ny(1),nS(0x7fffffff&t),nS(o0(r,oJ)),nS(0)])},nU=e=>({type:"mdat",largeSize:e}),nL=e=>({type:"free",size:e}),nW=e=>nR("moov",void 0,[nq(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>nH(t,e.creationTime)),e.isFragmented?ok(e.trackDatas):null,oF(e)]),nq=(e,t)=>{let r=Math.max(0,...t.map(e=>o0(nV(e),oJ)+o0(e.startTimestampOffset??0,oJ))),i=Math.max(0,...t.map(e=>e.track.id))+1,a=!n(e)||!n(r),s=a?nv:nS;return nD("mvhd",+a,0,[s(e),s(e),nS(oJ),s(r),nI(1),nC(1),Array(10).fill(0),nM(nF),Array(24).fill(0),nS(i)])},nV=e=>{if(0===e.samples.length)return 0;let t=1/0,r=-1/0;for(let i=0;i<e.samples.length;i++){let a=e.samples[i];a.timestamp<t&&(t=a.timestamp),a.timestamp+a.duration>r&&(r=a.timestamp+a.duration)}return t===1/0?0:r-t},nH=(e,t)=>{let r=oZ(e),i=null!==e.startTimestampOffset&&e.startTimestampOffset>0;return nR("trak",void 0,[nj(e,t),i?n$(e,e.startTimestampOffset):null,nK(e,t),void 0!==r.name?nR("udta",void 0,[nR("name",[...h.encode(r.name)])]):null])},nj=(e,t)=>{let r,i=o0(nV(e),oJ)+o0(e.startTimestampOffset??0,oJ),a=!n(t)||!n(i),s=a?nv:nS;r="video"===e.type?nA(e.track.metadata.rotation??0):nF;let o=2;e.track.metadata.disposition?.default!==!1&&(o|=1);let l="video"===e.type?0:"audio"===e.type?1:"subtitle"===e.type?2:D(e);return nD("tkhd",+a,o,[s(t),s(t),nS(e.track.id),nS(0),s(i),Array(8).fill(0),ny(0),ny(l),nC(+("audio"===e.type)),ny(0),nM(r),nI("video"===e.type?e.info.width:0),nI("video"===e.type?e.info.height:0)])},n$=(e,t)=>
1{let r=o0(t,oJ),i=o0(nV(e),oJ),a=!n(r)||!n(i),s=a?nv:nS,o=a?nx:nP;return nR("edts",void 0,[nD("elst",+!!a,0,[nS(2),s(r),o(-1),nI(1),s(i),o(0),nI(1)])])},nK=(e,t)=>nR("mdia",void 0,[nX(e,t),nY(!0,nG[e.type],nQ[e.type]),nJ(e)]),nX=(e,t)=>{let r=o0(nV(e),e.timescale),i=!n(t)||!n(r),a=i?nv:nS;return nD("mdhd",+i,0,[a(t),a(t),nS(e.timescale),a(r),ny(o$(e.track.metadata.languageCode??"und")),ny(0)])},nG={video:"vide",audio:"soun",subtitle:"text"},nQ={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},nY=(e,t,r,i="\0\0\0\0")=>nD("hdlr",0,0,[e?nB("mhlr"):nS(0),nB(t),nB(i),nS(0),nS(0),nB(r,!0)]),nJ=e=>nR("minf",void 0,[nZ[e.type](),n0(),n3(e)]),nZ={video:()=>nD("vmhd",0,1,[ny(0),ny(0),ny(0),ny(0)]),audio:()=>nD("smhd",0,0,[ny(0),ny(0)]),subtitle:()=>nD("nmhd",0,0)},n0=()=>nR("dinf",void 0,[n1()]),n1=()=>nD("dref",0,0,[nS(1)],[n2()]),n2=()=>nD("url ",0,1),n3=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return nR("stbl",void 0,[n4(e),ou(e),t?op(e):null,t?og(e):null,oh(e),of(e),om(e),od(e)])},n4=e=>{let t;if("video"===e.type)t=n8(oL(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){let r=oq(e.track.source._codec,e.muxer.isQuickTime);i(r),t=n9(r,e)}else"subtitle"===e.type&&(t=oc(oH[e.track.source._codec],e));return i(t),nD("stsd",0,0,[nS(1)],[t])},n8=(e,t)=>nR(e,[Array(6).fill(0),ny(1),ny(0),ny(0),Array(12).fill(0),ny(t.info.width),ny(t.info.height),nS(4718592),nS(4718592),nS(0),ny(1),nb(10),nB("Mediabunny"),Array(21).fill(0),ny(t.info.hasAlphaChannel?32:24),nT(65535)],[oW[t.track.source._codec]?.(t)??null,n6(t),T(t.info.decoderConfig.colorSpace)?n5(t):null]),n6=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:nR("pasp",[nS(e.info.pixelAspectRatio.num),nS(e.info.pixelAspectRatio.den)]),n5=e=>nR("colr",[nB(e.muxer.isQuickTime?"nclc":"nclx"),ny(m[e.info.decoderConfig.colorSpace.primaries]),ny(g[e.info.decoderConfig.colorSpace.transfer]),ny(b[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:nb(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),n7=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,r=t.codec.split("."),i=Number(r[1]),a=Number(r[2]),s=Number(r[3]),n=r[4]?Number(r[4]):1,o=r[8]?Number(r[8]):Number(t.colorSpace?.fullRange??0),l=r[5]?Number(r[5]):t.colorSpace?.primaries?m[t.colorSpace.primaries]:2,c=r[6]?Number(r[6]):t.colorSpace?.transfer?g[t.colorSpace.transfer]:2,u=r[7]?Number(r[7]):t.colorSpace?.matrix?b[t.colorSpace.matrix]:2;return nD("vpcC",1,0,[nb(i),nb(a),nb((s<<4)+(n<<1)+o),nb(l),nb(c),nb(u),ny(0)])},n9=(e,t)=>{let r,i=0,a=16,s=eD.includes(t.track.source._codec);if(s){let{sampleSize:e}=eG(t.track.source._codec);(a=8*e)>16&&(i=1)}return t.muxer.isQuickTime&&(i=1),nR(e,0===i?[Array(6).fill(0),ny(1),ny(i),ny(0),nS(0),ny(t.info.numberOfChannels),ny(a),ny(0),ny(0),ny(t.info.sampleRate<65536?t.info.sampleRate:0),ny(0)]:[Array(6).fill(0),ny(1),ny(i),ny(0),nS(0),ny(t.info.numberOfChannels),ny(Math.min(a,16)),nT(s?0:-2),ny(0),ny(t.info.sampleRate<65536?t.info.sampleRate:0),ny(0),s?[nS(1),nS(a/8),nS(t.info.numberOfChannels*a/8)]:[nS(0),nS(0),nS(0)],nS(2)],[oV(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},oe=e=>{let t;switch(e.track.source._codec){case"aac":t=64;break;case"mp3":t=107;break;case"vorbis":t=221;break;default:throw Error(`Unhandled audio codec: ${e.track.source._codec}`)}let r=[...nb(t),...nb(21),...nw(0),...nS(0),...nS(0)];if(e.info.decoderConfig.description){let t=c(e.info.decoderConfig.description);r=[...r,...nb(5),...n_(t.byteLength),...t]}return r=[...ny(1),...nb(0),...nb(4),...n_(r.length),...r,...nb(6),...nb(1),...nb(2)],nD("esds",0,0,r=[...nb(3),...n_(r.length),...r])},ot=e=>nR("wave",void 0,[or(e),oi(e),nR("\0\0\0\0")]),or=e=>nR("frma",[nB(oq(e.track.source._codec,e.muxer.isQuickTime))]),oi=e=>{let{littleEndian:t}=eG(e.track.source._codec);return nR("enda",[ny(+t)])},oa=e=>{let t=e.info.numberOfChannels,r=3840,a=e.info.sampleRate,s=0,n=0,o=new Uint8Array(0),l=e.info.decoderConfig?.description;if(l){i(l.byteLength>=18);let e=tM(c(l));
1t=e.outputChannelCount,r=e.preSkip,a=e.inputSampleRate,s=e.outputGain,n=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return nR("dOps",[nb(0),nb(t),ny(r),nS(a),nT(s),nb(n),...o])},os=e=>{let t=e.info.decoderConfig?.description;return i(t),nD("dfLa",0,0,[...c(t).subarray(4)])},on=e=>{let{littleEndian:t,sampleSize:r}=eG(e.track.source._codec);return nD("pcmC",0,0,[nb(+t),nb(8*r)])},oo=e=>{i(e.info.primingPacket);let t=tL(e.info.primingPacket.data);if(!t)throw 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).");let r=new Uint8Array(3),a=new e_(r);return a.writeBits(2,t.fscod),a.writeBits(5,t.bsid),a.writeBits(3,t.bsmod),a.writeBits(3,t.acmod),a.writeBits(1,t.lfeon),a.writeBits(5,t.bitRateCode),a.writeBits(5,0),nR("dac3",[...r])},ol=e=>{i(e.info.primingPacket);let t=tV(e.info.primingPacket.data);if(!t)throw 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 r=16;for(let e of t.substreams)r+=23,e.numDepSub>0?r+=9:r+=1;let a=new Uint8Array(Math.ceil(r/8)),s=new e_(a);for(let e of(s.writeBits(13,t.dataRate),s.writeBits(3,t.substreams.length-1),t.substreams))s.writeBits(2,e.fscod),s.writeBits(5,e.bsid),s.writeBits(1,0),s.writeBits(1,0),s.writeBits(3,e.bsmod),s.writeBits(3,e.acmod),s.writeBits(1,e.lfeon),s.writeBits(3,0),s.writeBits(4,e.numDepSub),e.numDepSub>0?s.writeBits(9,e.chanLoc):s.writeBits(1,0);return nR("dec3",[...a])},oc=(e,t)=>nR(e,[Array(6).fill(0),ny(1)],[oj[t.track.source._codec](t)]),ou=e=>nD("stts",0,0,[nS(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[nS(e.sampleCount),nS(e.sampleDelta)])]),od=e=>{if(e.samples.every(e=>"key"===e.type))return null;let t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return nD("stss",0,0,[nS(t.length),t.map(([e])=>nS(e+1))])},oh=e=>nD("stsc",0,0,[nS(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[nS(e.firstChunk),nS(e.samplesPerChunk),nS(1)])]),of=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){let{sampleSize:t}=eG(e.track.source._codec);return nD("stsz",0,0,[nS(t*e.info.numberOfChannels),nS(e.samples.reduce((t,r)=>t+o0(r.duration,e.timescale),0))])}return nD("stsz",0,0,[nS(0),nS(e.samples.length),e.samples.map(e=>nS(e.size))])},om=e=>e.finalizedChunks.length>0&&s(e.finalizedChunks).offset>=0x100000000?nD("co64",0,0,[nS(e.finalizedChunks.length),e.finalizedChunks.map(e=>nv(e.offset))]):nD("stco",0,0,[nS(e.finalizedChunks.length),e.finalizedChunks.map(e=>nS(e.offset))]),op=e=>nD("ctts",1,0,[nS(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[nS(e.sampleCount),nP(e.sampleCompositionTimeOffset)])]),og=e=>{let t=1/0,r=-1/0,a=1/0,s=-1/0;i(e.compositionTimeOffsetTable.length>0),i(e.samples.length>0);for(let i=0;i<e.compositionTimeOffsetTable.length;i++){let a=e.compositionTimeOffsetTable[i];t=Math.min(t,a.sampleCompositionTimeOffset),r=Math.max(r,a.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let r=e.samples[t];a=Math.min(a,o0(r.timestamp,e.timescale)),s=Math.max(s,o0(r.timestamp+r.duration,e.timescale))}let n=Math.max(-t,0);return s>=0x80000000?null:nD("cslg",0,0,[nP(n),nP(t),nP(r),nP(a),nP(s)])},ok=e=>nR("mvex",void 0,e.map(ob)),ob=e=>nD("trex",0,0,[nS(e.track.id),nS(1),nS(0),nS(0),nS(0)]),oy=(e,t)=>nR("moof",void 0,[oT(e),...t.map(oS)]),oT=e=>nD("mfhd",0,0,[nS(e)]),ow=e=>{let t=0,r=0,i="delta"===e.type;return r|=i,i?t|=1:t|=2,t<<24|r<<16},oS=e=>nR("traf",void 0,[oP(e),ov(e),ox(e)]),oP=e=>{i(e.currentChunk);let t=e.currentChunk.samples[1]??e.currentChunk.samples[0],r={duration:t.timescaleUnitsToNextSample,size:t.size,flags:ow(t)};return nD("tfhd",0,131128,[nS(e.track.id),nS(r.duration),nS(r.size),nS(r.flags)])},ov=e=>(i(e.currentChunk),nD("tfdt",1,0,[nv(o0(e.currentChunk.startTimestamp,e.timescale))])),ox=e=>{let t;i(e.currentChunk);let r=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),a=e.currentChunk.samples.map(e=>e.size),s=e.currentChunk.samples.map(ow),n=e.currentChunk.samples.map(t=>o0(t.timestamp-t.decodeTimestamp,e.timescale)),o=new Set(r),l=new Set(a
1),c=new Set(s),u=new Set(n),d=2===c.size&&s[0]!==s[1],h=o.size>1,f=l.size>1,m=!d&&c.size>1,p=u.size>1||[...u].some(e=>0!==e);return nD("trun",1,1|4*d|256*h|512*f|1024*m|2048*p,[nS(e.currentChunk.samples.length),nS(e.currentChunk.offset-e.currentChunk.moofOffset||0),d?nS(s[0]):[],e.currentChunk.samples.map((e,t)=>[h?nS(r[t]):[],f?nS(a[t]):[],m?nS(s[t]):[],p?nP(n[t]):[]])])},oC=e=>nR("mfra",void 0,[...e.map(oI),oE()]),oI=e=>nD("tfra",1,0,[nS(e.track.id),nS(63),nS(e.finalizedChunks.length),e.finalizedChunks.map(t=>[nv(o0(t.samples[0].timestamp,e.timescale)),nv(t.moofOffset),nS(t.trafIndex+1),nS(1),nS(1)])]),oE=()=>nD("mfro",0,0,[nS(0)]),o_=()=>nR("vtte"),oB=(e,t,r,i,a)=>nR("vttc",void 0,[null!==a?nR("vsid",[nP(a)]):null,null!==r?nR("iden",[...h.encode(r)]):null,null!==t?nR("ctim",[...h.encode(nm(t))]):null,null!==i?nR("sttg",[...h.encode(i)]):null,nR("payl",[...h.encode(e)])]),oA=e=>nR("vtta",[...h.encode(e)]),oF=e=>{let t=[],r=e.format._options.metadataFormat??"auto",i=e.output._metadataTags;if("mdir"!==r&&("auto"!==r||e.isQuickTime))if("mdta"===r){let e=oz(i);e&&t.push(e)}else("udta"===r||"auto"===r&&e.isQuickTime)&&oM(t,e.output._metadataTags);else{let e=oN(i);e&&t.push(e)}return 0===t.length?null:nR("udta",void 0,t)},oM=(e,t)=>{for(let{key:r,value:i}of ec(t))switch(r){case"title":e.push(oR("\xa9nam",i));break;case"description":e.push(oR("\xa9des",i));break;case"artist":e.push(oR("\xa9ART",i));break;case"album":e.push(oR("\xa9alb",i));break;case"albumArtist":e.push(oR("albr",i));break;case"genre":e.push(oR("\xa9gen",i));break;case"date":e.push(oR("\xa9day",i.toISOString().slice(0,10)));break;case"comment":e.push(oR("\xa9cmt",i));break;case"lyrics":e.push(oR("\xa9lyr",i));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:D(r)}if(t.raw)for(let r in t.raw){let i=t.raw[r];!(null==i||4!==r.length||e.some(e=>e.type===r))&&("string"==typeof i?e.push(oR(r,i)):i instanceof Uint8Array&&e.push(nR(r,Array.from(i))))}},oR=(e,t)=>{let r=h.encode(t);return nR(e,[ny(r.length),ny(o$("und")),Array.from(r)])},oD={"image/jpeg":13,"image/png":14,"image/bmp":27},oO=(e,t)=>{let r=[];for(let{key:i,value:a}of ec(e))switch(i){case"title":r.push({key:t?"title":"\xa9nam",value:oU(a)});break;case"description":r.push({key:t?"description":"\xa9des",value:oU(a)});break;case"artist":r.push({key:t?"artist":"\xa9ART",value:oU(a)});break;case"album":r.push({key:t?"album":"\xa9alb",value:oU(a)});break;case"albumArtist":r.push({key:t?"album_artist":"aART",value:oU(a)});break;case"comment":r.push({key:t?"comment":"\xa9cmt",value:oU(a)});break;case"genre":r.push({key:t?"genre":"\xa9gen",value:oU(a)});break;case"lyrics":r.push({key:t?"lyrics":"\xa9lyr",value:oU(a)});break;case"date":r.push({key:t?"date":"\xa9day",value:oU(a.toISOString().slice(0,10))});break;case"images":for(let e of a)"coverFront"===e.kind&&r.push({key:"covr",value:nR("data",[nS(oD[e.mimeType]??0),nS(0),Array.from(e.data)])});break;case"trackNumber":if(t){let t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();r.push({key:"track",value:oU(t)})}else r.push({key:"trkn",value:nR("data",[nS(0),nS(0),ny(0),ny(a),ny(e.tracksTotal??0),ny(0)])});break;case"discNumber":t||r.push({key:"disc",value:nR("data",[nS(0),nS(0),ny(0),ny(a),ny(e.discsTotal??0),ny(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:D(i)}if(e.raw)for(let i in e.raw){let a=e.raw[i];!(null==a||!t&&4!==i.length||r.some(e=>e.key===i))&&("string"==typeof a?r.push({key:i,value:oU(a)}):a instanceof Uint8Array?r.push({key:i,value:nR("data",[nS(0),nS(0),Array.from(a)])}):a instanceof ev&&r.push({key:i,value:nR("data",[nS(oD[a.mimeType]??0),nS(0),Array.from(a.data)])}))}return r},oN=e=>{let t=oO(e,!1);return 0===t.length?null:nD("meta",0,0,void 0,[nY(!1,"mdir","","appl"),nR("ilst",void 0,t.map(e=>nR(e.key,void 0,[e.value])))])},oz=e=>{let t=oO(e,!0);return 0===t.length?null:nR("meta",void 0,[nY(!1,"mdta",""),nD("keys",0,0,[nS(t.length)],t.map(e=>nR("mdta",[...h.encode(e.key)]))),nR("ilst",void 0,t.map((e,t)=>nR(String.fromCharCode(...nS(t+1)),void 0,[e.value])))])},oU=e=>nR("data",[nS(1),nS(0),...h.encode(e)]),oL=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";
1case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";case"prores":return t}},oW={avc:e=>e.info.decoderConfig&&nR("avcC",[...c(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&nR("hvcC",[...c(e.info.decoderConfig.description)]),vp8:n7,vp9:n7,av1:e=>nR("av1C",eH(e.info.decoderConfig.codec)),prores:null},oq=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return"mp4a";case"opus":return"Opus";case"flac":return"fLaC";case"ulaw":return"ulaw";case"alaw":return"alaw";case"pcm-u8":return"raw ";case"pcm-s8":return"sowt";case"ac3":return"ac-3";case"eac3":return"ec-3"}if(t)switch(e){case"pcm-s16":return"sowt";case"pcm-s16be":return"twos";case"pcm-s24":case"pcm-s24be":return"in24";case"pcm-s32":case"pcm-s32be":return"in32";case"pcm-f32":case"pcm-f32be":return"fl32";case"pcm-f64":case"pcm-f64be":return"fl64"}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":return"ipcm";case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return"fpcm"}},oV=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return oe;case"opus":return oa;case"flac":return os;case"ac3":return oo;case"eac3":return ol}if(t)switch(e){case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return ot}else switch(e){case"pcm-s16":case"pcm-s16be":case"pcm-s24":case"pcm-s24be":case"pcm-s32":case"pcm-s32be":case"pcm-f32":case"pcm-f32be":case"pcm-f64":case"pcm-f64be":return on}return null},oH={webvtt:"wvtt"},oj={webvtt:e=>nR("vttC",[...h.encode(e.info.config.description)])},o$=e=>{i(3===e.length);let t=0;for(let r=0;r<3;r++)t<<=5,t+=e.charCodeAt(r)-96;return t};class oK{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 Error("Can't have multiple Writers for the same Target.");this.target=e,e._setMonotonicity(t),e._writerAcquired=!0}start(){i(!this.started),this.target._start(),this.started=!0}write(e){i(this.started&&!this.finalized),this.maybeTrackWrites(e),this.target._write(e,this.pos),this.pos+=e.byteLength}seek(e){this.pos=e}getPos(){return this.pos}async flush(){return i(this.started&&!this.finalized),this.target._flush()}async finalize(){i(this.started&&!this.finalized),await this.target._finalize(),this.finalized=!0}maybeTrackWrites(e){if(!this.trackedWrites)return;let t=this.getPos();if(t<this.trackedStart){if(t+e.byteLength<=this.trackedStart)return;e=e.subarray(this.trackedStart-t),t=0}let r=t+e.byteLength-this.trackedStart,i=this.trackedWrites.byteLength;for(;i<r;)i*=2;if(i!==this.trackedWrites.byteLength){let e=new Uint8Array(i);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw Error("Internal error: Can't get tracked writes since nothing was tracked.");let e={data:this.trackedWrites.subarray(0,this.trackedEnd-this.trackedStart),start:this.trackedStart,end:this.trackedEnd};return this.trackedWrites=null,e}}class oX extends ew{constructor(){super(...arguments),this._writerAcquired=!1,this._monotonicity=null,this.onwrite=null}_setMonotonicity(e){!1!==this._monotonicity&&(this._monotonicity=e)}_dispatchWrite(e,t){this.onwrite?.(e,t),this._emit("write",{start:e,end:t})}slice(e){if(!Number.isInteger(e)||e<0)throw TypeError("offset must be a non-negative integer.");return new oQ(this,e)}}class oG extends oX{constructor(e={}){if(super(),this.buffer=null,this._maxPos=0,!e||"object"!=typeof e)throw TypeError("BufferTarget options, when provided, must be an object.");if(void 0!==e.onFinalize&&"function"!=typeof e.onFinalize)throw 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(65536,{maxByteLength:0x100000000})}catch{this._buffer=new ArrayBuffer(65536),this._supportsResize=!1}else this._buffer=new ArrayBuffer(65536);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>0x100000000)throw Error("ArrayBuffer exceeded maximum size of 4294967296 bytes. Please consider using another target.");if(this._supportsResize)this._buffer.resize(t);else{let e=new ArrayBuffer(t),r=new Uint8Array(e);
1r.set(this._bytes,0),this._buffer=e,this._bytes=r}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}}class oQ extends oX{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 oY{constructor(e,t){if(this.rootPath=e,this.getTarget=t,"string"!=typeof e)throw TypeError("rootPath must be a string.");if("function"!=typeof t)throw TypeError("getTarget must be a function.")}}let oJ=57600,oZ=e=>{let t={},r=e.track;return void 0!==r.metadata.name&&(t.name=r.metadata.name),t},o0=(e,t,r=!0)=>{let i=e*t;return r?Math.round(i):i};class o1 extends nh{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new oG,this.auxWriter=new oK(this.auxTarget,!1),this.auxBoxWriter=new np(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=_(),this.creationTime=Math.floor(Date.now()/1e3)+0x7c25b080,this.finalizedChunks=[],this.wroteFragmentedHeader=!1,this.nextFragmentNumber=1,this.maxWrittenTimestamp=-1/0,this.minWrittenTimestamp=1/0,this.maxWrittenEndTimestamp=-1/0,this.segmentHeaderSize=null,this.format=t,this.formatOptions={...t._options},this.isQuickTime=t instanceof ly,this.isCmaf=t instanceof lb,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof lb?1/0:1),this.auxWriter.start()}async start(){let e=await this.mutex.acquire();if(this.isCmaf?(this.fastStart="fragmented",this.isFragmented=!0):(this.writer=await this.output._getRootWriter(e=>void 0!==this.formatOptions.fastStart?"fragmented"===this.formatOptions.fastStart:e instanceof oG),this.boxWriter=new np(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof oG&&"in-memory"),this.isFragmented="fragmented"===this.fastStart),this.isCmaf){if(!this.output._hasInitTarget())throw Error("CMAF outputs require the initTarget field in OutputOptions to be set; the init segment will be written to it.");let e=new oK(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new np(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&"avc"===e.source._codec);{let e=this.initBoxWriter??this.boxWriter;if(i(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox(nO({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:r}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,r)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(let e of this.output.tracks)if(void 0===e.metadata.maximumPacketCount)throw Error("All tracks must specify maximumPacketCount in their metadata when using fastStart: 'reserve'.")}else this.isFragmented||(i(this.writer),i(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=nU(!0),this.boxWriter.writeBox(this.mdat));for(let e of(await this.writer?.flush(),this.output.tracks))e.isVideoTrack()&&e.metadata.decoderConfig?this.getVideoTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig}):e.isAudioTrack()&&e.metadata.decoderConfig&&this.getAudioTrackData(e,e.metadata.primingPacket??null,{decoderConfig:e.metadata.decoderConfig});e()}allTracksAreKnown(){for(let 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;let e=this.trackDatas.map(e=>"video"===e.type||"audio"===e.type?e.info.decoderConfig.codec:({webvtt:"wvtt"})[e.track.source._codec]);return tQ({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,r){let a=this.trackDatas.find(t=>t.track===e);if(a)return a;e3(r,e.source._codec),i(r),i(r.decoderConfig);let s={...r.decoderConfig};i(void 0!==s.codedWidth),i(void 0!==s.codedHeight);let n=!1;if("avc"!==e.source._codec||s.description){if("hevc"===e.source._codec&&!s.description){if(!t)throw Error("No HEVC description provided; you must therefore provide a priming packet.");let e=tw(t.data);if(!e)throw Error("Couldn't extract an HEVCDecoderConfigurationRecord from the HEVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.265) when not providing a description, or provide a description (must be an HEVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in HEVC format.");s.description=t_(e),n=!0}}
1else{if(!t)throw Error("No AVC description provided; you must therefore provide a priming packet.");let e=tf(t.data);if(!e)throw Error("Couldn't extract an AVCDecoderConfigurationRecord from the AVC packet. Make sure the packets are in Annex B format (as specified in ITU-T-REC-H.264) when not providing a description, or provide a description (must be an AVCDecoderConfigurationRecord as specified in ISO 14496-15) and ensure the packets are in AVCC format.");s.description=tm(e),n=!0}let o=Y(1/(e.metadata.frameRate??oJ),1e6).den,l=s.displayAspectWidth,c=s.displayAspectHeight,u=void 0===l||void 0===c?{num:1,den:1}:ek({num:l*s.codedHeight,den:c*s.codedWidth}),d="ap4h"===s.codec||"ap4x"===s.codec,h={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:u,decoderConfig:s,requiresAnnexBTransformation:n,hasAlphaChannel:d},timescale:o,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(h),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),h}getAudioTrackData(e,t,r){let a=this.trackDatas.find(t=>t.track===e);if(a)return a;e8(r,e.source._codec),i(r),i(r.decoderConfig);let s={...r.decoderConfig},n=!1;if("aac"===e.source._codec&&!s.description){if(!t)throw Error("No AAC description provided; you must therefore provide a priming packet.");let e=r5(sK.tempFromBytes(t.data));if(!e)throw 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.");let r=eB[e.samplingFrequencyIndex],i=eA[e.channelConfiguration];if(void 0===r||void 0===i)throw Error("Invalid ADTS frame header.");s.description=eM({objectType:e.objectType,sampleRate:r,numberOfChannels:i}),n=!0}if(("ac3"===e.source._codec||"eac3"===e.source._codec)&&!t)throw Error("AC-3/E-AC-3 require a priming packet.");let o={muxer:this,track:e,type:"audio",info:{numberOfChannels:r.decoderConfig.numberOfChannels,sampleRate:r.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&eD.includes(e.source._codec),expectedNextPcmPacketTimestamp:null,requiresAdtsStripping:n,primingPacket:t},timescale:s.sampleRate,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1};return this.trackDatas.push(o),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}getSubtitleTrackData(e,t){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;e6(t),i(t),i(t.config);let a={muxer:this,track:e,type:"subtitle",info:{config:t.config},timescale:1e3,samples:[],sampleQueue:[],timestampProcessingQueue:[],timeToSampleTable:[],compositionTimeOffsetTable:[],lastTimescaleUnits:null,lastSample:null,startTimestampOffset:null,finalizedChunks:[],currentChunk:null,compactlyCodedChunkTable:[],closed:!1,lastCueEndTimestamp:0,cueQueue:[],nextSourceId:0,cueToSourceId:new WeakMap};return this.trackDatas.push(a),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),a}async addEncodedVideoPacket(e,t,r){let i=await this.mutex.acquire();try{let i=this.getVideoTrackData(e,t,r),a=t.data;if(i.info.requiresAnnexBTransformation){let e=[...to(a)].map(e=>a.subarray(e.offset,e.offset+e.length));if(0===e.length)throw 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=th(e,4)}this.validateTimestamp(i.track,t.timestamp,"key"===t.type);let s=this.createSampleForTrack(i,a,t.timestamp,t.duration,t.type);await this.registerSample(i,s)}finally{i()}}async addEncodedAudioPacket(e,t,r){let i=await this.mutex.acquire();try{let i=this.getAudioTrackData(e,t,r),a=t.data;if(i.info.requiresAdtsStripping){let e=r5(sK.tempFromBytes(a));if(!e)throw Error("Expected ADTS frame, didn't get one.");let t=null===e.crcCheck?7:9;a=a.subarray(t)}this.validateTimestamp(i.track,t.timestamp,"key"===t.type);let s=t.timestamp,n=t.duration;if(i.info.requiresPcmTransformation){let e=eG(i.info.decoderConfig.codec).sampleSize*i.info.numberOfChannels;if(n=a.byteLength/e/i.info.sampleRate,null!==i.info.expectedNextPcmPacketTimestamp){let e=s-i.info.expectedNextPcmPacketTimestamp;if(e<.01)s=i.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(i,i.info.expectedNextPcmPacketTimestamp,e);s=i.info.expectedNextPcmPacketTimestamp+t}}i.info.expectedNextPcmPacketTimestamp=s+n}let o=this.createSampleForTrack(i,a,s,n,t.type);await this.registerSample(i,o)}finally{i()}}async padWithSilence(e,t,r){let i=o0(r,e.timescale);if(r=i/e.timescale,i>0){let{sampleSize:a,silentValue:s}=eG(e.info.decoderConfig.codec),n=new Uint8Array(a*(i*e.info.numberOfChannels)).fill(s),o=this.createSampleForTrack(e,new Uint8Array(n.buffer),t,r,"key");await this.registerSample(e,o)}return r}async addSubtitleCue(e,t,r){let i=await this.mutex.acquire();try{let i=this.getSubtitleTrackData(e,r);this.validateTimestamp(i.track,t.timestamp,!0),"webvtt"===e.source._codec&&(i.cueQueue.push(t),await this.processWebVTTCues(i,t.timestamp))}finally{i()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let r=new Set([]);
1for(let a of e.cueQueue)i(a.timestamp<=t),i(e.lastCueEndTimestamp<=a.timestamp+a.duration),r.add(Math.max(a.timestamp,e.lastCueEndTimestamp)),r.add(a.timestamp+a.duration);let a=[...r].sort((e,t)=>e-t),s=a[0],n=a[1]??s;if(t<n)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let t=o_();this.auxBoxWriter.writeBox(t);let r=this.auxTarget._getSlice(0,this.auxWriter.getPos()),i=this.createSampleForTrack(e,r,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,i),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let r=e.cueQueue[t];if(r.timestamp>=n)break;nf.lastIndex=0;let i=nf.test(r.text),a=r.timestamp+r.duration,o=e.cueToSourceId.get(r);if(void 0===o&&n<a&&(o=e.nextSourceId++,e.cueToSourceId.set(r,o)),r.notes){let e=oA(r.notes);this.auxBoxWriter.writeBox(e)}let l=oB(r.text,i?s:null,r.identifier??null,r.settings??null,o??null);this.auxBoxWriter.writeBox(l),a===n&&e.cueQueue.splice(t--,1)}let o=this.auxTarget._getSlice(0,this.auxWriter.getPos()),l=this.createSampleForTrack(e,o,s,n-s,"key");await this.registerSample(e,l),e.lastCueEndTimestamp=n}}createSampleForTrack(e,t,r,i,a){return{timestamp:r,decodeTimestamp:r,duration:i,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:o0(i,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let r=0;r<e.timestampProcessingQueue.length;r++)t+=o0(e.timestampProcessingQueue[r].duration,e.timescale);if(0===e.timeToSampleTable.length)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let r=s(e.timeToSampleTable);r.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let r=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=r[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let a=e.timestampProcessingQueue[t];a.decodeTimestamp=r[t];let n=o0(a.timestamp-a.decodeTimestamp,e.timescale),o=o0(a.duration,e.timescale);if(null!==e.lastTimescaleUnits){i(e.lastSample);let t=Math.round(o0(a.decodeTimestamp,e.timescale,!1)-e.lastTimescaleUnits);if(i(t>=0),e.lastTimescaleUnits+=t,e.lastSample.timescaleUnitsToNextSample=t,!this.isFragmented){let r=s(e.timeToSampleTable);if(i(r),1===r.sampleCount){r.sampleDelta=t;let i=e.timeToSampleTable[e.timeToSampleTable.length-2];i&&i.sampleDelta===t&&(i.sampleCount++,e.timeToSampleTable.pop(),r=i)}else r.sampleDelta!==t&&(r.sampleCount--,e.timeToSampleTable.push(r={sampleCount:1,sampleDelta:t}));r.sampleDelta===o?r.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let a=s(e.compositionTimeOffsetTable);i(a),a.sampleCompositionTimeOffset===n?a.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n})}}else e.lastTimescaleUnits=o0(a.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:n}));e.lastSample=a}if(e.timestampProcessingQueue.length=0,i(e.lastSample),i(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){i("key"===t.type);let r=Math.round(o0(t.timestamp,e.timescale,!1)-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=r}}async registerSample(e,t){"key"===t.type&&this.processTimestamps(e,t),e.timestampProcessingQueue.push(t),this.isFragmented?(e.sampleQueue.push(t),await this.interleaveSamples()):"reserve"===this.fastStart?await this.registerSampleFastStartReserve(e,t):await this.addSampleToTrack(e,t)}async addSampleToTrack(e,t){if(!this.isFragmented&&(e.samples.push(t),"reserve"===this.fastStart)){let t=e.track.metadata.maximumPacketCount;if(i(void 0!==t),e.samples.length>t)throw Error(`Track #${e.track.id} has already reached the maximum packet count (${t}). Either add less packets or increase the maximum packet count.`)}let r=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);
1let i=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let a=this.trackDatas.every(r=>{if(e===r)return"key"===t.type;let i=r.sampleQueue[0];return i?"key"===i.type:r.closed});i>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(r=!0,await this.finalizeFragment())}else r=i>=.5}else r=!0;r&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),i(e.currentChunk),e.currentChunk.samples.push(t),this.isFragmented&&(this.maxWrittenTimestamp=Math.max(this.maxWrittenTimestamp,t.timestamp),this.maxWrittenEndTimestamp=Math.max(this.maxWrittenEndTimestamp,t.timestamp+t.duration),this.minWrittenTimestamp=Math.min(this.minWrittenTimestamp,t.timestamp))}async finalizeCurrentChunk(e){if(i(!this.isFragmented),i(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,r)=>t+o0(r.duration,e.timescale),0)),(0===e.compactlyCodedChunkTable.length||s(e.compactlyCodedChunkTable).samplesPerChunk!==t)&&e.compactlyCodedChunkTable.push({firstChunk:e.finalizedChunks.length,samplesPerChunk:t}),"in-memory"===this.fastStart){e.currentChunk.offset=0;return}for(let t of(e.currentChunk.offset=this.writer.getPos(),e.currentChunk.samples))i(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(i(this.isFragmented),e||this.allTracksAreKnown())t:for(;;){let t=null,r=1/0;for(let i of this.trackDatas){if(!e&&0===i.sampleQueue.length&&!i.closed)break t;i.sampleQueue.length>0&&i.sampleQueue[0].timestamp<r&&(t=i,r=i.sampleQueue[0].timestamp)}if(!t)break;let i=t.sampleQueue.shift();await this.addSampleToTrack(t,i)}}async finalizeFragment(e=!this.isCmaf){if(i(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;i(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=nW(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:r}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,r)}if(this.isCmaf){i(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new np(this.writer);let e=this.boxWriter.measureBox(nN()),t=this.boxWriter.measureBox(nz(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}i(this.writer),i(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(0===t.length){e&&await this.writer.flush();return}let r=this.nextFragmentNumber++,a=oy(r,t),s=this.writer.getPos(),n=s+this.boxWriter.measureBox(a),o=n+8,l=1/0;for(let e=0;e<t.length;e++){let r=t[e];for(let t of(r.currentChunk.offset=o,r.currentChunk.moofOffset=s,r.currentChunk.trafIndex=e,r.currentChunk.samples))o+=t.size;l=Math.min(l,r.currentChunk.startTimestamp)}let c=o-n,u=c>=0x100000000;if(u)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let d=oy(r,t);if(this.boxWriter.writeBox(d),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,l)}i(this.writer.getPos()===n),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let h=nU(u);for(let e of(h.size=c,this.boxWriter.writeBox(h),this.writer.seek(n+(u?16:8)),t))for(let t of e.currentChunk.samples)this.writer.write(t.data),t.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}for(let e of t)e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk),e.currentChunk=null;e&&await this.writer.flush()}async registerSampleFastStartReserve(e,t){this.allTracksAreKnown()?(this.mdat||await this.createFastStartReserveMdat(),await this.addSampleToTrack(e,t)):e.sampleQueue.push(t)}async createFastStartReserveMdat(){i(this.writer),i(this.boxWriter),this.ensureOneEnabledTrack();let e=nW(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;for(let e of(i(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=nU(!0),this.boxWriter.writeBox(this.mdat),this.trackDatas)){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){i("reserve"===this.fastStart);let e=0;for(let t of this.trackDatas){let r=t.track.metadata.maximumPacketCount;i(void 0!==r),e+=8*Math.ceil(2/3*r)+4*r+8*Math.ceil(2/3*r)+12*Math.ceil(2/3*r)+4*r+8*r}return e}async onTrackClose(e){let t=await this.mutex.acquire(),r=this.trackDatas.find(t=>t.track===e);r&&(r.closed=!0,"subtitle"===r.type&&"webvtt"===e.source._codec&&await this.processWebVTTCues(r,1/0),this.processTimestamps(r)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}ensureOneEnabledTrack(){for(let e of["video","audio","subtitle"]){let t=this.trackDatas.filter(t=>t.type===e);if(0!==t.length&&!t.some(e=>e.track.metadata.disposition?.default!==!1)){let e=t[0];e.track.metadata.disposition={...e.track.metadata.disposition,default:!0}}}}async forceFragmentFinalization(){i(this.isFragmented);let e=await this.mutex.acquire();try{for(let e of this.trackDatas)"subtitle"===e.type&&"webvtt"===e.track.source._codec&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);await this.interleaveSamples(!0),await this.finalizeFragment()}finally{e()}}async finalize(){let e=await this.mutex.acquire();for(let e of(this.allTracksKnown.resolve(),this.ensureOneEnabledTrack(),this.mdat||"reserve"!==this.fastStart||await this.createFastStartReserveMdat(),this.trackDatas))e.closed=!0,"subtitle"===e.type&&"webvtt"===e.track.source._codec&&await this.processWebVTTCues(e,1/0),this.processTimestamps(e);if(this.isFragmented)await this.interleaveSamples(!0),await this.finalizeFragment(!1);else for(let e of this.trackDatas)if(await this.finalizeCurrentChunk(e),null!==e.startTimestampOffset)for(let t=0;t<e.samples.length;t++){let r=e.samples[t];r.timestamp-=e.startTimestampOffset,r.decodeTimestamp-=e.startTimestampOffset}if(i(this.writer),i(this.boxWriter),"in-memory"===this.fastStart){let e;this.mdat=nU(!1);for(let t=0;t<2;t++){let t=nW(this),r=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let a=this.writer.getPos()+r+e;for(let t of this.finalizedChunks)for(let{data:r}of(t.offset=a,t.samples))i(r),a+=r.byteLength,e+=r.byteLength;if(a<0x100000000)break;e>=0x100000000&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=nW(this);if(this.boxWriter.writeBox(t),this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}for(let t of(this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat.size=e,this.boxWriter.writeBox(this.mdat),this.finalizedChunks))for(let e of t.samples)i(e.data),this.writer.write(e.data),e.data=null;if(this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}}else if(this.isFragmented)if(this.isCmaf){let e=null!==this.segmentHeaderSize?this.writer.getPos()-this.segmentHeaderSize:0;this.writer.seek(0),this.boxWriter.writeBox(nN()),this.boxWriter.writeBox(nz(this,e))}else{let e=this.writer.getPos(),t=oC(this.trackDatas);this.boxWriter.writeBox(t);let r=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(r)}else{i(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);i(void 0!==e);let t=this.writer.getPos()-e;if(this.mdat.size=t,this.mdat.largeSize=t>=0x100000000,this.boxWriter.patchBox(this.mdat),this.formatOptions.onMdat){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMdat(e,t)}let r=nW(this);if("reserve"===this.fastStart){i(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox(nL(e))}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(r);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}}new Uint8Array([9,240]),new Uint8Array([70,1]);let o2=new Uint32Array(256);for(let e=0;e<256;e++){let t=e<<24;for(let e=0;e<8;e++)t=0x80000000&t?t<<1^0x4c11db7:t<<1;o2[e]=t>>>0}let o3=new Uint8Array(16);{let e=u(o3);o3[0]=0,e.setUint16(1,45069,!1),e.setUint16(3,1,!1),o3[5]=193,o3[6]=0,o3[7]=0,e.setUint16(8,1,!1),e.setUint16(10,61440,!1),e.setUint32(12,(e=>{let t=0xffffffff;for(let r=0;r<e.length;r++)t=(t<<8^o2[t>>>24^e[r]])>>>0;return t})(o3.subarray(0,12)),!1)}
1let o4=new Map,o8=e=>{if(!e||"object"!=typeof e)throw TypeError("Encoding config must be an object.");if(!eN.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${eN.join(", ")}.`);let t=e.bitrate;if(void 0===e.quality&&void 0===t&&!(eD.includes(e.codec)||"flac"===e.codec))throw TypeError("config.quality must be provided for compressed audio codecs.");if(void 0!==e.quality&&void 0!==t)throw TypeError("config.quality and config.bitrate cannot both be provided.");if(void 0!==e.quality&&!(e.quality instanceof o7))throw TypeError("config.quality, when provided, must be a Quality.");if(void 0!==t&&!(t instanceof o7)&&(!Number.isInteger(t)||t<=0))throw TypeError("config.bitrate, when provided, must be a positive integer or a quality.");if(void 0!==e.transform){if("object"!=typeof e.transform||!e.transform)throw TypeError("config.transform, when provided, must be an object.");if(void 0!==e.transform.numberOfChannels&&(!Number.isInteger(e.transform.numberOfChannels)||e.transform.numberOfChannels<=0))throw TypeError("config.transform.numberOfChannels, when provided, must be a positive integer.");if(void 0!==e.transform.sampleRate&&(!Number.isInteger(e.transform.sampleRate)||e.transform.sampleRate<=0))throw TypeError("config.transform.sampleRate, when provided, must be a positive integer.");if(void 0!==e.transform.sampleFormat&&!["u8","s16","s32","f32"].includes(e.transform.sampleFormat))throw TypeError("config.transform.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(void 0!==e.transform.process&&"function"!=typeof e.transform.process)throw TypeError("config.transform.process, when provided, must be a function.")}if(void 0!==e.onEncodedPacket&&"function"!=typeof e.onEncodedPacket)throw TypeError("config.onEncodedPacket, when provided, must be a function.");if(void 0!==e.onEncoderConfig&&"function"!=typeof e.onEncoderConfig)throw TypeError("config.onEncoderConfig, when provided, must be a function.");if(void 0!==e.onEncodedSample&&"function"!=typeof e.onEncodedSample)throw TypeError("config.onEncodedSample, when provided, must be a function.");o6(e.codec,e)},o6=(e,t)=>{if(!t||"object"!=typeof t)throw TypeError("Encoding options must be an object.");let r=t.bitrateMode;if(void 0!==r&&!["constant","variable"].includes(r))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==t.fullCodecString&&"string"!=typeof t.fullCodecString)throw TypeError("fullCodecString, when provided, must be a string.");if(void 0!==t.fullCodecString&&eQ(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},o5=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??e$(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec),bitrateMode:e.quality?._bitrateMode??t,...eY(e.codec)}};class o7{constructor(e){if(("number"==typeof e||"string"==typeof e)&&(e={quality:e}),!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.bitrateMode&&!["constant","variable"].includes(e.bitrateMode))throw TypeError("options.bitrateMode, when provided, must be 'constant' or 'variable'.");if("quality"in e){if("string"==typeof e.quality?!(e.quality in o9):"number"!=typeof e.quality||Number.isNaN(e.quality))throw TypeError("options.quality must be a number, or one of 'very-low', 'low', 'medium', 'high' or 'very-high'.");if(void 0!==e.preferBitrate&&"boolean"!=typeof e.preferBitrate)throw TypeError("options.preferBitrate, when provided, must be a boolean.");if("bitrate"in e||"quantizer"in e)throw TypeError("options.quality cannot be combined with options.bitrate or options.quantizer.");this._quality="string"==typeof e.quality?o9[e.quality]:e.quality,this._preferBitrate=e.preferBitrate??!1,this._bitrate=void 0,this._quantizer=void 0}else{if(void 0!==e.bitrate&&(!Number.isInteger(e.bitrate)||e.bitrate<=0))throw TypeError("options.bitrate, when provided, must be a positive integer.");if(void 0!==e.quantizer&&(!Number.isInteger(e.quantizer)||e.quantizer<0))throw TypeError("options.quantizer, when provided, must be a non-negative integer.");if(void 0===e.bitrate&&void 0===e.quantizer)throw TypeError("At least one of options.bitrate or options.quantizer must be set.");if("preferBitrate"in e)throw TypeError("options.preferBitrate can only be combined with options.quality.");this._quality=void 0,this._preferBitrate=!1,this._bitrate=e.bitrate,this._quantizer=e.quantizer}this._bitrateMode=e.bitrateMode}_toVideoRateControl(e,t,r,a){let s,n=le[e],o=null,l=this._bitrateMode??a??"variable";if(void 0!==this._quantizer){if(n)if(this._quantizer<n.min||this._quantizer>n.max){if(void 0===this._bitrate)throw Error(`Quantizer ${this._quantizer} is out of range for codec '${e}'; must be between ${n.min} and ${n.max}.`)}else o=this._quantizer,void 0===this._bitrate&&(l="quantizer");else if(void 0===this._bitrate)throw Error(`Codec '${e}' does not support quantizer-based encoding. Provide a bitrate in the Quality to define a fallback.`)}else void 0===this._bitrate&&n&&!this._preferBitrate&&(i(void 0!==this._quality),o=W(Math.round(q(n.worst,n.best,this._quality)),n.min,n.max));if(void 0!==this._bitrate)s=this._bitrate;else{let a=this._quality;void 0===a&&(i(null!==o&&n),a=W((o-n.worst)/(n.best-n.worst),0,1)),s=lr(e,t,r,lt(a))}return{quantizer:o,bitrate:s,bitrateMode:l}}_toVideoBitrate(e,t,r){return void 0!==this._bitrate?this._bitrate:(i(void 0!==this._quality),lr(e,t,r,lt(this._quality)))}_toAudioBitrate(e){if(eD.includes(e)||"flac"===e)return;if(void 0!==this._bitrate)return this._bitrate;if(void 0===this._quality)throw Error("This Quality defines neither a quality level nor a bitrate and therefore cannot be used for audio encoding.");let t=lt(this._quality),r={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3}[e];if(!r)throw Error(`Unhandled codec: ${e}`);let i=r*t;return"aac"===e?i=[96e3,128e3,16e4,192e3].reduce((e,t)=>
1Math.abs(t-i)<Math.abs(e-i)?t:e):"opus"===e||"vorbis"===e?i=Math.max(6e3,i):"mp3"===e&&(i=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-i)<Math.abs(e-i)?t:e)),1e3*Math.round(i/1e3)}}let o9={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},le={avc:{min:0,max:51,worst:41,best:16},hevc:{min:0,max:51,worst:41,best:16},vp9:{min:0,max:63,worst:52,best:20},av1:{min:0,max:255,worst:208,best:80}},lt=e=>.3*Math.exp(2.5538*e),lr=(e,t,r,i)=>1e3*Math.ceil(3e6*Math.pow(t*r/2073600,.95)*({avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:73.33333333333333})[e]*i/1e3),li=async(e,t={})=>{let{numberOfChannels:r=2,sampleRate:i=48e3,quality:a,bitrate:s,...n}=t;if(!eN.includes(e))return!1;if(!Number.isInteger(r)||r<=0)throw TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(i)||i<=0)throw TypeError("sampleRate must be a positive integer.");if(void 0!==a&&!(a instanceof o7))throw TypeError("quality, when provided, must be a Quality.");if(void 0!==a&&void 0!==s)throw TypeError("quality and bitrate cannot both be provided.");if(void 0!==s&&!(s instanceof o7)&&(!Number.isInteger(s)||s<=0))throw TypeError("bitrate must be a positive integer.");o6(e,n);let o=o5({codec:e,numberOfChannels:r,sampleRate:i,quality:la(a,s)??new o7({bitrate:128e3}),...n}),l=JSON.stringify(o),c=o4.get(l);if(c)return c;let u=(async()=>{if(aq.some(t=>t.supports(e,o))||eD.includes(e))return!0;if("undefined"==typeof AudioEncoder)return!1;try{let e=await AudioEncoder.isConfigSupported(o);return!0===e.supported}catch{return!1}})();return o4.set(l,u),u},la=(e,t)=>void 0!==e?e:void 0!==t?t instanceof o7?t:new o7({bitrate:t}):void 0,ls=async(e,t)=>{for(let r of e)if(await li(r,t))return r;return null};class ln{constructor(e){this.sourceSampleRate=null,this.sourceNumberOfChannels=null,this.startTime=null,this.bufferStartFrame=0,this.maxWrittenFrame=null,this.targetSampleRate=e.targetSampleRate,this.targetNumberOfChannels=e.targetNumberOfChannels,this.onSample=e.onSample,this.bufferSizeInFrames=Math.floor(5*this.targetSampleRate),this.bufferSizeInSamples=this.bufferSizeInFrames*this.targetNumberOfChannels,this.outputBuffer=new Float32Array(this.bufferSizeInSamples)}doChannelMixerSetup(){i(null!==this.sourceNumberOfChannels);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;1===e&&2===t?this.channelMixer=(t,r)=>t[r*e]:1===e&&4===t?this.channelMixer=(t,r,i)=>t[r*e]*(i<2):1===e&&6===t?this.channelMixer=(t,r,i)=>t[r*e]*(2===i):2===e&&1===t?this.channelMixer=(t,r)=>{let i=r*e;return .5*(t[i]+t[i+1])}:2===e&&4===t?this.channelMixer=(t,r,i)=>t[r*e+i]*(i<2):2===e&&6===t?this.channelMixer=(t,r,i)=>t[r*e+i]*(i<2):4===e&&1===t?this.channelMixer=(t,r)=>{let i=r*e;return .25*(t[i]+t[i+1]+t[i+2]+t[i+3])}:4===e&&2===t?this.channelMixer=(t,r,i)=>{let a=r*e;return .5*(t[a+i]+t[a+i+2])}:4===e&&6===t?this.channelMixer=(t,r,i)=>{let a=r*e;return i<2?t[a+i]:2===i||3===i?0:t[a+i-2]}:6===e&&1===t?this.channelMixer=(t,r)=>{let i=r*e;return Math.SQRT1_2*(t[i]+t[i+1])+t[i+2]+.5*(t[i+4]+t[i+5])}:6===e&&2===t?this.channelMixer=(t,r,i)=>{let a=r*e;return t[a+i]+Math.SQRT1_2*(t[a+2]+t[a+i+4])}:6===e&&4===t?this.channelMixer=(t,r,i)=>{let a=r*e;return i<2?t[a+i]+Math.SQRT1_2*t[a+2]:t[a+i+2]}:this.channelMixer=(t,r,i)=>i<e?t[r*e+i]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){let e=new Float32Array(t);e.set(this.tempSourceBuffer),this.tempSourceBuffer=e}}async add(e){null===this.sourceSampleRate&&(this.sourceSampleRate=e.sampleRate,this.sourceNumberOfChannels=e.numberOfChannels,this.startTime=e.timestamp,this.tempSourceBuffer=new Float32Array(this.sourceSampleRate*this.sourceNumberOfChannels),this.doChannelMixerSetup()),i(null!==this.startTime);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let r=e.allocationSize({planeIndex:0,format:"f32"}),a=new Float32Array(this.tempSourceBuffer.buffer,0,r/4);e.copyTo(a,{planeIndex:0,format:"f32"});let s=e.timestamp-this.startTime,n=s+e.duration,o=Math.floor((s-1/this.sourceSampleRate)*this.targetSampleRate)+1,l=Math.ceil(n*this.targetSampleRate);for(let t=o;t<l;t++){if(t<this.bufferStartFrame)continue;for(;t>=this.bufferStartFrame+this.bufferSizeInFrames;)await this.finalizeCurrentBuffer(),this.bufferStartFrame+=this.bufferSizeInFrames;let r=t-this.bufferStartFrame;i(r<this.bufferSizeInFrames);let n=(t/this.targetSampleRate-s)*this.sourceSampleRate,o=Math.floor(n),l=Math.ceil(n),c=n-o;for(let t=0;t<this.targetNumberOfChannels;t++){let i=0,s=0;o>=0&&o<e.numberOfFrames&&(i=this.channelMixer(a,o,t)),l>=0&&l<e.numberOfFrames&&(s=this.channelMixer(a,l,t));let n=i+c*(s-i),u=r*this.targetNumberOfChannels+t;this.outputBuffer[u]+=n}null===this.maxWrittenFrame?this.maxWrittenFrame=r:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,r)}}async finalizeCurrentBuffer(){if(null===this.maxWrittenFrame)return;i(null!==this.startTime);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let r=new sc({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(r),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}"function"==typeof SuppressedError&&SuppressedError;class lo{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!1}
1_ensureValidAdd(){if(!this._connectedTrack)throw Error("Source is not connected to an output track.");if("canceled"===this._connectedTrack.output.state)throw Error("Output has been canceled.");if("finalizing"===this._connectedTrack.output.state||"finalized"===this._connectedTrack.output.state)throw Error("Output has been finalized.");if("pending"===this._connectedTrack.output.state)throw Error("Output has not started.");if(this._closed)throw Error("Source is closed.")}async _start(){}async _flushAndClose(e){}close(){if(this._closingPromise)return;let e=this._connectedTrack;if(!e)throw Error("Cannot call close without connecting the source to an output track.");if("pending"===e.output.state)throw Error("Cannot call close before output has been started.");this._closingPromise=(async()=>{await this._flushAndClose(!1),this._closed=!0,"finalizing"!==e.output.state&&"finalized"!==e.output.state&&e.output._muxer.onTrackClose(e)})()}async _flushOrWaitForOngoingClose(e){return this._closingPromise??=(async()=>{await this._flushAndClose(e),this._closed=!0})()}}class ll extends lo{constructor(e){if(super(),this._connectedTrack=null,!eR.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${eR.join(", ")}.`);this._codec=e}}let lc=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&"key"!==t.type)throw Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class lu extends ll{constructor(e){super(e)}add(e,t){if(!(e instanceof tG))throw TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw TypeError("Metadata-only packets cannot be added.");if(void 0!==t&&(!t||"object"!=typeof t))throw TypeError("meta, when provided, must be an object.");return this._ensureValidAdd(),lc(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class ld extends lo{constructor(e){if(super(),this._connectedTrack=null,!eN.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${eN.join(", ")}.`);this._codec=e}}class lh{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastNumberOfChannels=null,this.lastSampleRate=null,this.isPcmEncoder=!1,this.outputSampleSize=null,this.writeOutputValue=null,this.customEncoder=null,this.customEncoderCallSerializer=new J,this.customEncoderQueueSize=0,this.lastEndSampleIndex=null,this.resampler=null,this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t){try{if(this.checkForEncoderError(),this.source._ensureValidAdd(),null!==this.lastNumberOfChannels&&null!==this.lastSampleRate){if(e.numberOfChannels!==this.lastNumberOfChannels||e.sampleRate!==this.lastSampleRate)throw 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;let r=this.encodingConfig;r.transform?.numberOfChannels!==void 0||r.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new ln({targetNumberOfChannels:r.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:r.transform.sampleRate??e.sampleRate,onSample:async e=>{await this.processAndEncode(e,!0)}})),await this.resampler.add(e)):await this.processAndEncode(e,t)}finally{t&&e.close()}}async processAndEncode(e,t){let r=this.encodingConfig;if(r.transform?.sampleFormat!==void 0&&sp(e.format)!==r.transform.sampleFormat){let i=sk(e,r.transform.sampleFormat);t&&e.close(),e=i,t=!0}if(r.transform?.process)try{let t=r.transform.process(e);if(t instanceof Promise&&(t=await t),null===t)return;Array.isArray(t)||(t=[t]);try{for(let e of t)if(!(e instanceof sc))throw TypeError("The audio process function must return an AudioSample, null, or an array of AudioSamples.");for(let e of t)await this.encodeSample(e,!0)}finally{for(let e of t)e instanceof sc&&e.close()}}finally{t&&e.close()}else await this.encodeSample(e,t)}async encodeSample(e,t){try{if(!this.encoderInitialized&&(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),i(this.encoderInitialized),this.closed)return;
1{let t=Math.round(e.timestamp*e.sampleRate),r=Math.round((e.timestamp+e.duration)*e.sampleRate);if(null===this.lastEndSampleIndex)this.lastEndSampleIndex=r;else{let r=t-this.lastEndSampleIndex;if(r>=64){let t=new sc({data:new Float32Array(r*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:r,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),r=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await r,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{i(this.encoder);let r=e.toAudioData();this.encoder.encode(r),r.close(),t&&e.close(),this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener("dequeue",e,{once:!0})),await this.lastMuxerPromise}}finally{t&&e.close()}}async doPcmEncoding(e,t){i(this.outputSampleSize),i(this.writeOutputValue);let{numberOfChannels:r,numberOfFrames:a,sampleRate:s,timestamp:n}=e,o=[];for(let t=0;t<a;t+=2048){let i=Math.min(2048,e.numberOfFrames-t),a=new DataView(new ArrayBuffer(i*r*this.outputSampleSize));o.push({frameCount:i,view:a})}let l=new Float32Array(e.allocationSize({planeIndex:0,format:"f32-planar"})/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<r;t++){e.copyTo(l,{planeIndex:t,format:"f32-planar"});for(let e=0;e<o.length;e++){let{frameCount:i,view:a}=o[e];for(let s=0;s<i;s++)this.writeOutputValue(a,(s*r+t)*this.outputSampleSize,l[2048*e+s])}}t&&e.close();let c={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:r,sampleRate:s}};for(let e=0;e<o.length;e++){let{frameCount:t,view:r}=o[e],i=r.buffer,a=2048*e,l=new tG(new Uint8Array(i),"key",n+a/s,t/s);this.encodingConfig.onEncodedPacket?.(l,c),await this.muxer.addEncodedAudioPacket(this.source._connectedTrack,l,c)}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let{numberOfChannels:t,sampleRate:r}=e,a=la(this.encodingConfig.quality,this.encodingConfig.bitrate),n=o5({numberOfChannels:t,sampleRate:r,...this.encodingConfig,quality:a});this.encodingConfig.onEncoderConfig?.(n);let o=aq.find(e=>e.supports(this.encodingConfig.codec,n));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof tG))throw TypeError("The first argument passed to onPacket must be an EncodedPacket.");if(void 0!==t&&(!t||"object"!=typeof t))throw TypeError("The second argument passed to onPacket must be an object or undefined.");this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else if(eD.includes(this.encodingConfig.codec))this.initPcmEncoder();else{let e;if("undefined"==typeof AudioEncoder)throw Error("AudioEncoder is not supported by this browser.");try{e=(await AudioEncoder.isConfigSupported(n)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${n.codec}, ${n.bitrate} bps, ${n.numberOfChannels} channels, ${n.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let t=Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(e,t)=>{if("aac"===this.encodingConfig.codec&&t?.decoderConfig){let e=!1;if(!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||0===eF(c(t.decoderConfig.description)).objectType){let e=Number(s(n.codec.split(".")));t.decoderConfig.description=eM({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}}let r=tG.fromEncodedChunk(e);r=r.clone({timestamp:j(r.timestamp,n.sampleRate),duration:null!=e.duration?j(r.duration,n.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(r,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,r,t).catch(e=>{this.setError(e)})},error:e=>{e.stack=t,this.setError(e)}}),this.encoder.configure(n)}i(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let{dataType:e,sampleSize:t,littleEndian:r}=eG(this.encodingConfig.codec);switch(this.outputSampleSize=t,t){case 1:"unsigned"===e?this.writeOutputValue=(e,t,r)=>e.setUint8(t,W((r+1)*127.5,0,255)):"signed"===e?this.writeOutputValue=(e,t,r)=>{e.setInt8(t,W(Math.round(128*r),-128,127))}:"ulaw"===e?this.writeOutputValue=(e,t,r)=>{let i=W(Math.floor(32767*r),-32768,32767);e.setUint8(t,aV(i))}:"alaw"===e?this.writeOutputValue=(e,t,r)=>{let i=W(Math.floor(32767*r),-32768,32767);e.setUint8(t,aj(i))}:i(!1);break;case 2:"unsigned"===e?this.writeOutputValue=(e,t,i)=>e.setUint16(t,W((i+1)*32767.5,0,65535),r):"signed"===e?this.writeOutputValue=(e,t,i)=>e.setInt16(t,W(Math.round(32767*i),-32768,32767),r):i(!1);break;case 3:"unsigned"===e?this.writeOutputValue=(e,t,i)=>z(e,t,W((i+1)*8388607.5,0,0xffffff),r):"signed"===e?this.writeOutputValue=(e,t,i)=>U(e,t,W(Math.round(8388607*i),-8388608,8388607),r):i(!1);break;case 4:"unsigned"===e?this.writeOutputValue=(e,t,i)=>e.setUint32(t,W((i+1)*2147483647.5,0,0xffffffff),r):"signed"===e?this.writeOutputValue=(e,t,i)=>e.setInt32(t,W(Math.round(0x7fffffff*i),-0x80000000,0x7fffffff),r):"float"===e?this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,r):i(!1);break;case 8:"float"===e?this.writeOutputValue=(e,t,i)=>e.setFloat64(t,i,r):i(!1);break;default:D(t),i(!1)}}async flushAndClose(e){try{!e&&(this.checkForEncoderError(),this.resampler&&await this.resampler.finalize()),this.closed=!0,!e&&(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&await this.encoder.flush())}finally{this.closed=!0,this.resampler=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&"closed"!==this.encoder.state&&this.encoder.close()}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.isPcmEncoder?0:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}class lf extends ld{constructor(e){o8(e),super(e.codec),this._accumulatedTime=0,this._encoder=new lh(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let t=sc._fromAudioBuffer(e,this._accumulatedTime);for(let r of(this._accumulatedTime+=e.duration,t))await this._encoder.add(r,!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class lm extends lo{constructor(e){if(super(),this._connectedTrack=null,!ez.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${ez.join(", ")}.`);this._codec=e}}
1class lp{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>eR.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>eN.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>ez.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class lg extends lp{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.fastStart&&![!1,"in-memory","reserve","fragmented"].includes(e.fastStart))throw TypeError("options.fastStart, when provided, must be false, 'in-memory', 'reserve', or 'fragmented'.");if(void 0!==e.minimumFragmentDuration&&(!Number.isFinite(e.minimumFragmentDuration)||e.minimumFragmentDuration<0))throw TypeError("options.minimumFragmentDuration, when provided, must be a non-negative number.");if(void 0!==e.onFtyp&&"function"!=typeof e.onFtyp)throw TypeError("options.onFtyp, when provided, must be a function.");if(void 0!==e.onMoov&&"function"!=typeof e.onMoov)throw TypeError("options.onMoov, when provided, must be a function.");if(void 0!==e.onMdat&&"function"!=typeof e.onMdat)throw TypeError("options.onMdat, when provided, must be a function.");if(void 0!==e.onMoof&&"function"!=typeof e.onMoof)throw TypeError("options.onMoof, when provided, must be a function.");if(void 0!==e.metadataFormat&&!["mdir","mdta","udta","auto"].includes(e.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'auto', 'mdir', 'mdta', or 'udta'.");super(),this._options=e}getSupportedTrackCounts(){return{video:{min:0,max:0x100000000-1},audio:{min:0,max:0x100000000-1},subtitle:{min:0,max:0x100000000-1},total:{min:0,max:0x100000000-1}}}get supportsVideoRotationMetadata(){return!0}get supportsTimestampedMediaData(){return!0}_createMuxer(e){return new o1(e,this)}_isFragmentedIsobmff(){return"fragmented"===this._options.fastStart}}class lk extends lg{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...eR,...eO,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ez]}_codecUnsupportedHint(e){return new ly().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class lb extends lg{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...eR,...eO,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...ez]}}class ly extends lg{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...eR,...eN]}_codecUnsupportedHint(e){return new lk().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}let lT=["video","audio","subtitle"];class lw{constructor(e,t,r,i,a){this.id=e,this.output=t,this.type=r,this.source=i,this.metadata=a}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(e){if(!(e instanceof lw))throw TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=eT(this.metadata.group),r=eT(e.metadata.group);for(let i of t)if(this.type!==e.type&&r.some(e=>i===e)||r.some(e=>i._pairedGroups.has(e)))return!0;return!1}}
1class lS extends lw{constructor(e,t,r,i){super(e,t,"video",r,i)}}class lP extends lw{constructor(e,t,r,i){super(e,t,"audio",r,i)}}class lv extends lw{constructor(e,t,r,i){super(e,t,"subtitle",r,i)}}class lx{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof lx))throw TypeError("other must be an OutputTrackGroup.");if(this===e)throw TypeError("Cannot pair a group with itself.");this._pairedGroups.add(e),e._pairedGroups.add(this)}}let lC=e=>{if(!e||"object"!=typeof e)throw TypeError("metadata must be an object.");if(void 0!==e.languageCode&&!G(e.languageCode))throw TypeError("metadata.languageCode, when provided, must be a three-letter, ISO 639-2/T language code.");if(void 0!==e.name&&"string"!=typeof e.name)throw TypeError("metadata.name, when provided, must be a string.");if(void 0!==e.disposition&&eE(e.disposition),void 0!==e.maximumPacketCount&&(!Number.isInteger(e.maximumPacketCount)||e.maximumPacketCount<0))throw TypeError("metadata.maximumPacketCount, when provided, must be a non-negative integer.");if(void 0!==e.group&&!(e.group instanceof lx)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof lx))))throw TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class lI extends ew{get target(){let e="Output.target cannot be used when using PathedTarget with an async callback. Use the 'target' event instead.";if(this._rootTargetPromise)throw TypeError(e);let t=this._getRootTarget();if(t instanceof Promise)throw TypeError(e);return t}constructor(e){if(super(),this.state="pending",this.defaultTrackGroup=new lx,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new S,this._metadataTags={},this._rootTarget=null,this._rootTargetPromise=null,this._firstMediaStreamTimestamp=null,!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!(e.format instanceof lp))throw TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof oX||e.target instanceof oY))throw TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof oX&&this._rememberTarget(e.target),void 0!==e.initTarget&&!(e.initTarget instanceof oX)&&"function"!=typeof e.initTarget)throw Error("options.initTarget, when provided, must be a Target or a function that returns or resolves to a Target.");if(void 0!==e.onFinalize&&"function"!=typeof e.onFinalize)throw 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 oX&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){i(this._target instanceof oY);let t=this._target.getTarget(e),r=e=>{if(!(e instanceof oX))throw TypeError("getTarget must return a Target.");return e};return t instanceof Promise?t.then(r):r(t)}async _getTarget(e){i(this._target instanceof oY);let t=await this._getTargetValidated(e);return this._emit("target",{target:t,request:e,isRoot:e.isRoot}),"canceled"===this.state?await t._close():this._rememberTarget(t),t}_rememberTarget(e){this._unfinalizedTargets.add(e),e.on("finalized",()=>this._unfinalizedTargets.delete(e),{once:!0})}async _getInitTarget(){if(i(null!==this._initTarget),this._initTarget instanceof oX)return this._initTarget;let e=await this._initTarget();return"canceled"===this.state?await e._close():this._rememberTarget(e),e}_hasInitTarget(){return null!==this._initTarget}_getRootTarget(){if(this._rootTarget)return this._rootTarget;if(this._rootTargetPromise)return this._rootTargetPromise;if(this._target instanceof oX)return this._emit("target",{target:this._target,request:null,isRoot:!0}),this._rootTarget=this._target,this._target;let e={path:this._target.rootPath,isRoot:!0,mimeType:this.format.mimeType},t=this._getTargetValidated(e),r=t=>("canceled"===this.state?t._close():this._rememberTarget(t),this._emit("target",{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(r):r(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),r=new oK(t,"boolean"==typeof e?e:e(t));return r.start(),r})()}addVideoTrack(e,t={}){if(!(e instanceof ll))throw TypeError("source must be a VideoSource.");if(lC(t),void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError(`Invalid video rotation: ${t.rotation}. Has to be 0, 90, 180 or 270.`);if(!this.format.supportsVideoRotationMetadata&&t.rotation)throw Error(`${this.format._name} does not support video rotation metadata.`);if(void 0!==t.frameRate&&(!Number.isFinite(t.frameRate)||t.frameRate<=0))throw TypeError(`Invalid video frame rate: ${t.frameRate}. Must be a positive number.`);if(void 0!==t.decoderConfig&&e3({decoderConfig:t.decoderConfig},e._codec),void 0!==t.primingPacket){if(!(t.primingPacket instanceof tG))throw TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(void 0===t.decoderConfig)throw TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let r={...t};return r.group??=this.defaultTrackGroup,this._addTrack(new lS(this.tracks.length+1,this,e,r))}addAudioTrack(e,t={}){if(!(e instanceof ld))throw TypeError("source must be an AudioSource.");if(lC(t),void 0!==t.decoderConfig&&e8({decoderConfig:t.decoderConfig},e._codec),void 0!==t.primingPacket){if(!(t.primingPacket instanceof tG))throw TypeError("metadata.primingPacket, when provided, must be an EncodedPacket.");if(void 0===t.decoderConfig)throw TypeError("metadata.primingPacket can only be provided alongside metadata.decoderConfig.")}let r={...t};return r.group??=this.defaultTrackGroup,this._addTrack(new lP(this.tracks.length+1,this,e,r))}addSubtitleTrack(e,t={}){if(!(e instanceof lm))throw TypeError("source must be a SubtitleSource.");lC(t);let r={...t};return r.group??=this.defaultTrackGroup,this._addTrack(new lv(this.tracks.length+1,this,e,r))}setMetadataTags(e){if(eC(e),"pending"!==this.state)throw Error("Cannot set metadata tags after output has been started or canceled.");this._metadataTags=e}_addTrack(e){if("pending"!==this.state)throw Error("Cannot add track after output has been started or canceled.");
1if(e.source._connectedTrack)throw Error("Source is already used for a track.");let t=this.format.getSupportedTrackCounts(),r=this.tracks.reduce((t,r)=>t+ +(r.type===e.type),0),i=t[e.type].max;if(r===i)throw Error(0===i?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${i} ${e.type} track${1===i?"":"s"}.`);let a=t.total.max;if(this.tracks.length===a)throw Error(`${this.format._name} does not support more than ${a} tracks${1===a?"":"s"} in total.`);if(e.isVideoTrack()){let t=this.format.getSupportedVideoCodecs();if(0===t.length)throw Error(`${this.format._name} does not support video tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported video codecs are: ${t.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isAudioTrack()){let t=this.format.getSupportedAudioCodecs();if(0===t.length)throw Error(`${this.format._name} does not support audio tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported audio codecs are: ${t.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}else if(e.isSubtitleTrack()){let t=this.format.getSupportedSubtitleCodecs();if(0===t.length)throw Error(`${this.format._name} does not support subtitle tracks.`+this.format._codecUnsupportedHint(e.source._codec));if(!t.includes(e.source._codec))throw Error(`Codec '${e.source._codec}' cannot be contained within ${this.format._name}. Supported subtitle codecs are: ${t.map(e=>`'${e}'`).join(", ")}.`+this.format._codecUnsupportedHint(e.source._codec))}return this.tracks.push(e),e.source._connectedTrack=e,e}hasEnoughTracks(){let e=this.format.getSupportedTrackCounts();for(let t of lT)if(this.tracks.reduce((e,r)=>e+ +(r.type===t),0)<e[t].min)return!1;let t=e.total.min;return!(this.tracks.length<t)}async start(){let e=this.format.getSupportedTrackCounts();for(let t of lT){let r=this.tracks.reduce((e,r)=>e+ +(r.type===t),0),i=e[t].min;if(r<i)throw Error(i===e[t].max?`${this.format._name} requires exactly ${i} ${t} track${1===i?"":"s"}.`:`${this.format._name} requires at least ${i} ${t} track${1===i?"":"s"}.`)}let t=e.total.min;if(this.tracks.length<t)throw Error(t===e.total.max?`${this.format._name} requires exactly ${t} track${1===t?"":"s"}.`:`${this.format._name} requires at least ${t} track${1===t?"":"s"}.`);if("canceled"===this.state)throw Error("Output has been canceled.");return this._startPromise?(eP._warn("Output has already been started."),this._startPromise):this._startPromise=(async()=>{this.state="started";let e=this._mutex.acquire();try{await this._muxer.start();let e=this.tracks.map(e=>e.source._start());await Promise.all(e)}finally{(await e)()}})()}getMimeType(){return this._muxer.getMimeType()}async cancel(){if(this._cancelPromise)return eP._warn("Output has already been canceled."),this._cancelPromise;if("finalizing"===this.state||"finalized"===this.state){"finalized"===this.state&&eP._warn("Output has already been finalized.");return}return this._cancelPromise=(async()=>{this.state="canceled";let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!0));await Promise.all(e),await Promise.all([...this._unfinalizedTargets].map(e=>e._close())),this._unfinalizedTargets.clear()}finally{e()}})()}async finalize(){if("pending"===this.state)throw Error("Cannot finalize before starting.");if("canceled"===this.state)throw Error("Cannot finalize after canceling.");return this._finalizePromise?(eP._warn("Output has already been finalized."),this._finalizePromise):this._finalizePromise=(async()=>{this.state="finalizing";let e=await this._mutex.acquire();try{let e=this.tracks.map(e=>e.source._flushOrWaitForOngoingClose(!1));if(await Promise.all(e),await this._muxer.finalize(),this._rootWriterPromise){let e=await this._rootWriterPromise;e.finalized||(await e.flush(),await e.finalize())}this._onFinalize&&await this._onFinalize(),this.state="finalized"}finally{await Promise.all([...this._unfinalizedTargets].map(e=>e._close().catch(()=>{}))),this._unfinalizedTargets.clear(),e()}})()}}let lE=Symbol.for("mediabunny loaded");globalThis[lE]&&eP._error("[WARNING]\nMediabunny was loaded twice. This will likely cause Mediabunny not to work correctly. Check if multiple dependencies are importing different versions of Mediabunny, or if something is being bundled incorrectly."),globalThis[lE]=!0}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.