PageSourceSearch

https://www.mugen-mojiokoshi.com/_next/static/chunks/2971.9910e6f5df13baee.js

js mugen-mojiokoshi.com collected 2026-10-02 00:53:22 UTC 663,870 bytes, 17 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2971],{2971:(e,t,i)=>{let r;function a(e){if(!e)throw Error("Assertion failed.")}i.r(t),i.d(t,{ADTS:()=>sy,ALL_FORMATS:()=>sS,ALL_TRACK_TYPES:()=>dR,AUDIO_CODECS:()=>eG,AdtsInputFormat:()=>sl,AdtsOutputFormat:()=>dI,AppendOnlyStreamTarget:()=>cC,AttachedFile:()=>ez,AudioBufferSink:()=>n6,AudioBufferSource:()=>da,AudioSample:()=>s8,AudioSampleResource:()=>s4,AudioSampleSink:()=>n8,AudioSampleSource:()=>dr,AudioSource:()=>de,BaseMediaSampleSink:()=>nK,BlobSource:()=>aO,BufferSource:()=>az,BufferTarget:()=>cv,CanvasSink:()=>n2,CanvasSource:()=>c7,CmafOutputFormat:()=>dA,ConcurrentRunner:()=>eF,Conversion:()=>dQ,ConversionCanceledError:()=>d$,CustomAudioDecoder:()=>nR,CustomAudioEncoder:()=>nz,CustomPathedSource:()=>aD,CustomSource:()=>aH,CustomVideoDecoder:()=>nM,CustomVideoEncoder:()=>nD,EncodedAudioPacketSource:()=>dt,EncodedPacket:()=>ik,EncodedPacketSink:()=>nQ,EncodedVideoPacketSource:()=>c2,EventEmitter:()=>eI,FLAC:()=>sw,FilePathSource:()=>aq,FilePathTarget:()=>cx,FlacInputFormat:()=>so,FlacOutputFormat:()=>dB,HLS:()=>sT,HLS_FORMATS:()=>sA,HlsInputFormat:()=>sd,HlsOutputFormat:()=>dM,Input:()=>oh,InputAudioTrack:()=>ot,InputDisposedError:()=>of,InputFormat:()=>a7,InputTrack:()=>n5,InputVideoTrack:()=>oe,IsobmffInputFormat:()=>a9,IsobmffOutputFormat:()=>dT,LogLevel:()=>af,Logging:()=>eR,MATROSKA:()=>sm,MP3:()=>sp,MP4:()=>su,MPEG_TS:()=>sb,MatroskaInputFormat:()=>si,MediaSource:()=>cZ,MediaStreamAudioTrackSource:()=>ds,MediaStreamVideoTrackSource:()=>c9,MkvOutputFormat:()=>dP,MovOutputFormat:()=>dv,Mp3InputFormat:()=>sa,Mp3OutputFormat:()=>dx,Mp4InputFormat:()=>se,Mp4OutputFormat:()=>dS,MpegTsInputFormat:()=>sc,MpegTsOutputFormat:()=>dF,NON_PCM_AUDIO_CODECS:()=>eX,NullTarget:()=>cE,OGG:()=>sk,OggInputFormat:()=>sn,OggOutputFormat:()=>d_,Output:()=>dV,OutputAudioTrack:()=>dO,OutputFormat:()=>db,OutputSubtitleTrack:()=>dU,OutputTrack:()=>dD,OutputTrackGroup:()=>dN,OutputVideoTrack:()=>dz,PCM_AUDIO_CODECS:()=>eK,PathedSource:()=>aR,PathedTarget:()=>cI,QTFF:()=>sh,QUALITY_HIGH:()=>nw,QUALITY_LOW:()=>nk,QUALITY_MEDIUM:()=>ny,QUALITY_VERY_HIGH:()=>nb,QUALITY_VERY_LOW:()=>ng,Quality:()=>nd,QuickTimeInputFormat:()=>st,RangedSource:()=>aX,RangedTarget:()=>c_,ReadableStreamSource:()=>aQ,RichImageData:()=>eD,SUBTITLE_CODECS:()=>eY,Source:()=>aF,SourceRef:()=>aM,StreamSource:()=>aj,StreamTarget:()=>cP,SubtitleSource:()=>dm,Target:()=>cA,TextSubtitleSource:()=>df,UnsupportedInputFormatError:()=>om,UrlSource:()=>aW,VIDEO_CODECS:()=>e$,VIDEO_SAMPLE_PIXEL_FORMATS:()=>sU,VideoSample:()=>sW,VideoSampleColorSpace:()=>sQ,VideoSampleResource:()=>sO,VideoSampleSink:()=>n1,VideoSampleSource:()=>c5,VideoSource:()=>c0,WAVE:()=>sg,WEBM:()=>sf,WavOutputFormat:()=>dE,WaveInputFormat:()=>ss,WebMInputFormat:()=>sr,WebMOutputFormat:()=>dC,asc:()=>oi,canDecode:()=>sC,canDecodeAudio:()=>sE,canDecodeVideo:()=>sx,canEncode:()=>nT,canEncodeAudio:()=>nA,canEncodeSubtitles:()=>nP,canEncodeVideo:()=>nS,desc:()=>or,getDecodableAudioCodecs:()=>sB,getDecodableCodecs:()=>s_,getDecodableVideoCodecs:()=>sI,getEncodableAudioCodecs:()=>nE,getEncodableCodecs:()=>nC,getEncodableSubtitleCodecs:()=>n_,getEncodableVideoCodecs:()=>nx,getFirstEncodableAudioCodec:()=>nB,getFirstEncodableSubtitleCodec:()=>nF,getFirstEncodableVideoCodec:()=>nI,prefer:()=>oa,registerDecoder:()=>nV,registerEncoder:()=>nL,registerVideoSampleTransformer:()=>sL});let s=e=>{let t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw Error(`Invalid rotation ${e}.`)},n=e=>e&&e[e.length-1],o=e=>e>=0&&e<0x100000000,l=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)},c=e=>{let t=l(e);return(1&t)==0?-(t>>1):t+1>>1},d=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),h=new TextDecoder,m=new TextEncoder,f=e=>{for(let t=0;t<e.length;t++)if(e.charCodeAt(t)>255)return!1;return!0},p=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),g={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},k=p(g),y={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},w=p(y),b={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},T=p(b),S=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,A=e=>e instanceof ArrayBuffer||"undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class v{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e,t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}let P=/^[0-9a-fA-F]+$/,C=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),x=e=>
1(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,E=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){let n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o<t?r=n+1:a=n-1}return s},_=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){let n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},I=(e,t,i)=>{let r=_(e,i(t),i);e.splice(r+1,0,t)},B=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},F=(e,t)=>{let i=e.indexOf(t);-1!==i&&e.splice(i,1)},M=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},R=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return -1},D=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()},z=e=>{throw Error(`Unexpected value: ${e}`)},O=(e,t,i)=>{let r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},U=(e,t,i,r)=>{i>>>=0,i&=0xffffff,r?(e.setUint8(t,255&i),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,i>>>16&255)):(e.setUint8(t,i>>>16&255),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,255&i))},N=(e,t)=>({async next(){let i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),W=(e,t,i)=>Math.max(t,Math.min(i,e)),V=e=>{let t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},L=(e,t)=>Math.round(e/t)*t,q=(e,t)=>Math.round(e*t)/t,H=(e,t)=>Math.floor(e/t)*t,j=(e,t)=>Math.floor(e*t)/t,Q=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},$=/^[a-z]{3}$/,K=e=>$.test(e),X=1e6*(1+Number.EPSILON),G=(e,t)=>{let i={...e,...t};if(e.headers||t.headers){let r=e.headers?Y(e.headers):{},a=t.headers?Y(t.headers):{},s={...r};Object.entries(a).forEach(([e,t])=>{let i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},Y=e=>{if(e instanceof Headers){let t={};return e.forEach((e,i)=>{t[i]=e}),t}if(Array.isArray(e)){let t={};return e.forEach(([e,i])=>{t[e]=i}),t}return e},J=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(i){if(a())throw i;let e=r(++s,i,t);if(null===e)throw i;if(eR._error("Retrying failed fetch. Error:",i),!Number.isFinite(e)||e<0)throw TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await eE(1e3*e),a())throw i}};class Z{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ee=null,et=()=>null!==ee?ee:ee=!!("undefined"!=typeof navigator&&(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent))),ei=null,er=()=>null!==ei?ei:ei="undefined"!=typeof navigator&&navigator.userAgent?.includes("Firefox"),ea=null,es=()=>null!==ea?ea:ea=!!("undefined"!=typeof navigator&&(navigator.vendor?.includes("Google Inc")||/Chrome/.test(navigator.userAgent))),en=null,eo=()=>{if(null!==en)return en;if("undefined"==typeof navigator)return null;let e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?en=Number(e[1]):null},el=(e,t)=>-1!==e?e:t,ec=(e,t,i,r)=>e<=r&&i<=t,ed=function*(e){for(let t in e){let i=e[t];void 0!==i&&(yield{key:t,value:i})}},eu=e=>{switch(e.toLowerCase()){case"image/jpeg":case"image/jpg":return".jpg";case"image/png":return".png";case"image/gif":return".gif";case"image/webp":return".webp";case"image/bmp":return".bmp";case"image/svg+xml":return".svg";case"image/tiff":return".tiff";case"image/avif":return".avif";case"image/x-icon":case"image/vnd.microsoft.icon":return".ico";default:return null}},eh=e=>{let t=atob(e),i=new Uint8Array(t.length);for(let e=0;e<t.length;e++)i[e]=t.charCodeAt(e);return i},em=e=>{let t="";for(let i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return btoa(t)},ef=(e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0},ep=()=>{Symbol.dispose??=Symbol("Symbol.dispose")},eg=e=>"number"==typeof e&&!Number.isNaN(e),ek=(e,t)=>{let i;if(t.includes("://"))return t;if(e.includes("://")){let t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}if(t.startsWith("/")){let r=e.indexOf("://");if(-1===r)i=t;else{let a=e.indexOf("/",r+3);i=-1===a?e+t:e.slice(0,a)+t}}else{let r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="",a=i.indexOf("://");if(-1!==a){let e=i.indexOf("/",a+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}let s=i.split("/"),n=[];for(let e of s)".."===e?n.pop():"."!==e&&n.push(e);return r+n.join("/")},ey=(e,t)=>{let i=0;for(let r=0;r<e.length;r++)t(e[r])&&i++;return i},ew=(e,t)=>{let i=-1,r=1/0;for(let a=0;a<e.length;a++){let s=t(e[a]);s<r&&(r=s,i=a)}return i},eb=(e,t)=>{let i=-1,r=-1/0;for(let a=0;a<e.length;a++){let s=t(e[a]);s>r&&(r=s,i=a)}return i},eT=e=>{a(Number.isInteger(e.num)),a(Number.isInteger(e.den)),a(0!==e.den);let t=Math.abs(e.num),i=Math.abs(e.den);for(;0!==i;){let e=t%i;t=i,i=e}let r=t||1;return{num:e.num/r,den:e.den/r}},eS=(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.`)},eA=1,ev=new Map,eP=new Map,eC=()=>{let e=new Map,t=new Map;self.onmessage=i=>{let r=i.data;switch(r.type){case"set-timeout":{let t=setTimeout(()=>{e.delete(r.timerId),self.postMessage({type:"fire",timerId:r.timerId})},r.delay);e.set(r.timerId,t)}break;case"set-interval":{let e=setInterval(()=>{self.postMessage({type:"fire",timerId:r.timerId})},r.delay);t.set(r.timerId,e)}break;case"clear-timeout":{let t=e.get(r.timerId);void 0!==t&&(clearTimeout(t),e.delete(r.timerId))}break;case"clear-interval":{let e=t.get(r.timerId);void 0!==e&&(clearInterval(e),t.delete(r.timerId))}}}},ex=()=>
1{if(r)return r;let e=`(${eC.toString()})();`,t=URL.createObjectURL(new Blob([e],{type:"text/javascript"}));return r=new Worker(t),URL.revokeObjectURL(t),r.onmessage=e=>{let t=e.data,i=ev.get(t.timerId);if(i){ev.delete(t.timerId),i();return}let r=eP.get(t.timerId);r&&r()},r},eE=e=>new Promise(t=>setTimeout(t,e)),e_=e=>Array.isArray(e)?e:[e];class eI{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);let r={fn:t,once:i?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){let[t,i]=e,r=this._listeners.get(t);if(r)for(let e of r){try{e.fn(i)}catch(e){console.error(e)}e.once&&r.delete(e)}}}let eB=e=>2*Math.ceil(e/2);class eF{constructor(e){this._queue=[],this._errored=!1,this.parallelism=e}get errored(){return this._errored}get inFlightCount(){return this._queue.length}async run(e){for(this._errored&&await Promise.race(this._queue);this._queue.length>=this.parallelism;)await Promise.race(this._queue);let t=e();this._queue.push(t),t.then(()=>F(this._queue,t)).catch(()=>this._errored=!0)}async flush(){await Promise.all(this._queue)}}let eM=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"}(af||(af={}));class eR{constructor(){}static get level(){return eR._level}static set level(e){if(e!==af.Silent&&e!==af.Errors&&e!==af.Warnings&&e!==af.Info)throw TypeError("Invalid log level. Use one of the values of the LogLevel enum.");eR._level=e}static get _emitter(){return eR._emitterInstance??=new eI}static on(e,t,i){return eR._emitter.on(e,t,i)}static _error(...e){eR._emitter._emit("error",e),eR._level>=af.Errors&&console.error(...e)}static _warn(...e){eR._emitter._emit("warn",e),eR._level>=af.Warnings&&console.warn(...e)}static _info(...e){eR._emitter._emit("info",e),eR._level>=af.Info&&console.info(...e)}}eR._level=af.Info,eR._emitterInstance=null;class eD{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 ez{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(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!==i&&"string"!=typeof i)throw TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!=typeof r)throw TypeError("description, when provided, must be a string.")}}let eO=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("Eac
1h 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 eD)&&!(t instanceof ez)&&!eM(t))throw TypeError("Each value in tags.raw must be a string, Uint8Array, RichImageData, AttachedFile, Record<string, string>, or null.")}},eU=e=>void 0===e.title&&void 0===e.description&&void 0===e.artist&&void 0===e.album&&void 0===e.albumArtist&&void 0===e.trackNumber&&void 0===e.tracksTotal&&void 0===e.discNumber&&void 0===e.discsTotal&&void 0===e.genre&&void 0===e.date&&void 0===e.lyrics&&(!e.images||0===e.images.length)&&void 0===e.comment&&(void 0===e.raw||0===Object.keys(e.raw).length),eN={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class eW{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,i=7-(7&this.pos);return this.pos++,(t&1<<i)>>i}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){let i=this.pos+e;for(let e=this.pos;e<i;e++){let r=Math.floor(e/8),a=this.bytes[r],s=7-(7&e);a&=~(1<<s),a|=(t&1<<i-e-1)>>i-e-1<<s,this.bytes[r]=a}this.pos=i}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 eW(this.bytes);return e.pos=this.pos,e}}let eV=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],eL=[-1,1,2,3,4,5,6,8],eq=e=>{if(!e||e.byteLength<2)throw TypeError("AAC description must be at least 2 bytes long.");let t=new eW(e),i=t.readBits(5);31===i&&(i=32+t.readBits(6));let r=t.readBits(4),a=null;15===r?a=t.readBits(24):r<eV.length&&(a=eV[r]);let s=t.readBits(4),n=null;return s>=1&&s<=7&&(n=eL[s]),{objectType:i,frequencyIndex:r,sampleRate:a,channelConfiguration:s,numberOfChannels:n}},eH=e=>{let t=eV.indexOf(e.sampleRate),i=null;-1===t&&(t=15,i=e.sampleRate);let r=eL.indexOf(e.numberOfChannels);if(-1===r)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 eW(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,i),n.writeBits(4,r),s},ej=e=>{let t=new Uint8Array(7),i=new eW(t),{objectType:r,frequencyIndex:a,channelConfiguration:s}=e;return i.writeBits(12,4095),i.writeBits(1,0),i.writeBits(2,0),i.writeBits(1,1),i.writeBits(2,r-1),i.writeBits(4,a),i.writeBits(1,0),i.writeBits(3,s),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.writeBits(1,0),i.skipBits(13),i.writeBits(11,2047),i.writeBits(2,0),{header:t,bitstream:i}},eQ=(e,t)=>{e.pos=30,e.writeBits(13,t)},e$=["avc","hevc","vp9","av1","vp8","prores"],eK=["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"],eX=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts"],eG=[...eX,...eK],eY=["webvtt"],eJ=[{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}],eZ=[{maxPictureSize:36864,maxBitrate:128e3,tier:"L",level:30},{maxPictureSize:122880,maxBitrate:15e5,tier:"L",level:60},{maxPictureSize:245760,maxBitrate:3e6,tier:"L",level:63},{maxPictureSize:552960,maxBitrate:6e6,tier:"L",level:90},{maxPictureSize:983040,maxBitrate:1e7,tier:"L",level:93},{maxPictureSize:2228224,maxBitrate:12e6,tier:"L",level:120},{maxPictureSize:2228224,maxBitrate:3e7,tier:"H",level:120},{maxPictureSize:2228224,maxBitrate:2e7,tier:"L",level:123},{maxPictureSize:2228224,maxBitrate:5e7,tier:"H",level:123},{maxPictureSize:8912896,maxBitrate:25e6,tier:"L",level:150},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:150},{maxPictureSize:8912896,maxBitrate:4e7,tier:"L",level:153},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:153},{maxPictureSize:8912896,maxBitrate:6e7,tier:"L",level:156},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:156},{maxPictureSize:0x2200000,maxBitrate:6e7,tier:"L",level:180},{maxPictureSize:0x2200000,maxBitrate:24e7,tier:"H",level:180},{maxPictureSize:0x2200000,maxBitrate:12e7,tier:"L",level:183},{maxPictureSize:0x2200000,maxBitrate:48e7,tier:"H",level:183},{maxPictureSize:0x2200000,maxBitrate:24e7,tier:"L",level:186},{maxPictureSize:0x2200000,maxBitrate:8e8,tier:"H",level:186}],e0=[{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}],e1=[{maxPictureSize:147456,maxBitrate:15e5,tier:"M",level:0},{maxPictureSize:278784,maxBitrate:3e6,tier:"M",level:1},{maxPictureSize:665856,maxBitrate:6e6,tier:"M",level:4},{maxPictureSize:1065024,maxBitrate:1e7,tier:"M",level:5},{maxPictureSize:2359296,maxBitrate:12e6,tier:"M",level:8},{maxPictureSize:2359296,maxBitrate:3e7,tier:"H",level:8},{maxPictureSize:2359296,maxBitrate:2e7,tier:"M",level:9},{maxPictureSize:2359296,maxBitrate:5e7,tier:"H",level:9},{maxPictureSize:8912896,maxBitrate:3e7,tier:"M",level:12},{maxPictureSize:8912896,maxBitrate:1e8,tier:"H",level:12},{maxPictureSize:8912896,maxBitrate:4e7,tier:"M",level:13},{maxPictureSize:8912896,maxBitrate:16e7,tier:"H",level:13},{maxPictureSize:8912896,maxBitrate:6e7,tier:"M",level:14},{maxPictureSize:8912896,maxBitrate:24e7,tier:"H",level:14},{maxPictureSize:0x2200000,maxBitrate:6e7,tier:"M",level:15},{maxPictureSize:0x2200000,maxBitrate:24e7,tier:"H",level:15},{maxPictureSize:0x2200000,maxBitrate:6e7,tier:"M",level:16},{maxPictureSize:0x2200000,maxBitrate:24e7,tier:"H",level:16},{maxPictureSize:0x2200000,maxBitrate:1e8,tier:"M",level:17},{maxPictureSize:0x2200000,maxBitrate:48e7,tier:"H",level:17},{maxPictureSize:0x2200000,maxBitrate:16e7,tier:"M",level:18},{maxPictureSize:0x2200000,maxBitrate:8e8,tier:"H",level:18},{maxPictureSize:0x2200000,maxBitrate:16e7,tier:"M",level:19},{maxPictureSize:0x2200000,maxBitrate:8e8,tier:"H",level:19}],e2=".01.01.01.01.00",e3=".0.110.01.01.01.0",e4=["ap4x","ap4h","apch","apcn","apcs","apco"],e8=["dtsc","dtsh","dtsl","dtse"],e6=[{fourCc:"apco",bitrate:45e6,alph
1a:!1},{fourCc:"apcs",bitrate:102e6,alpha:!1},{fourCc:"apcn",bitrate:147e6,alpha:!1},{fourCc:"apch",bitrate:22e7,alpha:!1},{fourCc:"ap4h",bitrate:33e7,alpha:!0},{fourCc:"ap4x",bitrate:5e8,alpha:!0}],e5=(e,t,i,r,a)=>{if("avc"===e){let e=Math.ceil(t/16)*Math.ceil(i/16),a=eJ.find(t=>e<=t.maxMacroblocks&&r<=t.maxBitrate)??n(eJ),s=a?a.level:0,o="64".padStart(2,"0"),l=s.toString(16).padStart(2,"0");return`avc1.${o}00${l}`}if("hevc"===e){let e=t*i,a=eZ.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??n(eZ);return`hev1.1.6.${a.tier}${a.level}.B0`}if("vp8"===e)return"vp8";if("vp9"===e){let e=t*i,a=e0.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??n(e0);return`vp09.00.${a.level.toString().padStart(2,"0")}.08`}if("av1"===e){let e=t*i,a=e1.find(t=>e<=t.maxPictureSize&&r<=t.maxBitrate)??n(e1),s=a.level.toString().padStart(2,"0");return`av01.0.${s}${a.tier}.08`}else if("prores"===e){let e=Math.pow(t*i/2073600,.95),s=e6.filter(e=>e.alpha===a),n=s[0].fourCc,o=1/0;for(let{fourCc:t,bitrate:i}of s){let a=Math.abs(i*e-r);a<o&&(o=a,n=t)}return n}else z(e);throw TypeError(`Unhandled codec '${String(e)}'.`)},e7=e=>{let t=e.split("."),i=Number(t[1]),r=t[2],a=Number(r.slice(0,-1)),s=+("H"===r.slice(-1)),n=Number(t[3]),o=t[4]?Number(t[4]):0,l=t[5]?Number(t[5][0]):1;return[129,(i<<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]},e9=e=>{let{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:s,hevcCodecInfo:o,vp9CodecInfo:l,av1CodecInfo:c,proresFormat:d}=e;if("avc"===t){if(a(null!==e.avcType),s){let t=new Uint8Array([s.avcProfileIndication,s.profileCompatibility,s.avcLevelIndication]);return`avc${e.avcType}.${C(t)}`}if(!i||i.byteLength<4)throw TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${C(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,s,n;if(o)e=o.generalProfileSpace,t=o.generalProfileIdc,r=x(o.generalProfileCompatibilityFlags),a=o.generalTierFlag,s=o.generalLevelIdc,n=[...o.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");let o=u(i),l=o.getUint8(1);e=l>>6&3,t=31&l,r=x(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+=r.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,i=n(e0).level;for(let e of e0)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=l.profile.toString().padStart(2,"0"),i=l.level.toString().padStart(2,"0"),r=l.bitDepth.toString().padStart(2,"0"),a=l.chromaSubsampling.toString().padStart(2,"0"),s=l.colourPrimaries.toString().padStart(2,"0"),o=l.transferCharacteristics.toString().padStart(2,"0"),c=l.matrixCoefficients.toString().padStart(2,"0"),d=l.videoFullRangeFlag.toString().padStart(2,"0"),u=`vp09.${t}.${i}.${r}.${a}`;return(u+=`.${s}.${o}.${c}.${d}`).endsWith(e2)&&(u=u.slice(0,-e2.length)),u}if("av1"===t){if(!c){let t=e.width*e.height,i=n(e0).level;for(let e of e0)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}let t=c.profile,i=c.level.toString().padStart(2,"0"),a=c.tier?"H":"M",s=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),d=r?.primaries?g[r.primaries]:1,u=r?.transfer?y[r.transfer]:1,h=r?.matrix?b[r.matrix]:1,m=+!!r?.fullRange,f=`av01.${t}.${i}${a}.${s}`;return f+=`.${o}.${l.toString().padStart(3,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,(f+=`.${m}`).endsWith(e3)&&(f=f.slice(0,-e3.length)),f}else{if("prores"===t)return d??"apch";null!==t&&z(t)}throw TypeError(`Unhandled codec '${t}'.`)},te=(e,t,i)=>{if("aac"===e)return t>=2&&i<=24e3?"mp4a.40.29":i<=24e3?"mp4a.40.5":"mp4a.40.2";if("mp3"===e)return"mp3";if("opus"===e)return"opus";if("vorbis"===e)return"vorbis";if("flac"===e)return"flac";else if("ac3"===e)return"ac-3";else if("eac3"===e)return"ec-3";else if("dts"===e)return"dtsc";else if(eK.includes(e))return e;throw TypeError(`Unhandled codec '${e}'.`)},tt=e=>{let{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;return e=null!==r.objectType?r.objectType:eq(i).objectType,`mp4a.40.${e}`}}
1if("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("dts"===t)return a??"dtsc";else if(t&&eK.includes(t))return t;throw TypeError(`Unhandled codec '${t}'.`)},ti=/^pcm-([usf])(\d+)(be)?$/,tr=e=>{let t;if(a(eK.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 i=ti.exec(e);a(i),t="u"===i[1]?"unsigned":"s"===i[1]?"signed":"float";let r=Number(i[2])/8;return{dataType:t,sampleSize:r,littleEndian:"be"!==i[3],silentValue:128*("pcm-u8"===e)}},ta=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(e4.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";else if("ac-3"===e||"ac3"===e)return"ac3";else if("ec-3"===e||"eac3"===e)return"eac3";else if(e8.includes(e))return"dts";else if("ulaw"===e)return"ulaw";else if("alaw"===e)return"alaw";else if(ti.test(e))return e;return"webvtt"===e?"webvtt":null},ts=["avc1","avc3","hev1","hvc1","vp8","vp09","av01",...e4],tn=/^(avc1|avc3)\.[0-9a-fA-F]{6}$/,to=/^(hev1|hvc1)\.(?:[ABC]?\d+)\.[0-9a-fA-F]{1,8}\.[LH]\d+(?:\.[0-9a-fA-F]{1,2}){0,6}$/,tl=/^vp09(?:\.\d{2}){3}(?:(?:\.\d{2}){5})?$/,tc=/^av01\.\d\.\d{2}[MH]\.\d{2}(?:\.\d\.\d{3}\.\d{2}\.\d{2}\.\d{2}\.\d)?$/,td=(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(!ts.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&&!A(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 i=Object.keys(g);if(null!=t.primaries&&!i.includes(t.primaries))throw TypeError(`Video chunk metadata decoder configuration colorSpace primaries, when defined, must be one of ${i.join(", ")}.`);let r=Object.keys(y);if(null!=t.transfer&&!r.includes(t.transfer))throw TypeError(`Video chunk metadata decoder configuration colorSpace transfer, when defined, must be one of ${r.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(", ")}.`);
1if(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(!tn.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(!to.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(!tl.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(!tc.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(e4.some(t=>e.decoderConfig.codec.startsWith(t))&&!e4.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: ${e4.join(", ")}.`);if(null!==t&&ta(e.decoderConfig.codec)!==t)throw TypeError(`Video chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},tu=["mp4a","mp3","opus","vorbis","flac","ulaw","alaw","pcm","ac-3","ec-3","dts"],th=(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(!tu.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&&!A(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 
1in 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("dts")){if(!e8.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for DTS must be one of the following four-character codes: ${e8.join(", ")}.`)}else if((e.decoderConfig.codec.startsWith("pcm")||e.decoderConfig.codec.startsWith("ulaw")||e.decoderConfig.codec.startsWith("alaw"))&&!eK.includes(e.decoderConfig.codec))throw TypeError(`Audio chunk metadata decoder configuration codec string for PCM must be one of the supported PCM codecs (${eK.join(", ")}).`);if(null!==t&&ta(e.decoderConfig.codec)!==t)throw TypeError(`Audio chunk metadata decoder configuration codec string '${e.decoderConfig.codec}' does not fit to the track codec '${t}'.`)},tm=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.")},tf=[44100,48e3,32e3],tp=[-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],tg=(e,t,i,r,a)=>0===t?0:1===t?Math.floor(144*i/(r<<e))+a:2===t?Math.floor(144*i/r)+a:(Math.floor(12*i/r)+a)*4,tk=(e,t)=>3===e?3===t?21:36:3===t?13:21,ty=(e,t)=>{let i,r=e>>>24,a=e>>>16&255,s=e>>>8&255,n=255&e;if(255!==r&&255!==a&&255!==s&&255!==n)return{header:null,bytesAdvanced:4};if(255!==r||(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,d=a>>1&3,u=(s>>2&3)%3,h=tp[16*o*4+16*d+(s>>4&15)];if(-1===h)return{header:null,bytesAdvanced:1};let m=1e3*h,f=tf[u]>>o+l,p=tg(o,d,m,f,s>>1&1);return null!==t&&t<p?{header:null,bytesAdvanced:1}:(i=3===c?3===d?384:1152:3===d?384:2===d?1152:576,{header:{totalSize:p,mpegVersionId:c,lowSamplingFrequency:o,layer:d,bitrate:m,frequencyIndex:u,sampleRate:f,channel:n>>6&3,modeExtension:n>>4&3,copyright:n>>3&1,original:n>>2&1,emphasis:3&n,audioSamplesInFrame:i},bytesAdvanced:1})},tw=e=>{let t=0x7f000000,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};!function(e){e[e.FrameCount=1]="FrameCount",e[e.FileSize=2]="FileSize",e[e.Toc=4]="Toc"}(ap||(ap={}));let tb=e=>3===e?1:2,tT=[48e3,44100,32e3],tS=[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"}(ag||(ag={})),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"}(ak||(ak={}));let tA=function*(e){let t=0,i=-1;for(;t<e.length-2;){let r=e.indexOf(0,t);if(-1===r||r>=e.length-2)break;let a=0;if((t=r)+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!==i&&t>i&&(yield{offset:i,length:t-i}),t=i=t+a}-1!==i&&i<e.length&&(yield{offset:i,length:e.length-i})},tv=function*(e,t){let i=0,r=new DataView(e.buffer,e.byteOffset,e.byteLength);for(;i+t<=e.length;){let e;1===t?e=r.getUint8(i):2===t?e=r.getUint16(i,!1):3===t?e=O(r,i,!1):(a(4===t),e=r.getUint32(i,!1)),i+=t,yield{offset:i,length:e},i+=e}},tP=(e,t)=>t.description?tv(e,(3&d(t.description)[4])+1):tA(e),tC=e=>31&e,tx=e=>{let t=[],i=e.length;for(let r=0;r<i;r++)r+2<i&&0===e[r]&&0===e[r+1]&&3===e[r+2]?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},tE=new Uint8Array([0,0,0,1]),t_=e=>{let t=new Uint8Array(e.reduce((e,t)=>
1e+tE.byteLength+t.byteLength,0)),i=0;for(let r of e)t.set(tE,i),i+=tE.byteLength,t.set(r,i),i+=r.byteLength;return t},tI=(e,t)=>{let i=new Uint8Array(e.reduce((e,i)=>e+t+i.byteLength,0)),r=0;for(let a of e){let e=new DataView(i.buffer,i.byteOffset,i.byteLength);switch(t){case 1:e.setUint8(r,a.byteLength);break;case 2:e.setUint16(r,a.byteLength,!1);break;case 3:U(e,r,a.byteLength,!1);break;case 4:e.setUint32(r,a.byteLength,!1)}r+=t,i.set(a,r),r+=a.byteLength}return i},tB=e=>{try{let t=[],i=[],r=[];for(let a of tA(e)){let s=e.subarray(a.offset,a.offset+a.length),n=tC(s[0]);n===ag.SPS?t.push(s):n===ag.PPS?i.push(s):n===ag.SPS_EXT&&r.push(s)}if(0===t.length||0===i.length)return null;let s=t[0],n=tR(s);a(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:i,chromaFormat:o?n.chromaFormatIdc:null,bitDepthLumaMinus8:o?n.bitDepthLumaMinus8:null,bitDepthChromaMinus8:o?n.bitDepthChromaMinus8:null,sequenceParameterSetExt:o?r:null}}catch(e){return eR._error("Error building AVC Decoder Configuration Record:",e),null}},tF=e=>{try{let t=u(e),i=0,r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint8(i++),n=t.getUint8(i++),o=3&t.getUint8(i++),l=31&t.getUint8(i++),c=[];for(let r=0;r<l;r++){let r=t.getUint16(i,!1);i+=2,c.push(e.subarray(i,i+r)),i+=r}let d=t.getUint8(i++),h=[];for(let r=0;r<d;r++){let r=t.getUint16(i,!1);i+=2,h.push(e.subarray(i,i+r)),i+=r}let m={configurationVersion:r,avcProfileIndication:a,profileCompatibility:s,avcLevelIndication:n,lengthSizeMinusOne:o,sequenceParameterSets:c,pictureParameterSets:h,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&i+4<=e.length){let r=3&t.getUint8(i++),a=7&t.getUint8(i++),s=7&t.getUint8(i++),n=t.getUint8(i++);m.chromaFormat=r,m.bitDepthLumaMinus8=a,m.bitDepthChromaMinus8=s;let o=[];for(let r=0;r<n;r++){let r=t.getUint16(i,!1);i+=2,o.push(e.subarray(i,i+r)),i+=r}m.sequenceParameterSetExt=o}return m}catch(e){return eR._error("Error deserializing AVC Decoder Configuration Record:",e),null}},tM={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}},tR=e=>{try{let t=new eW(tx(e));t.skipBits(1),t.skipBits(2);let i=t.readBits(5);if(7!==i)return null;let r=t.readAlignedByte(),s=t.readAlignedByte(),o=t.readAlignedByte();l(t);let d=1,u=0,h=0,m=0;if((100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r)&&(d=l(t),3===d&&(m=t.readBits(1)),u=l(t),h=l(t),t.skipBits(1),t.readBits(1))){for(let e=0;e<(3!==d?8:12);e++)if(t.readBits(1)){let i=e<6?16:64,r=8,a=8;for(let e=0;e<i;e++){if(0!==a){let e=c(t);a=(r+e+256)%256}r=0===a?r:a}}}l(t);let f=l(t);if(0===f)l(t);else if(1===f){t.skipBits(1),c(t),c(t);let e=l(t);for(let i=0;i<e;i++)c(t)}l(t),t.skipBits(1);let p=l(t),g=l(t),k=16*(p+1),y=16*(g+1),w=k,b=y,T=t.readBits(1);if(T||t.skipBits(1),t.skipBits(1),t.readBits(1)){let e,i,r=l(t),a=l(t),s=l(t),n=l(t),o=0===m?d:0;if(0===o)e=1,i=2-T;else{let t=3===d?1:2,r=1===d?2:1;e=t,i=r*(2-T)}w-=e*(r+a),b-=i*(s+n)}let S=2,A=2,v=2,P=0,C={num:1,den:1},x=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=tM[e];t&&(C=t)}}t.readBits(1)&&t.skipBits(1),t.readBits(1)&&(t.skipBits(3),P=t.readBits(1),t.readBits(1)&&(S=t.readBits(8),A=t.readBits(8),v=t.readBits(8))),t.readBits(1)&&(l(t),l(t)),t.readBits(1)&&(t.skipBits(32),t.skipBits(32),t.skipBits(1));let e=t.readBits(1);e&&tD(t);let i=t.readBits(1);i&&tD(t),(e||i)&&t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(1),l(t),l(t),l(t),l(t),x=l(t),E=l(t))}if(null===x)if(a(null===E),(44===r||86===r||100===r||110===r||122===r||244===r)&&16&s)x=0,E=0;else{let e=eJ.find(e=>e.level>=o)??n(eJ),t=Math.min(Math.floor(e.maxDpbMbs/((2-T)*(g+1)*(p+1))),16);x=t,E=t}return a(null!==E),{profileIdc:r,constraintFlags:s,levelIdc:o,frameMbsOnlyFlag:T,chromaFormatIdc:d,bitDepthLumaMinus8:u,bitDepthChromaMinus8:h,codedWidth:k,co
1dedHeight:y,displayWidth:w,displayHeight:b,pixelAspectRatio:C,colourPrimaries:S,matrixCoefficients:v,transferCharacteristics:A,fullRangeFlag:P,numReorderFrames:x,maxDecFrameBuffering:E}}catch(e){return eR._error("Error parsing AVC SPS:",e),null}},tD=e=>{let t=l(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)l(e),l(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},tz=(e,t)=>t.description?tv(e,(3&d(t.description)[21])+1):tA(e),tO=e=>e>>1&63,tU=e=>{try{let t=new eW(tx(e));t.skipBits(16),t.readBits(4);let i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:d}=tW(t,i);l(t);let u=l(t),h=0;3===u&&(h=t.readBits(1));let m=l(t),f=l(t),p=m,g=f;if(t.readBits(1)){let e=l(t),i=l(t),r=l(t),a=l(t),s=1,n=1,o=0===h?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),p-=(e+i)*s,g-=(r+a)*n}let k=l(t),y=l(t);l(t);let w=t.readBits(1)?0:i,b=0;for(let e=w;e<=i;e++)l(t),b=l(t),l(t);l(t),l(t),l(t),l(t),l(t),l(t),t.readBits(1)&&t.readBits(1)&&tV(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),l(t),l(t),t.skipBits(1));let T=l(t);if(tL(t,T),t.readBits(1)){let e=l(t);for(let i=0;i<e;i++)l(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let S=2,A=2,v=2,P=0,C=0,x={num:1,den:1};if(t.readBits(1)){let e=tH(t,i);x=e.pixelAspectRatio,S=e.colourPrimaries,A=e.transferCharacteristics,v=e.matrixCoefficients,P=e.fullRangeFlag,C=e.minSpatialSegmentationIdc}return{displayWidth:p,displayHeight:g,pixelAspectRatio:x,colourPrimaries:S,transferCharacteristics:A,matrixCoefficients:v,fullRangeFlag:P,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:n,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:d,chromaFormatIdc:u,bitDepthLumaMinus8:k,bitDepthChromaMinus8:y,minSpatialSegmentationIdc:C}}catch(e){return eR._error("Error parsing HEVC SPS:",e),null}},tN=e=>{try{let t=[],i=[],r=[],a=[];for(let s of tA(e)){let n=e.subarray(s.offset,s.offset+s.length),o=tO(n[0]);o===ak.VPS_NUT?t.push(n):o===ak.SPS_NUT?i.push(n):o===ak.PPS_NUT?r.push(n):(o===ak.PREFIX_SEI_NUT||o===ak.SUFFIX_SEI_NUT)&&a.push(n)}if(0===i.length||0===r.length)return null;let s=tU(i[0]);if(!s)return null;let n=0;if(r.length>0){let e=r[0],t=new eW(tx(e));t.skipBits(16),l(t),l(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),l(t),l(t),c(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&l(t),c(t),c(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);let i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}let o=[...t.length?[{arrayCompleteness:1,nalUnitType:ak.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:ak.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:ak.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:tO(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:o}}catch(e){return eR._error("Error building HEVC Decoder Configuration Record:",e),null}},tW=(e,t)=>{let i=e.readBits(2),r=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 i=0;i<t;i++)l.push(e.readBits(1)),c.push(e.readBits(1));if(t>0)for(let i=t;i<8;i++)e.skipBits(2);for(let i=0;i<t;i++)l[i]&&e.skipBits(88),c[i]&&e.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},tV=e=>{for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++)if(e.readBits(1)){let i=Math.min(64,1<<4+(t<<1));t>1&&c(e);for(let t=0;t<i;t++)c(e)}else l(e)},tL=(e,t)=>{let i=[];for(let r=0;r<t;r++)i[r]=tq(e,r,t,i)},tq=(e,t,i,r)=>{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){n=t===i?t-(l(e)+1):t-1,e.readBits(1),l(e);let s=r[n]??0;for(let t=0;t<=s;t++)e.readBits(1)||e.readBits(1);a=r[n]}else{let t=l(e),i=l(e);for(let i=0;i<t;i++)l(e),e.readBits(1);for(let t=0;t<i;t++)l(e),e.readBits(1);a=t+i}return a},tH=(e,t)=>{let i=2,r=2,a=2,s=0,n=0,o={num:1,den:1};if(e.readBits(1)){let t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{let e=tM[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&(l(e),l(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(l(e),l(e),l(e),l(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&l(e),e.readBits(1)&&tj(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=l(e),l(e),l(e),l(e),l(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},tj=(e,t,i)=>{let r=!1,a=!1,s=!1;t&&(r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&((s=1===e.readBits(1))&&(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<=i;t++){let t=1===e.readBits(1),i=!0;t||(i=1===e.readBits(1));let n=!1;i?l(e):n=1===e.readBits(1);let o=1;n||(o=l(e)+1),r&&tQ(e,o,s),a&&tQ(e,o,s)}},tQ=(e,t,i)=>{for(let r=0;r<t;r++)l(e),l(e),i&&(l(e),l(e)),e.readBits(1)};
1!function(e){e[e.audAllowed=0]="audAllowed",e[e.beforeFirstVcl=1]="beforeFirstVcl",e[e.afterFirstVcl=2]="afterFirstVcl",e[e.eoBitstreamAllowed=3]="eoBitstreamAllowed",e[e.noMoreDataAllowed=4]="noMoreDataAllowed"}(ay||(ay={}));let t$=e=>{let t=new eW(e);if(2!==t.readBits(2))return null;let i=t.readBits(1),r=(t.readBits(1)<<1)+i;if(3===r&&t.skipBits(1),1===t.readBits(1)||0!==t.readBits(1)||(t.skipBits(2),4817730!==t.readBits(24)))return null;let a=8;r>=2&&(a=t.readBits(1)?12:10);let s=t.readBits(3),o=0,l=0;if(7!==s)if(l=t.readBits(1),1===r||3===r){let e=t.readBits(1),i=t.readBits(1);o=e||i?e&&!i?2:1:3,t.skipBits(1)}else o=1;else o=3,l=1;let c=t.readBits(16),d=(c+1)*(t.readBits(16)+1),u=n(e0).level;for(let e of e0)if(d<=e.maxPictureSize){u=e.level;break}return{profile:r,level:u,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:2===s?1:1===s?6:2,transferCharacteristics:2===s?1:1===s?6:2,matrixCoefficients:7===s?0:2===s?1:1===s?6:2}},tK=function*(e){let t=new eW(e),i=()=>{let e=0;for(let i=0;i<8;i++){let r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=0x100000000-1?null:e};for(;t.getBitsLeft()>=8;){let r;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=i();if(null===e)return;r=e}else r=Math.floor(t.getBitsLeft()/8);a(t.pos%8==0),yield{type:s,data:e.subarray(t.pos/8,t.pos/8+r)},t.skipBits(8*r)}},tX=e=>{for(let{type:t,data:i}of tK(e)){if(1!==t)continue;let e=new eW(i),r=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 i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);let i=e.readBits(5);if(0===r&&(s=i),i>7){let t=e.readBits(1);0===r&&(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),d=l+1;e.skipBits(d);let u=c+1;e.skipBits(u);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 i=e.readBits(1);(i?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 h=e.readBits(1),m=8;2===r&&h?m=e.readBits(1)?12:10:r<=2&&(m=h?10:8);let f=0;1!==r&&(f=e.readBits(1));let p=1,g=1,k=0;return!f&&(0===r?(p=1,g=1):1===r?(p=0,g=0):12===m&&(p=e.readBits(1))&&(g=e.readBits(1)),p&&g&&(k=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:f,chromaSubsamplingX:p,chromaSubsamplingY:g,chromaSamplePosition:k}}return null},tG=e=>{let t=u(e),i=t.getUint8(9),r=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+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}},tY=[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],tJ=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,i=new Uint8Array(t);for(let r=0;r<t;r++)i[r]=e[t-1-r];let r=new eW(i),a=0;for(;r.getBitsLeft()>97;)if(1===r.readBits(1)){a=r.pos;break}if(0===a)throw Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;r.getBitsLeft()>=97;){let e=r.pos,t=r.readBits(8),i=r.readBits(16),a=r.readBits(16);if(t>63||0!==i||0!==a){r.pos=e;break}if(r.skipBits(1),++s>64)break;r.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;r.pos=0,r.skipBits(a);let c=Array(l).fill(0);for(let e=l-1;e>=0;e--)r.skipBits(40),c[e]=r.readBits(1);return{modeBlockflags:c}},tZ=(e,t,i)=>{switch(e){case"avc":for(let e of tP(i,t)){let t=tC(i[e.offset]);if(t>=ag.NON_IDR_SLICE&&t<=ag.SLICE_DPC)break;if(t===ag.IDR)return"key";if(t===ag.SEI&&(!es()||eo()>=144)){let t=tx(i.subarray(e.offset,e.offset+e.length)),r=1;do{let e=0;for(;;){let i=t[r++];if(void 0===i||(e+=i,i<255))break}let i=0;for(;;){let e=t[r++];if(void 0===e||(i+=e,e<255))break}if(6===e){let e=new eW(t);e.pos=8*r;let i=l(e),a=e.readBits(1);if(0===i&&1===a)return"key"}r+=i}while(r<t.length-1)}}return"delta";case"hevc":for(let e of tz(i,t)){let t=tO(i[e.offset]);if(t<ak.BLA_W_LP)break;
1if(t<=ak.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 0==(1&i[0])?"key":"delta";case"vp9":{let e=new eW(i);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:r}of tK(i))if(1===t){let t=new eW(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";let t=new eW(r);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:z(e),a(!1)}};!function(e){e[e.STREAMINFO=0]="STREAMINFO",e[e.VORBIS_COMMENT=4]="VORBIS_COMMENT",e[e.PICTURE=6]="PICTURE"}(aw||(aw={}));let t0=(e,t)=>{let i=u(e),r=0,a=i.getUint32(r,!0);r+=4;let s=h.decode(e.subarray(r,r+a));r+=a,a>0&&(t.raw??={},t.raw.vendor??=s);let n=i.getUint32(r,!0);r+=4;for(let a=0;a<n;a++){let a=i.getUint32(r,!0);r+=4;let s=h.decode(e.subarray(r,r+a));r+=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("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.trackNumber??=i),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??=r)}break;case"TRACKTOTAL":{let e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??=e)}break;case"DISCNUMBER":{let e=l.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.discNumber??=i),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??=r)}break;case"DISCTOTAL":{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=eh(l),i=u(e),r=i.getUint32(0,!1),a=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=i.getUint32(8+a,!1),o=h.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),d=e.subarray(a+n+32,a+n+32+c);t.images??=[],t.images.push({data:d,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},t1=(e,t,i)=>{let r=[e],a=m.encode("Mediabunny"),s=new Uint8Array(4+a.length),n=new DataView(s.buffer);n.setUint32(0,a.length,!0),s.set(a,4),r.push(s);let o=new Set,l=(e,t)=>{let i=`${e}=${t}`,a=m.encode(i);(n=new DataView((s=new Uint8Array(4+a.length)).buffer)).setUint32(0,a.length,!0),s.set(a,4),r.push(s),o.add(e)};for(let{key:e,value:r}of ed(t))switch(e){case"title":l("TITLE",r);break;case"description":l("DESCRIPTION",r);break;case"artist":l("ARTIST",r);break;case"album":l("ALBUM",r);break;case"albumArtist":l("ALBUMARTIST",r);break;case"genre":l("GENRE",r);break;case"date":{let e=t.raw?.DATE??t.raw?.date;l("DATE",e&&"string"==typeof e?e:r.toISOString().slice(0,10))}break;case"comment":l("COMMENT",r);break;case"lyrics":l("LYRICS",r);break;case"trackNumber":l("TRACKNUMBER",r.toString());break;case"tracksTotal":l("TRACKTOTAL",r.toString());break;case"discNumber":l("DISCNUMBER",r.toString());break;case"discsTotal":l("DISCTOTAL",r.toString());break;case"images":if(!i)break;for(let e of r){let t="coverFront"===e.kind?3:4*("coverBack"===e.kind),i=new Uint8Array(e.mimeType.length);for(let t=0;t<e.mimeType.length;t++)i[t]=e.mimeType.charCodeAt(t);let r=m.encode(e.description??""),a=new Uint8Array(8+i.length+4+r.length+16+4+e.data.length),s=u(a);s.setUint32(0,t,!1),s.setUint32(4,i.length,!1),a.set(i,8),s.setUint32(8+i.length,r.length,!1),a.set(r,12+i.length),s.setUint32(28+i.length+r.length,e.data.length,!1),a.set(e.data,32+i.length+r.length),l("METADATA_BLOCK_PICTURE",em(a))}break;case"raw":break;default:z(e)}if(t.raw)for(let e in t.raw){let i=t.raw[e]??t.raw[e.toLowerCase()];"vendor"===e||null==i||o.has(e)||"string"==typeof i&&l(e,i)}let c=new Uint8Array(4);u(c).setUint32(0,o.size,!0),r.splice(2,0,c);let d=new Uint8Array(r.reduce((e,t)=>
1e+t.length,0)),h=0;for(let e of r)d.set(e,h),h+=e.length;return d},t2=[2,1,2,3,3,4,4,5],t3=e=>{if(e.length<7||11!==e[0]||119!==e[1])return null;let t=new eW(e);t.skipBits(16),t.skipBits(16);let i=t.readBits(2);if(3===i)return null;let r=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:i,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},t4=[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],t8=new Uint8Array([5,4,65,67,45,51]),t6=new Uint8Array([5,4,69,65,67,51]),t5=[1,2,3,6],t7=e=>{let t;if(e.length<6||11!==e[0]||119!==e[1])return null;let i=new eW(e);i.skipBits(16);let r=i.readBits(2);if(i.skipBits(3),0!==r&&2!==r)return null;let a=i.readBits(11),s=i.readBits(2),n=0;3===s?(n=i.readBits(2),t=3):t=i.readBits(2);let o=i.readBits(3),l=i.readBits(1),c=i.readBits(5);if(c<11||c>16)return null;let d=t5[t];return{dataRate:Math.round((a+1)*(s<3?tT[s]/1e3:tS[n]/1e3)/(16*d)),substreams:[{fscod:s,fscod2:n,bsid:c,bsmod:0,acmod:o,lfeon:l,numDepSub:0,chanLoc:0}]}},t9=e=>{let t=e.substreams[0];return(a(t),t.fscod<3)?tT[t.fscod]:null!==t.fscod2&&t.fscod2<3?tS[t.fscod2]:null},ie=e=>{let t=e.substreams[0];a(t);let i=t2[t.acmod]+t.lfeon;if(t.numDepSub>0){let e=[2,2,1,1,2,2,2,1,1];for(let r=0;r<9;r++)t.chanLoc&1<<8-r&&(i+=e[r])}return i},it=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],ii=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],ir=[16,16,20,20,0,24,24,0],ia=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],is=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],io=[32e3,44100,48e3,0],il=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],ic=[512,1024,2048,4096],id=e=>{let t=ih(e),i=u(e),r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&0x64582025===i.getUint32(r);){let t=im(e.subarray(r));if(!t)break;a??=t,r+=t.frameSize}if(t)return{frameSize:a?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==a};if(!a?.asset)return null;let{asset:s}=a;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},iu=e=>{let t=id(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},ih=e=>{if(e.length<18||127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;let t=new eW(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;let i=t.readBits(1),r=t.readBits(7)+1;if(r%8!=0)return null;let a=t.readBits(14)+1;if(a<96)return null;let s=t.readBits(6);if(s>=ia.length)return null;let n=it[t.readBits(4)];if(0===n)return null;let o=ii[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);let l=t.readBits(2);if(3===l)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);let c=ir[t.readBits(3)];if(0===c)return null;let d=0!==l;return{frameSize:a,sampleRate:n,numberOfChannels:ia[s]+ +!!d,sampleCount:32*r,channelLayout:is[s]|8*!!d,amode:s,lfePresent:d,bitRate:o,pcmResolution:c}},im=e=>{if(e.length<10||100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;let t=new eW(e);t.skipBits(32),t.skipBits(8);let i=t.readBits(2),r=t.readBits(1),a=16+4*r;t.skipBits(8+4*r);let s=t.readBits(a)+1,n={frameSize:s,asset:null};if(!t.readBits(1))return n;let o=io[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);let c=t.readBits(3)+1,d=t.readBits(3)+1,u=[];for(let e=0;e<c;e++)u.push(t.readBits(i+1));for(let e of u)t.skipBits(8*Q(e));
1if(t.readBits(1)){t.skipBits(2);let e=t.readBits(2)+1<<2,i=t.readBits(2)+1;t.skipBits(i*e)}for(let e=0;e<d;e++)t.skipBits(a);t.skipBits(9),t.skipBits(3),t.readBits(1)&&t.skipBits(4),t.readBits(1)&&t.skipBits(24),t.readBits(1)&&t.skipBits(8*(t.readBits(10)+1));let h=t.readBits(5)+1,m=il[t.readBits(4)],f=t.readBits(8)+1,p=0;if(t.readBits(1)&&(f>2&&t.skipBits(1),f>6&&t.skipBits(1),t.readBits(1))){let e=t.readBits(2)+1<<2;p=t.readBits(e)}return 0===o||0>t.getBitsLeft()?n:{frameSize:s,asset:{sampleRate:m,numberOfChannels:f,sampleCount:Math.round(l*m/o),channelLayout:p,pcmResolution:h}}};class ip{constructor(e){this.input=e}dispose(){}}let ig=new Uint8Array(0);class ik{constructor(e,t,i,r,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=a,e===ig&&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(i))throw TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<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===ig}get microsecondTimestamp(){return Math.trunc(X*this.timestamp)}get microsecondDuration(){return Math.trunc(X*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 i=new Uint8Array(e.byteLength);return e.copyTo(i),new ik(i,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 ik(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 iy=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");if(e.codecStrings.length>0){let i=[...new Set(e.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t},iw=e=>{let t=u(e),i=0,r=t.getUint8(i);i+=4;let a=C(e.subarray(i,i+16));i+=16;let s=null;if(r>0){let r=t.getUint32(i);if(i+=4,r>0){s=[];for(let t=0;t<r;t++)s.push(C(e.subarray(i,i+16))),i+=16}}let n=t.getUint32(i);return i+=4,{systemId:a,keyIds:s,data:e.slice(i,i+n)}},ib=(e,t)=>e.systemId===t.systemId&&ef(e.data,t.data),iT=e=>{let t=oP(e),i=oR(e,4),r=8;1===t&&(t=o_(e),r=16);let a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},iS=e=>ox(e)/65536,iA=e=>ox(e)/0x40000000,iv=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;let i=ow(e);if(t|=127&i,(128&i)==0)break}return t},iP=e=>{let t=oT(e);return e.skip(2),t=Math.min(t,e.remainingLength),h.decode(oy(e,t))},iC=e=>{let t=iT(e);if(!t||"data"!==t.name||e.remainingLength<8)return null;let i=oP(e);e.skip(4);let r=oy(e,t.contentSize-8);switch(i){case 1:return h.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new eD(r,"image/jpeg");case 14:return new eD(r,"image/png");case 27:return new eD(r,"image/bmp");default:return r}},ix=new Uint32Array(256),iE=new Uint32Array(256),i_=new Uint32Array(256),iI=new Uint32Array(256),iB=new Uint32Array(256),iF=new Uint32Array(256),iM=new Uint32Array(10),iR=!1;class iD{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}){a(16===e.byteLength),a(16===t.byteLength),iR||(()=>{let e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let e=0,r=1;e<256;e++)i[e]=r,t[r]=e,r=r^r<<1^(128&r?283:0);let r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let r=1;r<256;r++){let a=i[255-t[r]],s=a^a<<1^a<<2^a<<3^a<<4;s=s>>>8^255&s^99,e[r]=s}for(let t=0;t<256;t++){let i=e[t],a=e.indexOf(t);ix[t]=i<<24|i<<16|i<<8|i,iF[t]=a<<24|a<<16|a<<8|a;let s=r(a,14),n=r(a,9),o=s<<24|n<<16|r(a,13)<<8|r(a,11);iE[t]=o,i_[t]=o>>>8|o<<24,iI[t]=o>>>16|o<<16,iB[t]=o>>>24|o<<8}let a=1;for(let e=0;e<10;e++)iM[e]=a<<24,a=a<<1^(128&a?283:0);iR=!0})();let i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.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&ix[t>>>16&255]^0xff0000&ix[t>>>8&255]^65280&ix[t>>>0&255]^255&ix[t>>>24&255]^iM[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 i=0;i<4;i++){let r=this.roundkey[e+i];this.roundkey[e+i]=this.roundkey[t+i],this.roundkey[t+i]=r}for(let e=4;e<40;e+=4)for(let t=0;t<4;t++){let i=this.roundkey[e+t];this.roundkey[e+t]=iE[255&ix[i>>>24&255]]^i_[255&ix[i>>>16&255]]^iI[255&ix[i>>>8&255]]^iB[255&ix[i>>>0&255]]}}decrypt(){let e,t,i,r,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),d=this.inView.getUint32(8,!1),u=this.inView.getUint32(12,!1);for(let l=1;l<10;l++){let c=4*l;e=iE[a>>>24]^i_[o>>>16&255]^iI[n>>>8&255]^iB[255&s]^this.roundkey[c],t=iE[s>>>24]^i_[a>>>16&255]^iI[o>>>8&255]^iB[255&n]^this.roundkey[c+1],i=iE[n>>>24]^i_[s>>>16&255]^iI[a>>>8&255]^iB[255&o]^this.roundkey[c+2],r=iE[o>>>24]^i_[n>>>16&255]^iI[s>>>8&255]^iB[255&a]^this.roundkey[c+3],a=e,s=t,n=i,o=r}let h=0xff000000&iF[a>>>24&255]^0xff0000&iF[o>>>16&255]^65280&iF[n>>>8&255]^255&iF[s>>>0&255]^this.roundkey[40],m=0xff000000&iF[s>>>24&255]^0xff0000&iF[a>>>16&255]^65280&iF[o>>>8&255]^255&iF[n>>>0&255]^this.roundkey[41],f=0xff000000&iF[n>>>24&255]^0xff0000&iF[s>>>16&255]^65280&iF[a>>>8&255]^255&iF[o>>>0&255]^this.roundkey[42],p=0xff000000&iF[o>>>24&255]^0xff0000&iF[n>>>16&255]^65280&iF[s>>>8&255]^255&iF[a>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,m^this.iv[1],!1),this.outView.setUint32(8,f^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=l,this.iv[1]=c,this.iv[2]=d,this.iv[3]=u}}class iz extends ip{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 iy({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,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(r instanceof Promise&&(r=await r),!r)break;let a=e,s=iT(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){let e=oR(r,4);this.isQuickTime="qt  "===e}else if("moov"===s.name){let e=this.reader.requestSlice(r.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,i=!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,i=!0;break}e=a+s.totalSize}if(!i&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){a(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=await e),a(e);let t=oP(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(e instanceof Promise&&(e=await e),e){let t=iT(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);i instanceof Promise&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})()}async copyMetadataFromInitInput(e){let t=await e._getDemuxer();if(t.constructor!==iz)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&&(a(t.info),"video"===t.info.type&&-1!==t.info.width?(t.trackBacking=new iU(t),this.tracks.push(t)):"audio"===t.info.type&&-1!==t.info.numberOfChannels&&(t.trackBacking=new iN(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;a(this.moovSlice);let i=this.moovSlice.slice(e.sampleTableByteOffset);if(this.currentTrack=e,this.traverseBox(i),this.currentTrack=null,e.info?.type==="audio"&&e.info.codec&&eK.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){a(e.info?.type==="audio");let i=tr(e.info.codec),r=[],s=[];for(let a=0;a<t.sampleToChunk.length;a++){let o=t.sampleToChunk[a],l=t.sampleToChunk[a+1],c=(l?l.startChunkIndex:t.chunkOffsets.length)-o.startChunkIndex;for(let a=0;a<c;a++){let l=o.startSampleIndex+a*o.samplesPerChunk,c=l+o.samplesPerChunk,d=_(t.sampleTimingEntries,l,e=>e.startIndex),u=t.sampleTimingEntries[d],h=_(t.sampleTimingEntries,c,e=>e.startIndex),m=t.sampleTimingEntries[h],f=u.startDecodeTimestamp+(l-u.startIndex)*u.delta,p=m.startDecodeTimestamp+(c-m.startIndex)*m.delta-f,g=n(r);g&&g.delta===p?g.count++:r.push({startIndex:o.startChunkIndex+a,startDecodeTimestamp:f,count:1,delta:p});let k=o.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;s.push(k)}o.startSampleIndex=o.startChunkIndex,o.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=s}if(t.sampleCompositionTimeOffsets.length>0){for(let e of(t.presentationTimestamps=[],t.sampleTimingEntries))for(let i=0;i<e.count;i++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+i*e.delta,sampleIndex:e.startIndex+i});for(let e of t.sampleCompositionTimeOffsets)for(let i=0;i<e.count;i++){let r=e.startIndex+i,a=t.presentationTimestamps[r];a&&(a.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);t instanceof Promise&&(t=await t),a(t);let i=iT(t);a(i?.name==="moof");let r=this.reader.requestSlice(e,i.totalSize);r instanceof Promise&&(r=await r),a(r),this.traverseBox(r);let s=this.lastReadFragment;for(let[,t]of(a(s&&s.moofOffset===e),s.trackData)){let e=t.track,{fragmentPositionCache:i}=e;if(!t.startTimestampIsFinal){let r=e.fragmentLookupTable.find(e=>e.moofOffset===s.moofOffset);if(r)iH(t,r.timestamp);else{let e=_(i,s.moofOffset-1,e=>e.moofOffset);-1!==e&&iH(t,i[e].endTimestamp)}t.startTimestampIsFinal=!0}let r=_(i,t.startTimestamp,e=>e.startTimestamp);if((-1===r||i[r].moofOffset!==s.moofOffset)&&i.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:t.startTimestamp,endTimestamp:t.endTimestamp}),t.encryptionAuxInfo&&e.encryptionInfo){let i=await iK(this.reader,e.encryptionInfo,t.encryptionAuxInfo);for(let e=0;e<Math.min(t.samples.length,i.length);e++){let r=i[e];t.samples[e].encryption=r}}}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,i=iT(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=t+i.totalSize}}traverseBox(e){let t=e.filePos,i=iT(e);if(!i)return!1;let r=e.filePos,o=t+i.totalSize;switch(i.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":case"wave":this.readContiguousBoxes(e.slice(r,i.contentSize));break;
1case"mvhd":{let t=ow(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=oP(e),this.movieDurationInTimescale=o_(e)):(e.skip(8),this.movieTimescale=oP(e),this.movieDurationInTimescale=oP(e))}break;case"trak":{let t={id:-1,demuxer:this,trackBacking:null,disposition:{...eN,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(r,i.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info&&("video"===t.info.type&&-1!==t.info.width?(t.trackBacking=new iU(t),this.tracks.push(t)):"audio"===t.info.type&&-1!==t.info.numberOfChannels&&(t.trackBacking=new iN(t),this.tracks.push(t))),this.currentTrack=null}break;case"tkhd":{let t=this.currentTrack;if(!t)break;let i=ow(e),r=oS(e);if(t.disposition.default=!!(1&r),0===i)e.skip(8),t.id=oP(e),e.skip(4),t.durationInMovieTimescale=oP(e);else if(1===i)e.skip(16),t.id=oP(e),e.skip(4),t.durationInMovieTimescale=o_(e);else throw Error(`Incorrect track header version ${i}.`);e.skip(16);let n=s(L(ij([iS(e),iS(e),iA(e),iS(e),iS(e),iA(e),iS(e),iS(e),iA(e)]),90));a(0===n||90===n||180===n||270===n),t.rotation=n}break;case"elst":{let t=this.currentTrack;if(!t)break;let i=ow(e);e.skip(3);let r=!1,a=0,s=oP(e);for(let n=0;n<s;n++){let s=1===i?o_(e):oP(e),n=1===i?oI(e):ox(e),o=iS(e);if(0!==s){if(r){eR._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1===n){a+=s;continue}if(1!==o){eR._warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=a,t.editListOffset=n,r=!0}}}break;case"mdhd":{let t=this.currentTrack;if(!t)break;let i=ow(e);e.skip(3),0===i?(e.skip(8),t.timescale=oP(e),t.durationInMediaTimescale=oP(e)):1===i&&(e.skip(16),t.timescale=oP(e),t.durationInMediaTimescale=o_(e));let r=oT(e);if(r>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;K(t.languageCode)||(t.languageCode="und")}}break;case"hdlr":{let t=this.currentTrack;if(!t)break;e.skip(8);let i=oR(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{let a=this.currentTrack;if(!a)break;a.sampleTableByteOffset=t,this.readContiguousBoxes(e.slice(r,i.contentSize))}break;case"stsd":{let t=this.currentTrack;if(!t||null===t.info||t.sampleTable)break;let i=ow(e);e.skip(3);let r=oP(e);for(let a=0;a<r;a++){let r=e.filePos,a=iT(e);if(!a)break;t.internalCodecId=a.name;let s=a.name.toLowerCase();if("video"===t.info.type){e.skip(24),t.info.width=oT(e),t.info.height=oT(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));let i="encv"===s?t.frmaCodecString:s;t.frmaCodecString=null,"avc1"===i||"avc3"===i?(t.info.codec="avc",t.info.avcType="avc1"===i?1:3):"hvc1"===i||"hev1"===i?t.info.codec="hevc":"vp08"===i?t.info.codec="vp8":"vp09"===i?t.info.codec="vp9":"av01"===i?t.info.codec="av1":e4.includes(s)?(t.info.codec="prores",t.info.proresFormat=s):null===i?eR._warn("Unknown encrypted video codec due to missing frma box."):eR._warn(`Unsupported video codec (sample entry type '${a.name}').`)}else{e.skip(8);let n=oT(e);e.skip(6);let o=oT(e),l=oT(e);e.skip(4);let c=oP(e)/65536,d=null;0===i&&n>0&&(1===n?(e.skip(4),l=8*oP(e),e.skip(8)):2===n&&(e.skip(4),c=oM(e),o=oP(e),e.skip(4),l=oP(e),d=oP(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=c,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));let u="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===u);else if("opus"===u)t.info.codec="opus",t.info.sampleRate=48e3;else if("flac"===u)t.info.codec="flac";else if("ulaw"===u)t.info.codec="ulaw";else if("alaw"===u)t.info.codec="alaw";
1else if("ac-3"===u)t.info.codec="ac3";else if("ec-3"===u)t.info.codec="eac3";else if(e8.includes(u))t.info.codec="dts",t.info.dtsFormat=u;else if("twos"===u)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(eR._warn(`Unsupported sample size ${l} for codec 'twos'.`),t.info.codec=null);else if("sowt"===u)8===l?t.info.codec="pcm-s8":16===l?t.info.codec="pcm-s16":(eR._warn(`Unsupported sample size ${l} for codec 'sowt'.`),t.info.codec=null);else if("raw "===u)t.info.codec="pcm-u8";else if("in24"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===u)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===u){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":(eR._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":(eR._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===u){let e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(eR._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(eR._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===u&&null!==d){let e=l+7>>3,i=!!(1&d),r=!!(2&d),a=4&d?-1:0;l>0&&l<=64&&(i?32===l&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=r?"pcm-s16be":"pcm-s16":3===e?t.info.codec=r?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=r?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&eR._warn("Unsupported PCM format.")}else null===u?eR._warn("Unknown encrypted audio codec due to missing frma box."):eR._warn(`Unsupported audio codec (sample entry type '${a.name}').`)}
1e.filePos=r+a.totalSize}}break;case"frma":{let t=this.currentTrack;if(!t)break;t.frmaCodecString=oR(e,4).toLowerCase()}break;case"schm":{let t=this.currentTrack;if(!t)break;e.skip(4);let i=oR(e,4);"cenc"===i||"cens"===i||"cbcs"===i?t.encryptionInfo={scheme:i,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:eR._warn(`Unsupported encryption scheme '${i}'.`)}break;case"tenc":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let i=ow(e);e.skip(3),e.skip(1);let r=ow(e);if(i>0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==ow(e),t.encryptionInfo.defaultPerSampleIvSize=ow(e),t.encryptionInfo.defaultKid=C(oy(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){let i=ow(e),r=new Uint8Array(16);r.set(oy(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{let t=this.currentTrack;if(!t)break;a(t.info),t.info.codecDescription=oy(e,i.contentSize)}break;case"hvcC":{let t=this.currentTrack;if(!t)break;a(t.info),t.info.codecDescription=oy(e,i.contentSize)}break;case"vpcC":{let t=this.currentTrack;if(!t)break;a(t.info?.type==="video"),e.skip(4);let i=ow(e),r=ow(e),s=ow(e),n=ow(e),o=ow(e),l=ow(e);t.info.vp9CodecInfo={profile:i,level:r,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;a(t.info?.type==="video"),e.skip(1);let i=ow(e),r=i>>5,s=ow(e),n=s>>6&1;t.info.av1CodecInfo={profile:r,level:31&i,tier:s>>7,bitDepth:2===r&&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,i=this.currentTrack;if(!i)break;a(i.info?.type==="video");let r=oR(e,4);if("nclx"!==r&&"nclc"!==r)break;let s=oT(e),n=oT(e),o=oT(e);"nclx"===r&&(t=!!(128&ow(e))),i.info.colorSpace={primaries:k[s],transfer:w[n],matrix:T[o],fullRange:t}}break;case"pasp":{let t=this.currentTrack;if(!t)break;a(t.info?.type==="video");let i=oP(e),r=oP(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{let t=this.currentTrack;if(!t)break;a(t.info?.type==="audio"),e.skip(4),a(3===ow(e)),iv(e),e.skip(2);let i=ow(e);if((128&i)!=0&&e.skip(2),(64&i)!=0){let t=ow(e);e.skip(t)}(32&i)!=0&&e.skip(2),a(4===ow(e));let r=iv(e),s=e.filePos,n=ow(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":169===n?t.info.codec="dts":eR._warn(`Unsupported audio codec (objectTypeIndication ${n}) - discarding track.`),e.skip(12),r>e.filePos-s){a(5===ow(e));let i=iv(e);if(t.info.codecDescription=oy(e,i),"aac"===t.info.codec){let e=eq(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;a(t.info?.type==="audio"),t.info.pcmLittleEndian=!!(255&oT(e))}break;case"pcmC":{let t=this.currentTrack;if(!t)break;a(t.info?.type==="audio"),e.skip(4);let i=ow(e);t.info.pcmLittleEndian=!!(1&i),t.info.pcmSampleSize=ow(e)}break;case"dOps":{let t,i=this.currentTrack;if(!i)break;a(i.info?.type==="audio"),e.skip(1);let r=ow(e),s=oT(e),n=oP(e),o=oA(e),l=ow(e);t=0!==l?oy(e,2+r):new Uint8Array(0);let c=new Uint8Array(19+t.byteLength),d=new DataView(c.buffer);d.setUint32(0,0x4f707573,!1),d.setUint32(4,0x48656164,!1),d.setUint8(8,1),d.setUint8(9,r),d.setUint16(10,s,!0),d.setUint32(12,n,!0),d.setInt16(16,o,!0),d.setUint8(18,l),c.set(t,19),i.info.codecDescription=c,i.info.numberOfChannels=r}break;case"dfLa":{let t=this.currentTrack;if(!t)break;a(t.info?.type==="audio"),e.skip(4);let i=e.filePos;for(;e.filePos<o;){let i=ow(e),r=oS(e);if((127&i)===aw.STREAMINFO){e.skip(10);let i=oP(e),r=i>>>12,a=(i>>9&7)+1;t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(r);if(128&i)break}let r=e.filePos;e.filePos=i;let s=oy(e,r-i),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;a(t.info?.type==="audio");let i=new eW(oy(e,3)),r=i.readBits(2);i.skipBits(8);let s=i.readBits(3),n=i.readBits(1);r<3&&(t.info.sampleRate=tT[r]),t.info.numberOfChannels=t2[s]+n}break;case"dec3":{let t=this.currentTrack;if(!t)break;a(t.info?.type==="audio");let r=(e=>{if(e.length<2)return null;let t=new eW(e),i=t.readBits(13),r=t.readBits(3),a=[];for(let i=0;i<=r&&!(Math.ceil(t.pos/8)+3>e.length);i++){let e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);let r=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:i,bsmod:r,acmod:s,lfeon:n,numDepSub:o,chanLoc:l})}return 0===a.length?null:{dataRate:i,substreams:a}})(oy(e,i.contentSize));if(!r){eR._warn("Invalid dec3 box contents, ignoring.");break}let s=t9(r);null!==s&&(t.info.sampleRate=s),t.info.numberOfChannels=ie(r)}break;case"ddts":{let t=this.currentTrack;if(!t)break;a(t.info?.type==="audio");let r=(e=>{let t;if(e.length<20)return null;let i=u(e),r=i.getUint32(0);if(0===r)return null;let a=new eW(e);a.seekToByte(13);let s=a.readBits(2);a.skipBits(5);let n=a.readBits(1),o=a.readBits(6);a.skipBits(14),a.skipBits(1),a.skipBits(3);let l=a.readBits(16),c=null;return 0!==l?c=Q(t=l)+Q(44646&t):o<ia.length&&(c=ia[o]+n),{sampleRate:r,maxBitrate:i.getUint32(4),avgBitrate:i.getUint32(8),pcmSampleDepth:e[12],sampleCount:ic[s],channelLayout:l,numberOfChannels:c}})(oy(e,Math.min(i.contentSize,20)));if(!r){eR._warn("Invalid ddts box contents, ignoring.");break}t.info.sampleRate=r.sampleRate,null!==r.numberOfChannels&&(t.info.numberOfChannels=r.numberOfChannels)}break;case"stts":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let i=oP(e),r=0,a=0;for(let s=0;s<i;s++){let i=oP(e),s=oP(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:a,count:i,delta:s}),r+=i,a+=i*s}}break;case"ctts":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let i=oP(e),r=0;for(let a=0;a<i;a++){let i=oP(e),a=ox(e);
1t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:i,offset:a}),r+=i}}break;case"stsz":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let i=oP(e),r=oP(e);if(0===i)for(let i=0;i<r;i++){let i=oP(e);t.sampleTable.sampleSizes.push(i)}else t.sampleTable.sampleSizes.push(i)}break;case"stz2":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),e.skip(3);let i=ow(e),r=oP(e),a=new eW(oy(e,Math.ceil(r*i/8)));for(let e=0;e<r;e++){let e=a.readBits(i);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];let i=oP(e);for(let r=0;r<i;r++){let i=oP(e)-1;t.sampleTable.keySampleIndices.push(i)}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 i=oP(e);for(let r=0;r<i;r++){let i=oP(e)-1,r=oP(e),a=oP(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:i,samplesPerChunk:r,sampleDescriptionIndex:a})}let r=0;for(let e=0;e<t.sampleTable.sampleToChunk.length;e++)t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1&&(r+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk)}break;case"stco":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let i=oP(e);for(let r=0;r<i;r++){let i=oP(e);t.sampleTable.chunkOffsets.push(i)}}break;case"co64":{let t=this.currentTrack;if(!t||!t.sampleTable)break;e.skip(4);let i=oP(e);for(let r=0;r<i;r++){let i=o_(e);t.sampleTable.chunkOffsets.push(i)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(r,i.contentSize));break;case"mehd":{let t=ow(e);e.skip(3);let i=1===t?o_(e):oP(e);this.movieDurationInTimescale=i}break;case"trex":{e.skip(4);let t=oP(e),i=oP(e),r=oP(e),a=oP(e),s=oP(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:i,defaultSampleDuration:r,defaultSampleSize:a,defaultSampleFlags:s})}break;case"tfra":{let t=ow(e);e.skip(3);let i=oP(e),r=this.tracks.find(e=>e.id===i);if(!r)break;let a=oP(e),s=[ow,oT,oS,oP],n=s[(48&a)>>4],o=s[(12&a)>>2],l=s[3&a],c=oP(e);for(let i=0;i<c;i++){let i=1===t?o_(e):oP(e),a=1===t?o_(e):oP(e);n(e),o(e),l(e),r.fragmentLookupTable.push({timestamp:i,moofOffset:a})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){let t=r.fragmentLookupTable[e],i=r.fragmentLookupTable[e+1];t.timestamp===i.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:t,moofSize:i.totalSize,implicitBaseDataOffset:t,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(r,i.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(a(this.currentFragment),this.readContiguousBoxes(e.slice(r,i.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 i=e.presentationTimestamps[t],r=e.samples[i.sampleIndex];null===e.firstKeyFrameTimestamp&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.presentationTimestamp),t<e.presentationTimestamps.length-1&&(r.duration=e.presentationTimestamps[t+1].presentationTimestamp-i.presentationTimestamp)}let t=e.samples[e.presentationTimestamps[0].sampleIndex],i=e.samples[n(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=i.presentationTimestamp+i.duration;let{currentFragmentState:r}=this.currentTrack;a(r),null!==r.startTimestamp&&(iH(e,r.startTimestamp),e.startTimestampIsFinal=!0),r.encryptionAuxInfo&&!e.samples[0].encryption&&(e.encryptionAuxInfo=r.encryptionAuxInfo)}this.currentTrack.currentFragmentState=null,this.currentTrack=null}break;case"pssh":{if(this.input._formatOptions.isobmff?._suppressPsshParsing)break;let t=iw(oy(e,i.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.pss
1hBoxes.push(t)}break;case"tfhd":{a(this.currentFragment),e.skip(1);let t=oS(e),i=oP(e),r=this.tracks.find(e=>e.id===i);if(!r)break;let s=this.fragmentTrackDefaults.find(e=>e.trackId===i);this.currentTrack=r,r.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?r.currentFragmentState.baseDataOffset=o_(e):131072&t&&(r.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),2&t&&(r.currentFragmentState.sampleDescriptionIndex=oP(e)),8&t&&(r.currentFragmentState.defaultSampleDuration=oP(e)),16&t&&(r.currentFragmentState.defaultSampleSize=oP(e)),32&t&&(r.currentFragmentState.defaultSampleFlags=oP(e)),65536&t&&(r.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{let t=this.currentTrack;if(!t)break;a(t.currentFragmentState);let i=ow(e);e.skip(3);let r=0===i?oP(e):o_(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{let t,i=this.currentTrack;if(!i)break;a(this.currentFragment),a(i.currentFragmentState);let r=ow(e),s=oS(e),n=!!(256&s),o=!!(512&s),l=!!(1024&s),c=!!(2048&s),d=oP(e),u=null;1&s&&(u=ox(e));let h=null;4&s&&(h=oP(e)),this.currentFragment.trackData.has(i.id)?(t=this.currentFragment.trackData.get(i.id),null!==u&&(t.currentOffset=i.currentFragmentState.baseDataOffset+u)):(t={track:i,currentTimestamp:0,currentOffset:i.currentFragmentState.baseDataOffset+(u??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(i.id,t));for(let s=0;s<d;s++){let d,u,m;n?d=oP(e):(a(null!==i.currentFragmentState.defaultSampleDuration),d=i.currentFragmentState.defaultSampleDuration),o?u=oP(e):(a(null!==i.currentFragmentState.defaultSampleSize),u=i.currentFragmentState.defaultSampleSize),l?m=oP(e):(a(null!==i.currentFragmentState.defaultSampleFlags),m=i.currentFragmentState.defaultSampleFlags),0===s&&null!==h&&(m=h);let f=0;c&&(f=0===r?oP(e):ox(e));let p=!(65536&m);t.samples.push({presentationTimestamp:t.currentTimestamp+f,duration:d,byteOffset:t.currentOffset,byteSize:u,isKeyFrame:p,encryption:null}),t.currentOffset+=u,t.currentTimestamp+=d}this.currentFragment.implicitBaseDataOffset=t.currentOffset}break;case"saiz":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;if(e.skip(1),1&oS(e)){let i=oR(e,4),r=oP(e);if(i!==t.encryptionInfo.scheme||0!==r)break}let i=ow(e),r=oP(e),a=null;0===i&&r>0&&(a=oy(e,r));let s=i$(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;let i=ow(e);if(1&oS(e)){let i=oR(e,4),r=oP(e);if(i!==t.encryptionInfo.scheme||0!==r)break}let r=oP(e);if(0===r)break;r>1&&eR._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?oP(e):Number(o_(e));this.currentFragment&&(a+=this.currentFragment.moofOffset),i$(t).offset=a}break;case"senc":{let t=this.currentTrack;if(!t||!t.encryptionInfo)break;a(this.currentFragment);let i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);let r=!!(2&oS(e)),s=oP(e),n=t.encryptionInfo.defaultPerSampleIvSize;a(null!==n);for(let a=0;a<Math.min(s,i.samples.length);a++){let s=new Uint8Array(16);n>0?s.set(oy(e,n),0):s.set(t.encryptionInfo.defaultConstantIv,0);let o=null;if(r){let t=oT(e);o=[];for(let i=0;i<t;i++){let t=oT(e),i=oP(e);o.push({clearLen:t,protectedLen:i})}}i.samples[a].encryption={iv:s,subsamples:o}}}break;case"udta":for(let{boxInfo:t,slice:a}of this.iterateContiguousBoxes(e.slice(r,i.contentSize))){if("meta"!==t.name&&!this.currentTrack){let e=a.filePos;this.metadataTags.raw??={},"\xa9"===t.name[0]?this.metadataTags.raw[t.name]??=iP(a):this.metadataTags.raw[t.name]??=oy(a,t.contentSize),a.filePos=e}switch(t.name){case"meta":a.skip(-t.headerSize),this.traverseBox(a);break;case"\xa9nam":case"name":this.currentTrack?this.currentTrack.name=h.decode(oy(a,t.contentSize)):this.metadataTags.title??=iP(a);break;case"\xa9des":this.currentTrack||(this.metadataTags.description??=iP(a));break;case"\xa9ART":this.currentTrack||(this.metadataTags.artist??=iP(a));break;
1case"\xa9alb":this.currentTrack||(this.metadataTags.album??=iP(a));break;case"albr":this.currentTrack||(this.metadataTags.albumArtist??=iP(a));break;case"\xa9gen":this.currentTrack||(this.metadataTags.genre??=iP(a));break;case"\xa9day":if(!this.currentTrack){let e=new Date(iP(a));Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"\xa9cmt":this.currentTrack||(this.metadataTags.comment??=iP(a));break;case"\xa9lyr":this.currentTrack||(this.metadataTags.lyrics??=iP(a))}}break;case"meta":{if(this.currentTrack)break;let t=oP(e);this.currentMetadataKeys=new Map,0!==t?this.readContiguousBoxes(e.slice(r,i.contentSize)):this.readContiguousBoxes(e.slice(r+4,i.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);let t=oP(e);for(let i=0;i<t;i++){let t=oP(e);e.skip(4);let r=h.decode(oy(e,t-8));this.currentMetadataKeys.set(i+1,r)}}break;case"ilst":if(!this.currentMetadataKeys)break;for(let{boxInfo:t,slice:a}of this.iterateContiguousBoxes(e.slice(r,i.contentSize))){let e=t.name,i=(e.charCodeAt(0)<<24)+(e.charCodeAt(1)<<16)+(e.charCodeAt(2)<<8)+e.charCodeAt(3);this.currentMetadataKeys.has(i)&&(e=this.currentMetadataKeys.get(i));let r=iC(a);switch(this.metadataTags.raw??={},this.metadataTags.raw[e]??=r,e){case"\xa9nam":case"titl":case"com.apple.quicktime.title":case"title":"string"==typeof r&&(this.metadataTags.title??=r);break;case"\xa9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"==typeof r&&(this.metadataTags.description??=r);break;case"\xa9ART":case"com.apple.quicktime.artist":case"artist":"string"==typeof r&&(this.metadataTags.artist??=r);break;case"\xa9alb":case"albm":case"com.apple.quicktime.album":case"album":"string"==typeof r&&(this.metadataTags.album??=r);break;case"aART":case"album_artist":"string"==typeof r&&(this.metadataTags.albumArtist??=r);break;case"\xa9cmt":case"com.apple.quicktime.comment":case"comment":"string"==typeof r&&(this.metadataTags.comment??=r);break;case"\xa9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"==typeof r&&(this.metadataTags.genre??=r);break;case"\xa9lyr":case"lyrics":"string"==typeof r&&(this.metadataTags.lyrics??=r);break;case"\xa9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"==typeof r){let e=new Date(r);Number.isNaN(e.getTime())||(this.metadataTags.date??=e)}break;case"covr":case"com.apple.quicktime.artwork":r instanceof eD?(this.metadataTags.images??=[],this.metadataTags.images.push({data:r.data,kind:"coverFront",mimeType:r.mimeType})):r instanceof Uint8Array&&(this.metadataTags.images??=[],this.metadataTags.images.push({data:r,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"==typeof r){let e=r.split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(this.metadataTags.tracksTotal??=i)}break;case"trkn":if(r instanceof Uint8Array&&r.length>=6){let e=u(r),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(this.metadataTags.trackNumber??=t),i>0&&(this.metadataTags.tracksTotal??=i)}break;case"disc":case"disk":if(r instanceof Uint8Array&&r.length>=6){let e=u(r),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(this.metadataTags.discNumber??=t),i>0&&(this.metadataTags.discsTotal??=i)}}}}return e.filePos=o,!0}}class iO{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(),i=0;for(let r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}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;a(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 i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=iW(r,i),s=await this.fetchPacketForSampleIndex(a,t);return iQ(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=_(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<t.endTimestamp}},i,i,t):s}async getNextPacket(e,t){let i=this.packetToSampleIndex.get(e);if(void 0!==i)return this.fetchPacketForSampleIndex(i+1,t);let r=this.packetToFragmentLocation.get(e);if(void 0===r)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0};return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=iV(r,i),s=await this.fetchPacketForSampleIndex(a,t);return iQ(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};let r=R(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<t.endTimestamp}},i,i,t):s}async getNextKeyPacket(e,t){let i=this.packetToSampleIndex.get(e);if(void 0!==i){let e=iq(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),i);return this.fetchPacketForSampleIndex(e,t)}let r=this.packetToFragmentLocation.get(e);if(void 0===r)throw Error("Packet was not created from this track.");return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){let t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.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 a(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){let i;if(-1===e)return null;let r=iL(this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),e);if(!r)return null;if(t.metadataOnly)i=ig;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(t instanceof Promise&&(t=await t),!t)return null;if(i=oy(t,r.sampleSize),this.internalTrack.encryptionAuxInfo){a(this.internalTrack.encryptionInfo);let t=await iK(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<t.length&&(i=await iX(this.internalTrack,t[e],i,null))}}let s=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=r.duration/this.internalTrack.timescale,o=new ik(i,r.isKeyFrame?"key":"delta",s,n,e,r.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,i){let r;if(-1===t)return null;let s=e.trackData.get(this.internalTrack.id).samples[t];if(a(s),i.metadataOnly)r=ig;else{let t=this.internalTrack.demuxer.reader.requestSlice(s.byteOffset,s.byteSize);if(t instanceof Promise&&(t=await t),!t)return null;r=oy(t,s.byteSize),s.encryption&&(r=await iX(this.internalTrack,s.encryption,r,e))}let n=(s.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,o=s.duration/this.internalTrack.timescale,l=ne
1w ik(r,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,i,r,s){let n,o=this.internalTrack.demuxer,l=null,c=null,d=-1;if(e){let{sampleIndex:i,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,i,s);-1!==i&&(c=e,d=i)}let u=_(this.internalTrack.fragmentLookupTable,i,e=>e.timestamp),h=-1!==u?this.internalTrack.fragmentLookupTable[u]:null,m=_(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),f=-1!==m?this.internalTrack.fragmentPositionCache[m]:null,p=Math.max(h?.moofOffset??0,f?.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>r)break}let e=o.reader.requestSliceRange(n,8,16);if(e instanceof Promise&&(e=await e),!e)break;let i=n,a=iT(e);if(!a)break;if("moof"===a.name){let{sampleIndex:e,correctSampleFound:r}=t(l=await o.readFragment(i));if(r)return this.fetchPacketInFragment(l,e,s);-1!==e&&(c=l,d=e)}n=i+a.totalSize}if(h&&(!c||c.moofOffset<h.moofOffset)){let e=this.internalTrack.fragmentLookupTable[u-1];a(!e||e.timestamp<h.timestamp);let i=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,i,r,s)}return c?this.fetchPacketInFragment(c,d,s):null}}class iU extends iO{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&&tX(e.data)}}else{let e=await this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&t$(e.data)}let e={codec:e9(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 iN extends iO{constructor(e){super(e),this.decoderConfigPromise=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.decoderConfigPromise??=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&iu(e.data)}return{codec:tt(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}let iW=(e,t)=>{if(e.presentationTimestamps){let i=_(e.presentationTimestamps,t,e=>e.presentationTimestamp);return -1===i?-1:e.presentationTimestamps[i].sampleIndex}{let i=_(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===i)return -1;let r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},iV=(e,t)=>{if(!e.keySampleIndices)return iW(e,t);if(e.presentationTimestamps){let i=_(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===i)return -1;for(let t=i;t>=0;t--){let i=e.presentationTimestamps[t].sampleIndex;if(-1!==E(e.keySampleIndices,i,e=>e))return i}return -1}{let i=iW(e,t),r=_(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},iL=(e,t)=>{let i=_(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let s=r.startDecodeTimestamp+(t-r.startIndex)*r.delta,n=_(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.sampleToChunk,t,e=>e.startSampleIndex),d=e.sampleToChunk[c];a(d);let u=d.startChunkIndex+Math.floor((t-d.startSampleIndex)/d.samplesPerChunk),h=e.chunkOffsets[u],m=d.startSampleIndex+(u-d.startChunkIndex)*d.samplesPerChunk,f=0,p=h;if(1===e.sampleSizes.length)p+=l*(t-m),f+=l*d.samplesPerChunk;else for(let i=m;i<m+d.samplesPerChunk;i++){let r=e.sampleSizes[i];i<t&&(p+=r),f+=r}let g=r.delta;if(e.presentationTimestamps){let i=e.presentationTimestampIndexMap[t];a(void 0!==i),i<e.presentationTimestamps.length-1&&(g=e.presentationTimestamps[i+1].presentationTimestamp-s)}return{presentationTimestamp:s,duration:g,sampleOffset:p,sampleSize:l,chunkOffset:h,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==E(e.keySampleIndices,t,e=>e)}},iq=(e,t)=>{if(!e.keySampleIndices)return t+1;let i=_(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},iH=(e,t)=>{for(let i of(e.startTimestamp+=t,e.endTimestamp+=t,e.samples))i.presentationTimestamp+=t;for(let i of e.presentationTimestamps)i.presentationTimestamp+=t},ij=e=>{let[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?180/Math.PI*r:0},iQ=e=>0===e.sampleSizes.length,i$=e=>e.currentFragmentState?e.currentFragmentState.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleC
1ount:0,offset:null,resolved:null}:e.encryptionAuxInfo??={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null},iK=async(e,t,i)=>{if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{a(i.sampleSizes);for(let e=0;e<i.sampleCount;e++)r+=i.sampleSizes[e]}let s=e.requestSlice(i.offset,r);if(s instanceof Promise&&(s=await s),!s)throw Error("Failed to read auxiliary encryption info.");let n=t.defaultPerSampleIvSize;a(null!==n);let o=[];for(let e=0;e<i.sampleCount;e++){let r=i.defaultSampleInfoSize>0?i.defaultSampleInfoSize:i.sampleSizes[e],a=new Uint8Array(16);n>0?a.set(oy(s,n),0):a.set(t.defaultConstantIv,0);let l=null;if(r>n){let e=oT(s);l=[];for(let t=0;t<e;t++){let e=oT(s),t=oP(s);l.push({clearLen:e,protectedLen:t})}}o.push({iv:a,subsamples:l})}return i.resolved=o,o},iX=async(e,t,i,r)=>{let s;a(e.encryptionInfo);let n=e.encryptionInfo;a(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(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(o));for(let e=0;e<t.length-1;e++)for(let i=e+1;i<t.length;i++)ib(t[e],t[i])&&(t.splice(i,1),i--)}let i=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:o,psshBoxes:t});if(!("string"==typeof i&&32===i.length&&P.test(i)||i instanceof Uint8Array&&16===i.byteLength))throw TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return i instanceof Uint8Array?i:(e=>{a(e.length%2==0);let t=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)t[i/2]=parseInt(e.slice(i,i+2),16);return t})(i)})();e.demuxer.decryptionKeyCache.set(o,t),s=await t}return"cenc"===n.scheme||"cens"===n.scheme?iG(s,n,t,i):iY(s,n,t,i)},iG=async(e,t,i,r)=>{let s=new Uint8Array(16);s.set(i.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(!i.subsamples)return o(r);a(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);let l=iJ(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock),c=0;for(let e of l)for(let t of e.perSubsample)c+=t.length;let d=new Uint8Array(c),u=0;for(let e of l)for(let t of e.perSubsample)d.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;let h=await o(d),m=new Uint8Array(r),f=0;for(let e of l)for(let t of e.perSubsample)m.set(h.subarray(f,f+t.length),t.offset),f+=t.length;return m},iY=(e,t,i,r)=>{let s=new iD;s.init({key:e,iv:i.iv});let n=t.defaultCryptByteBlock,o=t.defaultSkipByteBlock;if(a(null!==n&&null!==o),!i.subsamples){let e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i<t;i++){let t=16*i;s.in.set(r.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(r),c=iJ(i.subsamples,n,o),d=new DataView(i.iv.buffer,i.iv.byteOffset,16);for(let e of c)for(let t of(s.iv[0]=d.getUint32(0,!1),s.iv[1]=d.getUint32(4,!1),s.iv[2]=d.getUint32(8,!1),s.iv[3]=d.getUint32(12,!1),e.perSubsample)){let e=t.length/16;for(let i=0;i<e;i++){let e=t.offset+16*i;s.in.set(r.subarray(e,e+16)),s.decrypt(),l.set(s.out,e)}}return l},iJ=(e,t,i)=>{let r=[],a=0!==t||0!==i,s=0;for(let n of e){s+=n.clearLen;let e=[];
1if(a){let r=n.protectedLen,a=s;for(;r>0&&!(r<16*t);){let s=16*t;e.push({offset:a,length:s}),a+=s;let n=Math.min(16*i,r-=s);a+=n,r-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;r.push({perSubsample:e})}return r};class iZ{constructor(e){this.value=e}}class i0{constructor(e){this.value=e}}class i1{constructor(e){this.value=e}}class i2{constructor(e){this.value=e}}!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"}(ab||(ab={}));let i3=[ab.EBML,ab.Segment],i4=[ab.SeekHead,ab.Info,ab.Cluster,ab.Tracks,ab.Cues,ab.Attachments,ab.Chapters,ab.Tags],i8=[...i3,...i4],i6=e=>{if(e<256)return 1;if(e<65536)return 2;if(e<0x1000000)return 3;if(e<0x100000000)return 4;if(e<0x10000000000)return 5;else return 6},i5=e=>{if(e<1n<<8n)return 1;if(e<1n<<16n)return 2;if(e<1n<<24n)return 3;if(e<1n<<32n)return 4;if(e<1n<<40n)return 5;else if(e<1n<<48n)return 6;else if(e<1n<<56n)return 7;else return 8},i7=e=>{if(e>=-64&&e<64)return 1;if(e>=-8192&&e<8192)return 2;if(e>=-1048576&&e<1048576)return 3;if(e>=-0x8000000&&e<0x8000000)return 4;if(e>=-0x400000000&&e<0x400000000)return 5;else return 6},i9=e=>{if(e<127)return 1;if(e<16383)return 2;if(e<2097151)return 3;if(e<0xfffffff)return 4;if(e<0x800000000-1)return 5;else if(e<0x40000000000-1)return 6;else throw Error("EBML varint size not supported "+e)};class re{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer),this.offsets=new WeakMap,this.dataOffsets=new WeakMap}writeByte(e){this.helperView.setUint8(0,e),this.writer.write(this.helper.subarray(0,1))}writeFloat32(e){this.helperView.setFloat32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeFloat64(e){this.helperView.setFloat64(0,e,!1),this.writer.write(this.helper)}writeUnsignedInt(e,t=i6(e)){let i=0;switch(t){case 6:this.helperView.setUint8(i++,e/0x10000000000|0);case 5:this.helperView.setUint8(i++,e/0x100000000|0);case 4:this.helperView.setUint8(i++,e>>24);case 3:this.helperView.setUint8(i++,e>>16);case 2:this.helperView.setUint8(i++,e>>8);case 1:this.helperView.setUint8(i++,e);break;default:throw Error("Bad unsigned int size "+t)}this.writer.write(this.helper.subarray(0,i))}writeUnsignedBigInt(e,t=i5(e)){let i=0;for(let r=t-1;r>=0;r--)this.helperView.setUint8(i++,Number(e>>BigInt(8*r)&255n));this.writer.write(this.helper.subarray(0,i))}writeSignedInt(e,t=i7(e)){e<0&&(e+=2**(8*t)),this.writeUnsignedInt(e,t)}writeVarInt(e,t=i9(e)){let i=0;switch(t){case 1:this.helperView.setUint8(i++,128|e);break;case 2:this.helperView.setUint8(i++,64|e>>8),this.helperView.setUint8(i++,e);break;case 3:this.helperView.setUint8(i++,32|e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 4:this.helperView.setUint8(i++,16|e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 5:this.helperView.setUint8(i++,8|e/0x100000000&7),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;case 6:this.helperView.setUint8(i++,4|e/0x10000000000&3),this.helperView.setUint8(i++,e/0x100000000|0),this.helperView.setUint8(i++,e>>24),this.helperView.setUint8(i++,e>>16),this.helperView.setUint8(i++,e>>8),this.helperView.setUint8(i++,e);break;default:throw Error("Bad EBML varint size "+t)}this.writer.write(this.helper.subarray(0,i))}writeAsciiString(e){this.writer.write(new Uint8Array(e.split("").map(e=>e.charCodeAt(0))))}writeEBML(e){if(null!==e)if(e instanceof Uint8Array)this.writer.write(e);else if(Array.isArray(e))for(let t of e)this.writeEBML(t);else if(this.offsets.set(e,this.writer.getPos()),this.writeUnsignedInt(e.id),Array.isArray(e.data)){let t=this.writer.getPos(),i=-1===e.size?1:e.size??4;-1===e.size?this.writeByte(255):this.writer.seek(this.writer.getPos()+i);let r=this.writer.getPos();if(this.dataOffsets.set(e,r),this.writeEBML(e.data),-1!==e.size){let e=this.writer.getPos()-r,a=this.writer.getPos();this.writer.seek(t),this.writeVarInt(e,i),this.writer.seek(a)}}else if("number"==typeof e.data){let t=e.size??i6(e.data);this.writeVarInt(t),this.writeUnsignedInt(e.data,t)}else if("bigint"==typeof e.data){let t=e.size??i5(e.data);this.writeVarInt(t),this.writeUnsignedBigInt(e.data,t)}else if("string"==typeof e.data)this.writeVarInt(e.data.length),this.writeAsciiString(e.data);else if(e.data instanceof Uint8Array)this.writeVarInt(e.data.byteLength,e.size),this.writer.write(e.data);else if(e.data instanceof iZ)this.writeVarInt(4),this.writeFloat32(e.data.value);else if(e.data instanceof i0)this.writeVarInt(8),this.writeFloat64(e.data.value);else if(e.data instanceof i1){let t=e.size??i7(e.data.value);this.writeVarInt(t),this.writeSignedInt(e.data.value,t)}else if(e.data instanceof i2){let t=m.encode(e.data.value);this.writeVarInt(t.length),this.writer.write(t)}else z(e.data)}}let rt=e=>{if(e.remainingLength<1)return null;let t=ow(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;(t&r)==0;)i++,r>>=1;return e.remainingLength<i?null:i},ri=e=>{if(e.remainingLength<1)return null;let t=ow(e);if(0===t)return null;let i=1,r=128;for(;(t&r)==0;)i++,r>>=1;if(e.remainingLength<i-1)return null;let a=t&r-1;for(let t=1;t<i;t++)a*=256,a+=ow(e);return a},rr=(e,t)=>{if(t<1||t>8)throw Error("Bad unsigned int size "+t);let i=0;for(let r=0;r<t;r++)i*=256,i+=ow(e);return i},ra=e=>{let t=rt(e);return null===t||e.remainingLength<t?null:rr(e,t)}
1,rs=e=>{if(e.remainingLength<1)return null;if(255===ow(e))return;e.skip(-1);let t=ri(e);return null===t?null:0x100000000000000!==t?t:void 0},rn=e=>{a(e.remainingLength>=2);let t=ra(e);if(null===t)return null;let i=rs(e);return null===i?null:{id:t,size:i}},ro=(e,t)=>{let i=oy(e,t),r=0;for(;r<t&&0!==i[r];)r+=1;return String.fromCharCode(...i.subarray(0,r))},rl=(e,t)=>{let i=oy(e,t),r=0;for(;r<t&&0!==i[r];)r+=1;return h.decode(i.subarray(0,r))},rc=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw Error("Bad float size "+t);return 4===t?oF(e):oM(e)},rd=async(e,t,i,r)=>{let a=new Set(i),s=t;for(;null===r||s<r;){let t=e.requestSliceRange(s,2,16);if(t instanceof Promise&&(t=await t),!t)break;let i=rn(t);if(!i)break;if(a.has(i.id))return{pos:s,found:!0};rm(i.size),s=t.filePos+i.size}return{pos:null!==r&&r>s?r:s,found:!1}},ru=async(e,t,i,r)=>{let a=new Set(i),s=t;for(;s<r;){let t=e.requestSliceRange(s,0,Math.min(65536,r-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=ra(t);if(null!==e&&a.has(e))return s;s++}}return null},rh={avc:"V_MPEG4/ISO/AVC",hevc:"V_MPEGH/ISO/HEVC",vp8:"V_VP8",vp9:"V_VP9",av1:"V_AV1",prores:"V_PRORES",aac:"A_AAC",mp3:"A_MPEG/L3",opus:"A_OPUS",vorbis:"A_VORBIS",flac:"A_FLAC",ac3:"A_AC3",eac3:"A_EAC3",dts:"A_DTS","pcm-u8":"A_PCM/INT/LIT","pcm-s16":"A_PCM/INT/LIT","pcm-s16be":"A_PCM/INT/BIG","pcm-s24":"A_PCM/INT/LIT","pcm-s24be":"A_PCM/INT/BIG","pcm-s32":"A_PCM/INT/LIT","pcm-s32be":"A_PCM/INT/BIG","pcm-f32":"A_PCM/FLOAT/IEEE","pcm-f64":"A_PCM/FLOAT/IEEE",webvtt:"S_TEXT/WEBVTT"};function rm(e){if(void 0===e)throw Error("Undefined element size is used in a place where it is not supported.")}let rf=e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");if(e.codecStrings.length>0){let i=[...new Set(e.codecStrings.filter(Boolean))];t+=`; codecs="${i.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"}(aT||(aT={})),function(e){e[e.Block=1]="Block",e[e.Private=2]="Private",e[e.Next=4]="Next"}(aS||(aS={})),function(e){e[e.Zlib=0]="Zlib",e[e.Bzlib=1]="Bzlib",e[e.lzo1x=2]="lzo1x",e[e.HeaderStripping=3]="HeaderStripping"}(aA||(aA={}));let rp=[{id:ab.SeekHead,flag:"seekHeadSeen"},{id:ab.Info,flag:"infoSeen"},{id:ab.Tracks,flag:"tracksSeen"},{id:ab.Cues,flag:"cuesSeen"}];class rg extends ip{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 rf({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 i=rn(t);if(!i)break;let r=i.id,a=i.size,s=t.filePos;if(r===ab.EBML){rm(a);let e=this.reader.requestSlice(s,a);if(e instanceof Promise&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===ab.Segment){if(await this.readSegment(s,a),void 0===a||null===this.reader.fileSize)break}else if(r===ab.Cluster){if(null===this.reader.fileSize)break;void 0===a&&(a=(await rd(this.reader,s,i8,this.reader.fileSize)).pos-s);let e=n(this.segments);e&&(e.elementEndPos=s+a)}rm(a),e=s+a}})()}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;null===this.currentSegment.elementEndPos||i<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(i,2,16);if(e instanceof Promise&&(e=await e),!e)break;let t=i,r=rn(e);if(!r||!i4.includes(r.id)&&r.id!==ab.Void){let e=await ru(this.reader,t,i4,Math.min(this.currentSegment.elementEndPos??1/0,t+0xa00000));if(e){i=e;continue}break}let{id:a,size:s}=r,n=e.filePos,o=rp.findIndex(e=>e.id===a);if(-1!==o){let e=rp[o].flag;this.currentSegment[e]=!0,rm(s);let t=this.reader.requestSlice(n,s);t instanceof Promise&&(t=await t),t&&this.readContiguousElements(t)}else if(a===ab.Tags||a===ab.Attachments){a===ab.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,rm(s);let e=this.reader.requestSlice(n,s);e instanceof Promise&&(e=await e),e&&this.readContiguousElements(e)}else if(a===ab.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=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 i=rp.find(e=>e.id===t.id);if(!i||this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,16);if(r instanceof Promise&&(r=await r),!r)continue;let a=rn(r);if(!a)continue;let{id:s,size:n}=a;if(s!==i.id)continue;rm(n),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.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 r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(let e of this.currentSegment.cuePoints){let t=r.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 i=e.cuePoints[t],r=e.cuePoints[t+1];i.time===r.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 i=this.reader.requestSliceRange(e,2,16);i instanceof Promise&&(i=await i),a(i);let r=rn(i);a(r),a(r.id===ab.Cluster);let s=r.size,o=i.filePos;void 0===s&&(s=(await rd(this.reader,o,i8,t.elementEndPos)).pos-o);let l=this.reader.requestSlice(o,s);l instanceof Promise&&(l=await l);let c={segment:t,elementStartPos:e,elementEndPos:o+s,dataStartPos:o,timestamp:-1,trackData:new Map};for(let[,t]of(this.currentCluster=c,l&&(c.elementEndPos=this.readContiguousElements(l,i8)),c.trackData)){let i=t.track;a(t.blocks.length>0);let r=!1;for(let e=0;e<t.blocks.length;e++){let i=t.blocks[e];i.timestamp+=c.timestamp,r||=i.lacing!==aT.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 r=t.presentationTimestamps[e],a=t.blocks[r.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!=i.defaultDuration&&a.lacing===aT.None&&(a.duration=i.defaultDuration)}r&&(this.expandLacedBlocks(t.blocks,i),t.presentationTimestamps=t.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));let s=t.blocks[t.presentationTimestamps[0].blockIndex],o=t.blocks[n(t.presentationTimestamps).blockIndex];t.startTimestamp=s.timestamp,t.endTimestamp=o.timestamp+o.duration;let l=_(i.clusterPositionCache,t.startTimestamp,e=>e.startTimestamp);(-1===l||i.clusterPositionCache[l].elementStartPos!==e)&&i.clusterPositionCache.splice(l+1,0,{elementStartPos:c.elementStartPos,startTimestamp:t.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){let r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){let r=e[i];if(r.lacing===aT.None)continue;r.decoded||(r.data=this.decodeBlockData(t,r.data),r.decoded=!0);let s=og.tempFromBytes(r.data),n=[],o=ow(s)+1;switch(r.lacing){case aT.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;s.bufferPos<s.length;){let i=ow(s);if(t+=i,i<255){n.push(t),e+=t;break}}}n.push(s.length-(s.bufferPos+e))}break;case aT.FixedSize:{let e=Math.floor((s.length-1)/o);for(let t=0;t<o;t++)n.push(e)}break;case aT.Ebml:{let e=ri(s);a(null!==e);let t=e;n.push(t);let i=t;for(let e=1;e<o-1;e++){let e=s.bufferPos,r=ri(s);a(null!==r),t+=r-((1<<7*(s.bufferPos-e)-1)-1),n.push(t),i+=t}n.push(s.length-(s.bufferPos+i))}break;default:a(!1)}a(n.length===o),e.splice(i,1);let l=r.duration||o*(t.defaultDuration??0);for(let t=0;t<o;t++){let a=oy(s,n[t]),c=r.timestamp+l*t/o,d=l/o;e.splice(i+t,0,{timestamp:c,duration:d,isKeyFrame:r.isKeyFrame,data:a,lacing:aT.None,decoded:!0,postProcessed:!1,mainAdditional:r.mainAdditional})}i+=o,i--}}async loadSegmentMetadata(e){for(let t of e.seekEntries){if((t.id!==ab.Tags||e.tagsSeen)&&(t.id!==ab.Attachments||e.attachmentsSeen))continue;let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,16);if(i instanceof Promise&&(i=await i),!i)continue;let r=rn(i);if(!r||r.id!==t.id)continue;let{size:s}=r;rm(s),a(!this.currentSegment),this.currentSegment=e;let n=this.reader.requestSlice(i.filePos,s);n instanceof Promise&&(n=await n),n&&this.readContiguousElements(n),this.currentSegment=null,t.id===ab.Tags?e.tagsSeen=!0:t.id===ab.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){let i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){let i=rn(e);if(!i||t&&t.includes(i.id))return!1;let{id:r,size:n}=i,o=e.filePos;switch(rm(n),r){case ab.DocType:this.isWebM="webm"===ro(e,n);break;case ab.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 ab.SeekID:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=rr(e,n)}break;case ab.SeekPosition:{let t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=rr(e,n)}break;case ab.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=rr(e,n),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case ab.Duration:if(!this.currentSegment)break;this.currentSegment.duration=rc(e,n);break;case ab.TrackEntry:if(!this.currentSegment||(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...eN,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!==aS.Block||e.data.algorithm!==aA.HeaderStripping)&&(eR._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===rh.avc)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPr
1ivate;else if(this.currentTrack.codecId===rh.hevc)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===rh.vp8)this.currentTrack.info.codec="vp8";else if(t===rh.vp9)this.currentTrack.info.codec="vp9";else if(t===rh.av1)this.currentTrack.info.codec="av1";else if(t===rh.prores){let e=this.currentTrack.codecPrivate?h.decode(this.currentTrack.codecPrivate):"";e4.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}let e=this.currentTrack;this.currentTrack.trackBacking=new ry(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===rh.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===rh.mp3?this.currentTrack.info.codec="mp3":t===rh.opus?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=48e3):t===rh.vorbis?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rh.flac?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rh.ac3?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rh.eac3?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===rh.dts?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"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 rw(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case ab.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=rr(e,n);break;case ab.TrackType:{if(!this.currentTrack)break;let t=rr(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,dtsFormat:null})}break;case ab.FlagEnabled:if(!this.currentTrack)break;rr(e,n)||(this.currentTrack=null);break;case ab.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!rr(e,n);break;case ab.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!rr(e,n);break;case ab.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!rr(e,n);break;case ab.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!rr(e,n);break;case ab.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!rr(e,n);break;case ab.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!rr(e,n);break;case ab.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=ro(e,n);break;case ab.CodecPrivate:if(!this.currentTrack)break;
1this.currentTrack.codecPrivate=oy(e,n);break;case ab.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=rr(e,n);break;case ab.Name:if(!this.currentTrack)break;this.currentTrack.name=rl(e,n);break;case ab.Language:if(!this.currentTrack||this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=ro(e,n),K(this.currentTrack.languageCode)||(this.currentTrack.languageCode="und");break;case ab.LanguageBCP47:{if(!this.currentTrack)break;let t=ro(e,n).split("-")[0];t?this.currentTrack.languageCode=t:this.currentTrack.languageCode="und",this.currentTrack.hasLanguageBcp47=!0}break;case ab.Video:if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,n));break;case ab.PixelWidth:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.width=rr(e,n);break;case ab.PixelHeight:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.height=rr(e,n);break;case ab.DisplayWidth:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayWidth=rr(e,n);break;case ab.DisplayHeight:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayHeight=rr(e,n);break;case ab.DisplayUnit:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.displayUnit=rr(e,n);break;case ab.AlphaMode:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.alphaMode=1===rr(e,n);break;case ab.Colour:if(this.currentTrack?.info?.type!=="video")break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(o,n));break;case ab.MatrixCoefficients:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=T[rr(e,n)]??null;this.currentTrack.info.colorSpace.matrix=t}break;case ab.Range:if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===rr(e,n);break;case ab.TransferCharacteristics:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=w[rr(e,n)]??null;this.currentTrack.info.colorSpace.transfer=t}break;case ab.Primaries:{if(this.currentTrack?.info?.type!=="video"||!this.currentTrack.info.colorSpace)break;let t=k[rr(e,n)]??null;this.currentTrack.info.colorSpace.primaries=t}break;case ab.Projection:if(this.currentTrack?.info?.type!=="video")break;this.readContiguousElements(e.slice(o,n));break;case ab.ProjectionPoseRoll:{if(this.currentTrack?.info?.type!=="video")break;let t=rc(e,n);try{this.currentTrack.info.rotation=s(-t)}catch{}}break;case ab.Audio:if(this.currentTrack?.info?.type!=="audio")break;this.readContiguousElements(e.slice(o,n));break;case ab.SamplingFrequency:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.sampleRate=rc(e,n);break;case ab.Channels:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.numberOfChannels=rr(e,n);break;case ab.BitDepth:if(this.currentTrack?.info?.type!=="audio")break;this.currentTrack.info.bitDepth=rr(e,n);break;case ab.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(o,n)),this.currentCueTime=null;break;case ab.CueTime:this.currentCueTime=rr(e,n);break;case ab.CueTrackPositions:{if(null===this.currentCueTime)break;a(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 ab.CueTrack:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=rr(e,n)}break;case ab.CueClusterPosition:{let t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;a(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+rr(e,n)}break;case ab.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=rr(e,n);break;case ab.SimpleBlock:{if(!this.currentCluster)break;let t=ri(e);if(null===t)break;let i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;let r=oA(e),a=ow(e),s=!!(128&a);i.track.info?.type==="audio"&&i.track.info.codec&&(s=!0);
1let l=oy(e,n-(e.filePos-o)),c=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:s,data:l,lacing:a>>1&3,decoded:!c,postProcessed:!1,mainAdditional:null})}break;case ab.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(o,n)),this.currentBlock=null;break;case ab.Block:{if(!this.currentCluster)break;let t=ri(e);if(null===t)break;let i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;let r=oA(e),a=ow(e),s=oy(e,n-(e.filePos-o)),l=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:a>>1&3,decoded:!l,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case ab.BlockAdditions:this.readContiguousElements(e.slice(o,n));break;case ab.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 ab.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=oy(e,n);break;case ab.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=rr(e,n);break;case ab.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=rr(e,n);break;case ab.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case ab.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(o,n));break;case ab.Targets:this.readContiguousElements(e.slice(o,n));break;case ab.TargetTypeValue:50!==rr(e,n)&&(this.currentTagTargetIsMovie=!1);break;case ab.TagTrackUID:case ab.TagEditionUID:case ab.TagChapterUID:case ab.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case ab.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(o,n));break;case ab.TagName:this.currentSimpleTagName=rl(e,n);break;case ab.TagString:{if(!this.currentSimpleTagName)break;let t=rl(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case ab.TagBinary:{if(!this.currentSimpleTagName)break;let t=oy(e,n);this.processTagValue(this.currentSimpleTagName,t)}break;case ab.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 ez(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,i="unknown";if(e){let t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??=[],t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case ab.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw Error("Bad unsigned int size "+t);let i=0n;for(let r=0;r<t;r++)i<<=8n,i+=BigInt(ow(e));return i})(e,n);break;case ab.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=rl(e,n);break;case ab.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=ro(e,n);break;case ab.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=oy(e,n);break;case ab.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=rl(e,n);break;case ab.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(o,n)),this.currentTrack.decodingInstructions.sort((e,t)=>
1t.order-e.order);break;case ab.ContentEncoding:this.currentDecodingInstruction={order:0,scope:aS.Block,data:null},this.readContiguousElements(e.slice(o,n)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case ab.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=rr(e,n);break;case ab.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=rr(e,n);break;case ab.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:aA.Zlib,settings:null},this.readContiguousElements(e.slice(o,n));break;case ab.ContentCompAlgo:if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.algorithm=rr(e,n);break;case ab.ContentCompSettings:if(this.currentDecodingInstruction?.data?.type!=="decompress")break;this.currentDecodingInstruction.data.settings=oy(e,n);break;case ab.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=o+n,!0}decodeBlockData(e,t){a(e.decodingInstructions.length>0);let i=t;for(let t of e.decodingInstructions)if(a(t.data),"decompress"===t.data.type&&t.data.algorithm===aA.HeaderStripping&&t.data.settings&&t.data.settings.length>0){let e=t.data.settings,r=new Uint8Array(e.length+i.length);r.set(e,0),r.set(i,e.length),i=r}return i}processTagValue(e,t){if(!this.currentSegment?.metadataTags)return;let i=this.currentSegment.metadataTags;if(i.raw??={},i.raw[e]??=t,"string"==typeof t)switch(e.toLowerCase()){case"title":i.title??=t;break;case"description":i.description??=t;break;case"artist":i.artist??=t;break;case"album":i.album??=t;break;case"album_artist":i.albumArtist??=t;break;case"genre":i.genre??=t;break;case"comment":i.comment??=t;break;case"lyrics":i.lyrics??=t;break;case"date":{let e=new Date(t);Number.isNaN(e.getTime())||(i.date??=e)}break;case"track_number":case"part_number":{let e=t.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(i.trackNumber??=r),a&&Number.isInteger(a)&&a>0&&(i.tracksTotal??=a)}break;case"disc_number":case"disc":{let e=t.split("/"),r=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(r)&&r>0&&(i.discNumber??=r),a&&Number.isInteger(a)&&a>0&&(i.discsTotal??=a)}}}}class rk{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(),i=0;for(let r of e.segments)for(let e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}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,i=await this.getFirstPacket({metadataOnly:!0});return t+(i?.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 i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=_(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i<t.endTimestamp}},i,i,t)}async getNextPacket(e,t){let i=this.packetToClusterLocation.get(e);if(void 0===i)throw Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,e=>{if(e===i.cluster){let t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1<t.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0};return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){let i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{let t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};let r=R(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i<t.endTimestamp}},i,i,t)}async getNextKeyPacket(e,t){let i=this.packetToClusterLocation.get(e);if(void 0===i)throw Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,e=>{if(e===i.cluster){let t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>i.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{let t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){let e=t.blocks.findIndex(e=>e.isKeyFrame);return a(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(-1===t)return null;let r=e.trackData.get(this.internalTrack.id).blocks[t];if(a(r),r.decoded||(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),r.decoded=!0),!r.postProcessed){if(this.internalTrack.info?.codec==="prores"&&!(r.data.length>=8&&105===r.data[4]&&99===r.data[5]&&112===r.data[6]&&102===r.data[7])){let e=new Uint8Array(r.data.length+8);u(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(r.data,8),r.data=e}r.postProcessed=!0}let s=i.metadataOnly?ig:r.data,n=r.timestamp/this.internalTrack.segment.timestampFactor,o=r.duration/this.internalTrack.segment.timestampFactor,l={};r.mainAdditional&&this.internalTrack.info?.type==="video"&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?ig:r.mainAdditional,l.alphaByteLength=r.mainAdditional.byteLength);let c=new ik(s,r.isKeyFrame?"key":"delta",n,o,e.dataStartPos+t,r.data.byteLength,l);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,i,r,s){let n,{demuxer:o,segment:l}=this.internalTrack,c=null,d=null,u=-1;if(e){let{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,s);-1!==i&&(d=e,u=i)}let h=_(this.internalTrack.cuePoints,i,e=>e.time),m=-1!==h?this.internalTrack.cuePoints[h]:null,f=_(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),p=-1!==f?this.internalTrack.clusterPositionCache[f]:null,g=Math.max(m?.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>r)break}let e=o.reader.requestSliceRange(n,2,16);if(e instanceof Promise&&(e=await e),!e)break;let i=n,h=rn(e);if(!h||!i4.includes(h.id)&&h.id!==ab.Void){let e=await ru(o.reader,i,i4,Math.min(l.elementEndPos??1/0,i+0xa00000));if(e){n=e;continue}break}let m=h.id,f=h.size,p=e.filePos;if(m===ab.Cluster){f=(c=await o.readCluster(i,l)).elementEndPos-p;let{blockIndex:e,correctBlockFound:r}=t(c);if(r)return this.fetchPacketInCluster(c,e,s);-1!==e&&(d=c,u=e)}void 0===f&&(a(m!==ab.Cluster),f=(await rd(o.reader,p,i8,l.elementEndPos)).pos-p);let g=p+f;if(null===l.elementEndPos){let e=o.reader.requestSliceRange(g,2,16);if(e instanceof Promise&&(e=await e),!e)break;if(ra(e)===ab.Segment){l.elementEndPos=g;break}}n=g}if(m&&(!d||d.elementStartPos<m.clusterPosition)){let e=this.internalTrack.cuePoints[h-1];a(!e||e.time<m.time);let i=e?.time??-1/0;return this.performClusterLookup(null,t,i,r,s)}return d?this.fetchPacketInCluster(d,u,s):null}}class ry extends rk{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:e9({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?tB(e.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&e?tN(e.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&e?t$(e.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&e?tX(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 rw extends rk{constructor(e){super(e),this.decoderConfigPromise=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.decoderConfigPromise??=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){let e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&iu(e.data)}return{codec:tt({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})():null}}let rb=async(e,t,i,r=null)=>{let a=t;for(;null===i||a<i;){let t=null!==i?Math.min(65536,i-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,i=ty(oP(s),null!==e.fileSize?e.fileSize-a:null);if(i.header&&(!r||i.header.sampleRate===r.sampleRate&&i.header.mpegVersionId===r.mpegVersionId&&i.header.layer===r.layer&&tb(i.header.channel)===tb(r.channel)))return{header:i.header,startPos:a};s.filePos=t+i.bytesAdvanced,a=s.filePos}}return null};class rT extends ip{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 v,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 rS(this)]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,oO);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=oV(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=await rb(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 i=tk(t.mpegVersionId,t.channel),r=this.reader.requestSlice(e.startPos+i,4);if(r instanceof Promise&&(r=await r),r){let a=oP(r);if(0x58696e67===a||0x496e666f===a){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(t instanceof Promise&&(t=await t),t){let e=u(oy(t,12)),i=e.getUint32(0,!1);this.xingData={frameCount:i&ap.FrameCount?e.getUint32(4,!1):null,fileSize:i&ap.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 i=this.reader.requestSlice(e,oO);if(i instanceof Promise&&(i=await i),!i)break;let r=oV(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);
1if(a instanceof Promise&&(a=await a),!a)break;oL(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=oz){let e=this.reader.requestSlice(this.reader.fileSize-oz,oz);e instanceof Promise&&(e=await e),a(e);let t=oR(e,3);"TAG"===t&&oN(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class rS{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return a(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(a(null!==e.firstFrameHeader),a(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){var t,i,r,s;let a=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,s=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(s<<t):2===i?144*r/s:12*r/s*4);return Math.round((e.reader.fileSize-e.firstFrameHeaderPos)/a)*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 a(this.demuxer.firstFrameHeader),tb(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return a(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...eN}}async getDecoderConfig(){return a(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:tb(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){let i;if(-1===e)return null;let r=this.demuxer.loadedSamples[e];if(!r)return null;if(t.metadataOnly)i=ig;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=oy(e,r.dataSize)}return new ik(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{let i=E(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw Error("Packet was not created from this track.");let r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let rA=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;rA[e]=t>>>0}let rv=e=>{let t=u(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let t=0;t<e.length;t++)r=(r<<8^rA[r>>>24^e[t]])>>>0;return t.setUint32(22,i,!0),r},rP=(e,t,i)=>{let r=0,s=null;if(e.length>0)if("vorbis"===t.codec){a(t.vorbisInfo);let n=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,o=(e[0]&n)>>1;if(o>=t.vorbisInfo.modeBlockflags.length)throw Error("Invalid mode number.");let l=i,c=t.vorbisInfo.modeBlockflags[o];if(s=t.vorbisInfo.blocksizes[c],1===c){let i=e[0]&(1|n)+1?1:0;l=t.vorbisInfo.blocksizes[i]}r=null!==l?l+s>>2:0}else"opus"===t.codec&&(r=(e=>{let t,i=e[0]>>3,r=3&e[0];return t=0===r?1:1===r||2===r?2:63&e[1],{durationInSamples:tY[i]*t}})(e).durationInSamples);return{durationInSamples:r,vorbisBlockSize:s}},rC=e=>{let t="audio/ogg";if(e.codecStrings){let i=[...new Set(e.codecStrings)];t+=`; codecs="${i.join(", ")}"`}return t},rx=e=>{let t=e.filePos;if(0x5367674f!==oC(e))return null;e.skip(1);let i=ow(e),r=oB(e),a=oC(e),s=oC(e),n=oC(e),o=ow(e),l=new Uint8Array(o);for(let t=0;t<o;t++)l[t]=ow(e);let c=27+o,d=l.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:c+d,dataStartPos:t+c,dataSize:d,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:l}},rE=(e,t)=>{for(;e.filePos<t-3;){let t=oC(e),i=255&t,r=t>>>8&255,a=t>>>16&255,s=t>>>24&255;if(79===i||79===r||79===a||79===s){if(e.skip(-4),0x5367674f===t)return!0;e.skip(1)}}return!1};class r_ extends ip{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 i=rx(t);if(!i||!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(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 rI(e,this)))}})()}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;let r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r||!(i=await this.findNextPacketStart(r)))return;let a=await this.readPacket(i.startPage,i.startSegmentIndex);if(!a||3!==r.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(r.data.length);let o=new Uint8Array(1+s.length+e.data.length+r.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;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:tJ(a.data).modeBlockflags},t0(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;let r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;let a=tG(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=48e3,t.codecInfo.opusInfo={preSkip:a.preSkip},t0(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){a(t<e.lacingValues.length);let i=0;for(let r=0;r<t;r++)i+=e.lacingValues[r];let r=e,s=i,n=t,o=[];t:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);t instanceof Promise&&(t=await t),a(t);let l=oy(t,r.dataSize);for(;;){if(n===r.lacingValues.length){o.push(l.subarray(i,s));break}let e=r.lacingValues[n];if(s+=e,e<255){o.push(l.subarray(i,s));break t}n++}let c=r.headerStartPos+r.totalSize;
1for(;;){let t=this.reader.requestSliceRange(c,27,282);if(t instanceof Promise&&(t=await t),!t)return null;let i=rx(t);if(!i)return null;if((r=i).serialNumber===e.serialNumber)break;c=r.headerStartPos+r.totalSize}i=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),d=0;for(let e=0;e<o.length;e++){let t=o[e];c.set(t,d),d+=t.length}return{data:c,endPage:r,endSegmentIndex:n}}async findNextPacketStart(e){if(e.endSegmentIndex<e.endPage.lacingValues.length-1)return{startPage:e.endPage,startSegmentIndex:e.endSegmentIndex+1};if(4&e.endPage.headerType)return null;let t=e.endPage.headerStartPos+e.endPage.totalSize;for(;;){let i=this.reader.requestSliceRange(t,27,282);if(i instanceof Promise&&(i=await i),!i)return null;let r=rx(i);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){return await this.readMetadata(),rC({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 rI{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new v,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 a(-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 a(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{...eN,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(a(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;let{durationInSamples:r,vorbisBlockSize:a}=rP(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new ik(i.metadataOnly?ig:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),s}async getFirstPacket(e){a(this.bitstream.lastMetadataPacket);let t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(a(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);let r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){let i=this.encodedPacketToMetadata.get(e);if(!i)throw Error("Packet was not created from this track.");let r=await this.demuxer.findNextPacketStart(i.packet);if(!r)return null;let a=i.timestampInSamples+i.durationInSamples,s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){let i,r;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;a(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 i=Math.min(t+65307,l-27),r=this.demuxer.reader.requestSlice(t,i-t);if(r instanceof Promise&&(r=await r),a(r),!rE(r,i)){l=e+27;continue t}let n=this.demuxer.reader.requestSliceRange(r.filePos,27,282);n instanceof Promise&&(n=await n),a(n);let d=rx(n);a(d);let u=!1;if(d.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(d.headerStartPos,d.totalSize);e instanceof Promise&&(e=await e),a(e),u=rv(oy(e,d.totalSize))===d.checksum}if(!u){t=d.headerStartPos+4;continue}if(u&&d.serialNumber!==this.bitstream.serialNumber||-1===d.granulePosition){t=d.headerStartPos+d.totalSize;continue}this.granulePositionToTimestampInSamples(d.granulePosition)>s?l=d.headerStartPos:(o=d,c.push(d));continue t}}let d=n.startPage;for(let e of c){if(e.granulePosition===o.granulePosition)break;(!d||e.headerStartPos>d.headerStartPos)&&(d=e)}let u=d,h=[u];for(;u.serialNumber!==this.bitstream.serialNumber||u.granulePosition!==o.granulePosition;){let e=u.headerStartPos+u.totalSize,t=this.demuxer.reader.requestSliceRange(e,27,282);t instanceof Promise&&(t=await t),a(t);let i=rx(t);a(i),(u=i).serialNumber===this.bitstream.serialNumber&&h.push(u)}a(-1!==u.granulePosition);let m=null,f=u,p=0;if(u.headerStartPos===n.startPage.headerStartPos)i=this.granulePositionToTimestampInSamples(0),r=!0,m=0;else{i=0,r=!1;for(let e=u.lacingValues.length-1;e>=0;e--)if(u.lacingValues[e]<255){m=e+1;break}if(null===m)throw Error("Invalid page with granule position: no packets end on this page.");let e={data:ig,endPage:f,endSegmentIndex:p=m-1};if(await this.demuxer.findNextPacketStart(e)){let e=rF(h,u,m);a(e);let t=rB(h,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){let e=rF(h,u,m);if(!e)break;let t=rB(h,e.page,e.segmentIndex);if(!t)break;
1if(u=t.page,m=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,p=e.segmentIndex;break}}}let g=null,k=null;for(;null!==u;){a(null!==m);let e=await this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===n.startPage.headerStartPos&&m<n.startSegmentIndex)){let n=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:i,vorbisLastBlocksize:k?.vorbisBlockSize??null},t);a(n);let o=this.encodedPacketToMetadata.get(n);if(a(o),r||e.endPage.headerStartPos!==f.headerStartPos||e.endSegmentIndex!==p?i+=o.durationInSamples:(i=this.granulePositionToTimestampInSamples(u.granulePosition),r=!0,a(n=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:i-o.durationInSamples,vorbisLastBlocksize:k?.vorbisBlockSize??null},t)),a(o=this.encodedPacketToMetadata.get(n))),g=n,k=o,r&&(Math.max(i,0)>s||Math.max(o.timestampInSamples,0)===s))break}let o=await this.demuxer.findNextPacketStart(e);if(!o)break;u=o.startPage,m=o.startSegmentIndex}return g}async getPacketSequential(e,t){let i=await this.sequentialScanMutex.acquire();try{let i,r=V(e*this.internalSampleRate);e=r/this.internalSampleRate;let s=_(this.sequentialScanCache,r,e=>e.timestampInSamples);if(-1!==s){let e=this.sequentialScanCache[s];i=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else i=await this.getFirstPacket(t);let o=0;for(;i&&i.timestamp<e;){let r=await this.getNextPacket(i,t);if(!r||r.timestamp>e)break;if(i=r,o++,100===o){o=0;let e=this.encodedPacketToMetadata.get(i);a(e),this.sequentialScanCache.length>0&&a(n(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return i}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let rB=(e,t,i)=>{let r=t,s=i;t:for(;;){for(s--;s>=0;s--)if(r.lacingValues[s]<255){s++;break t}if(a(-1===s),!(1&r.headerType)){s=0;break}let t=M(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;s=(r=t).lacingValues.length}if(a(-1!==s),s===r.lacingValues.length){let t=e[e.indexOf(r)+1];a(t),r=t,s=0}return{page:r,segmentIndex:s}},rF=(e,t,i)=>{if(i>0)return{page:t,segmentIndex:i-1};let r=M(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};!function(e){e[e.PCM=1]="PCM",e[e.IEEE_FLOAT=3]="IEEE_FLOAT",e[e.ALAW=6]="ALAW",e[e.MULAW=7]="MULAW",e[e.EXTENSIBLE=65534]="EXTENSIBLE"}(av||(av={}));class rM extends ip{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),a(e);let t=oR(e,4),i="RIFX"!==t,r="RF64"===t,s=ov(e,i),n=r?this.reader.fileSize:Math.min(s+8,this.reader.fileSize??1/0);if("WAVE"!==oR(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=oR(e,4),a=ov(e,i),s=e.filePos;if(r&&0===o&&"ds64"!==t)throw Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===t)await this.parseFmtChunk(s,a,i);else if("data"===t){if(l??=a,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,a);if(e instanceof Promise&&(e=await e),!e)break;let t=oE(e,i);l=oE(e,i),n=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(s,a,i):("ID3 "===t||"id3 "===t)&&await this.parseId3Chunk(s,a);c=s+a+(1&a),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 d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new rR(this))})()}async parseFmtChunk(e,t,i){let r,a=this.reader.requestSlice(e,t);if(a instanceof Promise&&(a=await a),!a)return;let s=ob(a,i),n=ob(a,i),o=ov(a,i);a.skip(4);let l=ob(a,i);if((r=14===t?8:ob(a,i),t>=18&&357!==s)&&Math.min(t-18,ob(a,i))>=22&&s===av.EXTENSIBLE){a.skip(6);let e=oy(a,16);s=e[0]|e[1]<<8}if((s===av.MULAW||s===av.ALAW)&&(r=8),s!==av.PCM&&s!==av.IEEE_FLOAT&&s!==av.ALAW&&s!==av.MULAW)throw Error(`Unsupported WAVE codec (format tag ${s}). Only integer/float PCM, A-law, and μ-law are supported.`);if(s===av.PCM&&![8,16,24,32].includes(r))throw Error(`Unsupported WAVE PCM bit depth (${r}). Only 8, 16, 24, and 32 bits are supported.`);if(s===av.IEEE_FLOAT&&![32,64].includes(r))throw Error(`Unsupported WAVE float bit depth (${r}). Only 32 and 64 bits are supported.`);this.audioInfo={format:s,numberOfChannels:n,sampleRate:o,sampleSizeInBytes:Math.ceil(r/8),blockSizeInBytes:l}}async parseListChunk(e,t,i){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=await r),!r)return;let a=oR(r,4);if("INFO"!==a&&"INF0"!==a)return;let s=r.filePos;for(;s<=e+t-8;){r.filePos=s;let e=oR(r,4),t=ov(r,i),a=oy(r,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),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(this.metadataTags.trackNumber??=t),i&&Number.isInteger(i)&&i>0&&(this.metadataTags.tracksTotal??=i)}break;case"ICRD":case"IDIT":{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 i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=await i),!i)return;let r=oV(i);if(r){let a=t-oO;r.size=Math.min(r.size,a),r.size>0&&oL(i.slice(e+oO,r.size),r,this.metadataTags)}}getCodec(){if(a(this.audioInfo),this.audioInfo.format===av.MULAW)return"ulaw";if(this.audioInfo.format===av.ALAW)return"alaw";if(this.audioInfo.format===av.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===av.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";else if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}a(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class rR{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return a(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){let e=this.demuxer.getCodec();return e?(a(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return a(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return a(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return a(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 a(-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{...eN}}async getPacketAtIndex(e,t){let i;a(e>=0),a(this.demuxer.audioInfo);let r=2048*e*this.demuxer.audioInfo.blockSizeInBytes;if(r>=this.demuxer.dataSize)return null;let s=Math.min(2048*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-r);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);if(e instanceof Promise&&(e=await e),!e)return null}if(t.metadataOnly)i=ig;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+r,s);e instanceof Promise&&(e=await e),a(e),i=oy(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 ik(i,"key",n,o,e,s)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){a(this.demuxer.audioInfo);let i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/2048,(this.demuxer.dataSize-1)/(2048*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;let r=await this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;a(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){a(this.demuxer.audioInfo);let i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/2048);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let rD=e=>{let t=e.filePos,i=new eW(oy(e,9));if(4095!==i.readBits(12)||(i.skipBits(1),0!==i.readBits(2)))return null;let r=i.readBits(1),a=i.readBits(2)+1,s=i.readBits(4);if(15===s)return null;i.skipBits(1);let n=i.readBits(3);if(0===n)throw Error("ADTS frames with channel configuration 0 are not supported.");i.skipBits(1),i.skipBits(1),i.skipBits(1),i.skipBits(1);let o=i.readBits(13);i.skipBits(11);let l=i.readBits(2)+1;if(1!==l)throw Error("ADTS frames with more than one AAC frame are not supported.");let c=null;return 1===r?e.filePos-=2:c=i.readBits(16),{objectType:a,samplingFrequencyIndex:s,channelConfiguration:n,frameLength:o,numberOfAacFrames:l,crcCheck:c,startPos:t}};class rz extends ip{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new v,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();a(this.firstFrameHeader),this.trackBackings=[new rO(this)]})()}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,oO);if(e instanceof Promise&&(e=await e),!e){this.lastSampleLoaded=!0;return}let t=oV(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=rD(e);if(!t||null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize){this.lastSampleLoaded=!0;return}this.firstFrameHeader||(this.firstFrameHeader=t);let i=eV[t.samplingFrequencyIndex];a(void 0!==i);let r={timestamp:this.nextTimestampInSamples/i,duration:1024/i,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(r),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,oO);if(t instanceof Promise&&(t=await t),!t)break;let i=oV(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(r instanceof Promise&&(r=await r),!r)break;oL(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class rO{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}
1getTimeResolution(){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 a(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){a(this.demuxer.firstFrameHeader);let e=eL[this.demuxer.firstFrameHeader.channelConfiguration];return a(void 0!==e),e}getSampleRate(){a(this.demuxer.firstFrameHeader);let e=eV[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return a(void 0!==e),e}getDisposition(){return{...eN}}async getDecoderConfig(){return a(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){let i;if(-1===e)return null;let r=this.demuxer.loadedSamples[e];if(!r)return null;if(t.metadataOnly)i=ig;else{let e=this.demuxer.reader.requestSlice(r.dataStart,r.dataSize);if(e instanceof Promise&&(e=await e),!e)return null;i=oy(e,r.dataSize)}return new ik(i,"key",r.timestamp,r.duration,e,r.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{let i=E(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw Error("Packet was not created from this track.");let r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded||i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}let rU=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},rN=e=>{let t=0,i=new eW(oy(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);let r=[],a=t-1,s=new eW(oy(e,a)),n=8-t-1;for(let e=0;e<n;e++)r.unshift(i.readBits(1));for(let e=0;e<a;e++)for(let e=0;e<8;e++){let t=s.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,i)=>e|t<<i,0)},rW=(e,t)=>"uncommon-u16"===t?oT(e)+1:"uncommon-u8"===t?ow(e)+1:"number"==typeof t?t:void(z(t),a(!1));class rV extends ip{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 v,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),a(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,oO);if(t instanceof Promise&&(t=await t),!t){this.lastSampleLoaded=!0;return}let i=oV(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);r instanceof Promise&&(r=await r),a(r),oL(r,i,this.metadataTags),e=t.filePos+i.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.`);a(t);let i=ow(t),r=oS(t),s=(128&i)!=0;switch(127&i){case aw.STREAMINFO:{let t=this.reader.requestSlice(e,r);if(t instanceof Promise&&(t=await t),a(t),null===t)throw Error(`StreamInfo block at position ${e} is too small! Corrupted file.`);let i=oy(t,34),s=new eW(i),n=s.readBits(16),o=s.readBits(16),l=s.readBits(24),c=s.readBits(24),d=s.readBits(20),u=s.readBits(3)+1;s.readBits(5);let h=s.readBits(36);s.skipBits(128);let m=new Uint8Array(42);m.set(new Uint8Array([102,76,97,67]),0),m.set(new Uint8Array([128,0,0,34]),4),m.set(i,8),this.audioInfo={numberOfChannels:u,sampleRate:d,totalSamples:h,minimumBlockSize:n,maximumBlockSize:o,minimumFrameSize:l,maximumFrameSize:c,description:m},this.trackBacking=new rL(this);break}case aw.VORBIS_COMMENT:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),a(t),t0(oy(t,r),this.metadataTags);break}case aw.PICTURE:{let t=this.reader.requestSlice(e,r);t instanceof Promise&&(t=await t),a(t);let i=oP(t),s=oP(t),n=h.decode(oy(t,s)),o=oP(t),l=h.decode(oy(t,o));t.skip(16);
1let c=oP(t),d=oy(t,c);this.metadataTags.images??=[],this.metadataTags.images.push({data:d,mimeType:n,kind:3===i?"coverFront":4===i?"coverBack":"unknown",description:l})}}if(e+=r,s){this.lastLoadedPos=e;break}}if(!this.audioInfo)throw Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})()}async readNextFlacFrame({startPos:e,isFirstPacket:t}){a(this.audioInfo);let i=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,r=this.audioInfo.minimumFrameSize||10,s=this.audioInfo.maximumFrameSize||i,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+r;;){if(n.filePos>n.end-6)return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:n.end-e,isLastFrame:!0};if(255===ow(n)){let t=n.filePos;if(ow(n)!==(1===this.blockingBit?249:248)){n.filePos=t;continue}n.skip(-2);let i=n.filePos-e,r=this.readFlacFrameHeader({slice:n,isFirstPacket:!1});if(!r){n.filePos=t;continue}if(0===this.blockingBit){if(r.num-o.num!=1){n.filePos=t;continue}}else if(r.num-o.num!==o.blockSize){n.filePos=t;continue}return{num:o.num,blockSize:o.blockSize,sampleRate:o.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){let i=e.filePos,r=new eW(oy(e,4));if(32764!==r.readBits(15))return null;if(null===this.blockingBit){a(t);let e=r.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){if(a(!t),1!==r.readBits(1))return null}else if(0===this.blockingBit){if(a(!t),0!==r.readBits(1))return null}else throw Error("Invalid blocking bit");let s=rU(r.readBits(4));if(!s)return null;a(this.audioInfo);let n=((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}})(r.readBits(4),this.audioInfo.sampleRate);if(!n||(r.readBits(4),r.readBits(3),0!==r.readBits(1)))return null;let o=rN(e),l=rW(e,s),c="uncommon-u16"===n?oT(e):"uncommon-u16-10"===n?10*oT(e):"uncommon-u8"===n?ow(e):"number"==typeof n?n:null;if(null===c||c!==this.audioInfo.sampleRate)return null;let d=e.filePos-i,u=ow(e);return(e.skip(-d),e.skip(-1),u!==(e=>{let t=0;for(let i of e){t^=i;for(let e=0;e<8;e++)(128&t)!=0?t=t<<1^7:t<<=1,t&=255}return t})(oy(e,d)))?null:{num:o,blockSize:l,sampleRate:c}}async advanceReader(){await this.readMetadata(),a(null!==this.lastLoadedPos),a(this.audioInfo);let e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t){this.lastSampleLoaded=!0;return}let i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};if(this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame){this.lastSampleLoaded=!0;return}}}class rL{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return a(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return a(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return"und"}getTimeResolution(){return a(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(a(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples)?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}
1async getLiveRefreshInterval(){return null}getDisposition(){return{...eN}}async getDecoderConfig(){return a(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(a(this.demuxer.audioInfo),e<0)return null;let i=await this.demuxer.readingMutex.acquire();try{for(;;){let i=_(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){await this.demuxer.advanceReader();continue}let r=this.demuxer.loadedSamples[i],a=r.blockOffset/this.demuxer.audioInfo.sampleRate,s=r.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(i,t)}}finally{i()}}async getNextPacket(e,t){let i=await this.demuxer.readingMutex.acquire();try{let i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){let i,r=this.demuxer.loadedSamples[e];if(!r)return null;if(t.metadataOnly)i=ig;else{let e=this.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(e instanceof Promise&&(e=await e),!e)return null;i=oy(e,r.byteSize)}return a(this.demuxer.audioInfo),new ik(i,"key",r.blockOffset/this.demuxer.audioInfo.sampleRate,r.blockSize/this.demuxer.audioInfo.sampleRate,e,r.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}let rq=e=>{let t="video/MP2T",i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t},rH="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.",rj=new Set([133,134,162]),rQ=new Set;class r$ extends ip{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),a(e);let t=oy(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 i=this.packetOffset,r=null,s=!1,n=!1;for(;;){let e=await this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator||n&&!this.elementaryStreams.some(t=>t.pid===e.pid)){i+=this.packetStride;continue}let t=await this.readSection(i,!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 eW(t.payload),i=e.readAlignedByte();e.skipBits(8*i),o=2===e.readBits(8)}if(0!==t.pid||s)if((t.pid===r||o)&&!n){let e=new eW(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);let r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);let a=e.readBits(10),s=e.pos+8*a,o=!1;for(;e.pos<s;){let t=e.readBits(8),i=e.readBits(8),r=e.pos+8*i;if(5===t&&i>=4){let t=e.readBits(32);o||=0x48444d56===t||0x48445052===t}e.pos=r}for(e.pos=s;8*(r+3)-e.pos>32;){let t=e.readBits(8);e.skipBits(3);let i=e.readBits(13);e.skipBits(6);let r=e.readBits(10),a=e.pos+8*r,s=!1,n=!1,l=!1;for(;e.pos<a;){let t=e.readBits(8),i=e.readBits(8),r=e.pos+8*i;if(106===t)s=!0;else if(122===t||204===t)n=!0;else if(123===t)l=!0;else if(5===t&&i>=4){let t=e.readBits(32);l||=(0xffffff00&t)==0x44545300}e.pos=r}let c=null,d=o&&rj.has(t)?130:t;switch(d){case 27:case 36:c={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:case 130:case 138:c={type:"audio",codec:3===d||4===d?"mp3":15===d?"aac":129===d?"ac3":135===d?"eac3":"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1};break;case 6:n?c={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?c={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:l&&(c={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:rQ.has(t)||(eR._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),rQ.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}n=!0}else{let e=this.elementaryStreams.find(e=>e.pid===t.pid);t:if(e&&!e.initialized){let i=rX(t,!0);if(!i)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 i=(await this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break t}}let r=new r0(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,await r.markNextPacket(),"avc"===e.info.codec){if
1(!r.suppliedPacket)throw Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=tB(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;let t=e.info.avcCodecInfo.sequenceParameterSets[0];a(t);let i=tR(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;let s=i.pixelAspectRatio.num,n=i.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:k[i.colourPrimaries],transfer:w[i.transferCharacteristics],matrix:T[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!r.suppliedPacket)throw Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=tN(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;let t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===ak.SPS_NUT).nalUnits[0];a(t);let i=tU(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight,i.pixelAspectRatio.num>i.pixelAspectRatio.den?(e.info.squarePixelWidth=Math.round(e.info.width*i.pixelAspectRatio.num/i.pixelAspectRatio.den),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*i.pixelAspectRatio.den/i.pixelAspectRatio.num)),e.info.colorSpace={primaries:k[i.colourPrimaries],transfer:w[i.transferCharacteristics],matrix:T[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw Error("Unhandled.")}e.info.decoderConfig={codec:e9({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 r.markNextPacket(),!r.suppliedPacket)throw Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){let t=rD(og.tempFromBytes(r.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=eL[t.channelConfiguration],e.info.sampleRate=eV[t.samplingFrequencyIndex]}else if("mp3"===e.info.codec){let t=ty(oP(og.tempFromBytes(r.suppliedPacket.data)),r.suppliedPacket.data.byteLength);if(!t.header)throw Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=tb(t.header.channel),e.info.sampleRate=t.header.sampleRate}else if("ac3"===e.info.codec){let t=t3(r.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=t2[t.acmod]+t.lfeon,e.info.sampleRate=tT[t.fscod]}else if("eac3"===e.info.codec){let t=t7(r.suppliedPacket.data);if(!t)throw Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");let i=t9(t);if(null===i)throw Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=ie(t),e.info.sampleRate=i}else if("dts"===e.info.codec){let t=id(r.suppliedPacket.data);if(!t)throw Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}else throw Error("Unhandled.");e.info.decoderConfig={codec:tt({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{let e=new eW(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);let a=e.readBits(10);for(e.skipBits(40);8*(a+3)-e.pos>32;){let t=e.readBits(16);e.skipBits(3);let i=e.readBits(13);if(0!==t)if(null!==r)throw Error("Only files with a single program are supported.");else r=i}if(null===r)throw Error("Program Association Table must link to a Program Map Table.");s=!0}if(n&&this.elementaryStreams.every(e=>e.initialized))break;i+=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 rY(e)):this.trackBackingEntries.push(new rJ(e)))})()}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){return await this.readMetadata(),rq(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r,a=e,s=e,n=[],o=0,l=null,c=!0,d=0;for(;;){let e=await this.readPacket(s);if(s+=this.packetStride,!e)break;if(l){if(e.pid!==l.pid)if(!i)continue;else break;if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;l=e}let r=!!(2&e.adaptationFieldControl),u=!!(1&e.adaptationFieldControl),h=0;if(r&&(h=1+e.body[0],e===l&&h>1&&(d=e.body[1]>>6&1)),u&&(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!==E(this.sectionEndPositions,a,e=>e)){c=!1;break}}if(c){let e=_(this.sectionEndPositions,a,e=>e);this.sectionEndPositions.splice(e+1,0,a)}if(!l)return null;if(1===n.length)r=n[0];else{r=new Uint8Array(n.reduce((e,t)=>e+t.length,0));let e=0;for(let t of n)r.set(t,e),e+=t.length}return{startPos:e,endPos:t?a:null,pid:l.pid,payload:r,randomAccessIndicator:d}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=await t),!t)return null;if(71!==ow(t))throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let i=oT(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:ow(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,188);if(t instanceof Promise&&(t=await t),!t)return null;let i=oy(t,188);if(71!==i[0])throw Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");let r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}}let rK=(e,t)=>{if(e.payload.byteLength<3)return null;let i=new eW(e.payload);if(1!==i.readBits(24))return null;let r=i.readBits(8);if(i.skipBits(16),188===r||190===r||191===r||240===r||241===r||255===r||242===r||248===r)return null;i.skipBits(8);let a=i.readBits(2);i.skipBits(14);let s=null;if(2===a||3===a)s=0,i.skipBits(4),s+=0x40000000*i.readBits(3),i.skipBits(1),s+=32768*i.readBits(15),i.skipBits(1),s+=i.readBits(15);else if(t)throw Error(rH);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},rX=(e,t)=>{a(null!==e.endPos);let i=rK(e,t);if(!i)return null;let r=new eW(e.payload);r.skipBits(32);let s=r.readBits(16);r.skipBits(16);let n=r.readBits(8),o=r.pos+8*n;r.pos=o;let l=o/8;a(Number.isInteger(l));let c=e.payload.subarray(l,s>0?6+s:e.payload.byteLength);return{...i,data:c}};class rG{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,i=0;for(let r of e.trackBackingEntries)if(r.getType()===t&&i++,a(r instanceof rG),r.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return"und"}getDisposition(){return{...eN,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,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new ik(i.metadataOnly?ig:e.data,r,e.pts/9e4,Math.max(t/9e4,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){let t=this.elementaryStream.firstSection;a(t);let i=rX(t,!0);a(i);let r=new r1(this,new r0(this.elementaryStream,i)),s=await r.readNext();if(!s)return null;let n=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(n,r),this.packetSectionStarts.set(n,s.packet.sectionStartPos),n}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){let r=await i.readNext();if(!r)return null;this.packetBuffers.delete(e);let a=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(a,i),this.packetSectionStarts.set(a,r.packet.sectionStartPos),a}let r=this.packetSectionStarts.get(e);if(void 0===r)throw Error("Packet was not created from this track.");let s=this.elementaryStream.demuxer,n=await s.readSection(r,!0);a(n);let o=rX(n,!0);a(o),i=new r1(this,new r0(this.elementaryStream,o));let l=e.sequenceNumber;for(;;){let e=await i.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){let r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(!(i=await this.getNextPacket(i,t)))return null;if("key"===i.type)return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){let r,s=V(9e4*e),o=this.elementaryStream.demuxer,{reader:l,seekChunkSize:c}=o,d=this.elementaryStream.pid,u=async(e,t,i)=>{let r=e;for(;r<t;){let e=await o.readPacketHeader(r);if(!e)break;if(e.pid===d&&1===e.payloadUnitStartIndicator){let e=await o.readSection(r,i);if(!e)return null;let t=rK(e,!1);if(t&&null!==t.pts)return{pesPacketHeader:t,section:e}}r+=o.packetStride}return null},h=this.elementaryStream.firstSection;a(h);let m=rK(h,!0);if(a(m),s<m.pts)return null;let f=this.elementaryStream.referencePesPackets,p=_(f,s,e=>e.pts),g=-1!==p?f[p]:null;if(g&&s-g.pts<45e3)r=g.sectionStartPos;else{let e=0;if(null!==l.fileSize){let t=Math.ceil(l.fileSize/c);if(t>1){let i=0,r=t-1;for(e=0;i<=r;){let t=Math.floor((i+r)/2),a=H(t*c,o.packetStride)+m.sectionStartPos,n=a+c,l=await u(a,n,!1);if(!l){r=t-1;continue}l.pesPacketHeader.pts<=s?(e=t,i=t+1):r=t-1}}}r=H(e*c,o.packetStride)+m.sectionStartPos}let k=await u(r,l.fileSize??1/0,!1),y=k?.pesPacketHeader??null;y||(y=m);let w=this.getReorderSize(),b=async(e,t)=>{let r=await o.readSection(e,!0);a(r);let l=rX(r,!0);a(l);let c=new r1(this,new r0(this.elementaryStream,l));for(;!((n(c.presentationOrderPackets)?.pts??-1/0)>=s)&&await c.readNextPacket(););let d=R(c.presentationOrderPackets,t);if(-1===d)return null;let u=c.presentationOrderPackets[d],h=0===d?0:u.pts-c.presentationOrderPackets[d-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=h;let m=await c.readNext();a(m);let f=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(f,c),this.packetSectionStarts.set(f,m.packet.sectionStartPos),f};if(!t||this.allPacketsAreKeyPackets()){t:for(;;){let e=y.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break t;if(t.pid===d&&1===t.payloadUnitStartIndicator){let t=await o.readSection(e,!1);if(t){let e=rK(t,!1);if(e&&null!==e.pts){if(e.pts>s)break t;y=e,rZ(this.elementaryStream,y);break}}}e+=o.packetStride}}t:for(let e=0;e<w+1;e++){let e=y.sectionStartPos-o.packetStride;for(;e>=o.packetOffset;){let t=await o.readPacketHeader(e);if(!t)break t;if(t.pid===d&&1===t.payloadUnitStartIndicator){let t=await o.readSection(e,!1);if(t){let e=rK(t,!1);if(e&&null!==e.pts){y=e;break}}}e-=o.packetStride}}return b(y.sectionStartPos,e=>e.pts<=s)}{let e=r,t=null,i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r,n=null,f=e<=m.sectionStartPos,p=null;if(f)r=m,p=h;else{let t=await u(e,l.fileSize??1/0,i);r=t?.pesPacketHeader??null,p=t?.section??null}let g=!1,k=0;t:for(;r&&(null===t||!(r.sectionStartPos>=t));){if(r.pts<=s){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===r.randomAccessIndicator;else{a(p);let t=rX(p,!0);a(t);let i=new r0(this.elementaryStream,t);await i.markNextPacket(),e=i.suppliedPacket?.randomAccessIndicator===1}e&&(n=r)}if(r.pts>s&&(g=!0),g&&++k>w)break;let e=r.sectionStartPos+o.packetStride;for(;;){let t=await o.readPacketHeader(e);if(!t)break t;if(t.pid===d&&1===t.payloadUnitStartIndicator){let t=await o.readSection(e,i);if(t){let e=rK(t,!1);if(e&&null!==e.pts){r=e,p=t,rZ(this.elementaryStream,r);break}}}e+=o.packetStride}}if(n){let e=n;if(0===k)t:for(let t=0;t<w;t++){let t=e.sectionStartPos-o.packetStride;for(;t>=o.packetOffset;){let r=await o.readPacketHeader(t);if(!r)break t;if(r.pid===d&&1===r.payloadUnitStartIndicator){let r=await o.readSection(t,i);if(r){let t=rK(r,!1);if(t&&null!==t.pts){e=t;break}}}t-=o.packetStride}}let t=await b(e.sectionStartPos,e=>e.pts<=s&&1===e.randomAccessIndicator);return a(t),t}if(f)return null;t=e,e=Math.max(H(e-m.sectionStartPos-c,o.packetStride)+m.sectionStartPos,m.sectionStartPos)}}}}class rY extends rG{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 a(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class rJ extends rG{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return a(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}let rZ=(e,t)=>{let i=e.referencePesPackets,r=_(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){let a=i[r];if(t.pts<=a.pts)return!1;let s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos<s)return!1;if(r<i.length-1){let e=i[r+1];if(e.pts<t.pts||e.sectionStartPos-t.sectionStartPos<s)return!1}}return i.splice(r+1,0,t),!0};class r0{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 a(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=n(this.pesPackets).sectionEndPos;for(a(null!==t);;){let i=await this.demuxer.readPacketHeader(t);if(!i)return;if(i.pid===this.pid){let i=await this.demuxer.readSection(t,!0);if(!i)return;let r=rX(i,!1);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){let t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,r=i+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(i,r);let a=new Uint8Array(e);a.set(t.data.subarray(i));let s=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();let t=this.getCurrentPesPacket(),i=e-s;if(i<=t.data.byteLength){a.set(t.data.subarray(0,i),s);break}a.set(t.data,s),s+=t.data.byteLength}return a}readU8(){let e=this.getCurrentPesPacket(),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(){a(!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 i="avc"===t?1:2,r=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,o=this.readBytes(e),c=o.byteLength,d=0;for(;d<c;){let e,u,h,m=o.indexOf(0,d);if(-1===m||m>=c)break;let f=n+(d=m);if(d+3>=c){this.seekTo(f);break}let p=o[d+1],g=o[d+2],k=o[d+3],y=0;if(0===p&&0===g&&1===k?y=4:0===p&&1===g&&(y=3),0===y){d++;continue}r??=f;let w=d+y,b=w+i;if(b+("avc"===t?6:1)>c){this.seekTo(f);break}let T=o[w];if("avc"===t)u=(e=tC(T))===ag.NON_IDR_SLICE||e===ag.SLICE_DPA||e===ag.IDR,h=e===ag.SEI||e===ag.SPS||e===ag.PPS||e===ag.AUD;else{if(e=tO(T),((1&T)<<5|o[w+1]>>3)>0){d+=y;continue}u=e<=ak.RASL_R||e>=ak.BLA_W_LP&&e<=21,h=e>=ak.VPS_NUT&&e<=37||e===ak.PREFIX_SEI_NUT||e>=41&&e<=44||e>=48&&e<=55}let S=!1;if(u){let e;if("avc"===t){let t=l(new eW(o.subarray(b,b+6)));e=!a||t<=s,s=t}else e=o[b]>>7==1;e&&(a?S=!0:a=!0)}else h&&a&&(S=!0);if(S){let e=f-r;return this.seekTo(r),this.supplyPacket(e,0)}d+=y}if(e<1024)break}if(null!==r&&this.endPos>r){let e=this.endPos-r;return this.seekTo(r),this.supplyPacket(e,0)}}else{let t=e.info.codec;for(;;){let i=this.ensureBuffered(128);i instanceof Promise&&(i=await i);let r=this.currentPos;for(;this.currentPos-r<i;){let i=this.readU8();if("aac"===t){if(255!==i)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(9);if(r instanceof Promise&&(r=await r),r<9)return;let a=this.readBytes(9),s=rD(og.tempFromBytes(a));if(s){this.seekTo(t);let i=this.ensureBuffered(s.frameLength);return i instanceof Promise&&(i=await i),this.supplyPacket(i,Math.round(9216e4/e.info.sampleRate))}this.seekTo(t+1)}else if("mp3"===t){if(255!==i)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(4);if(r instanceof Promise&&(r=await r),r<4)return;let a=ty(u(this.readBytes(4)).getUint32(0),null);if(a.header){this.seekTo(t);let i=this.ensureBuffered(a.header.totalSize);
1i instanceof Promise&&(i=await i);let r=9e4*a.header.audioSamplesInFrame/e.info.sampleRate;return this.supplyPacket(i,Math.round(r))}this.seekTo(t+1)}else if("ac3"===t){if(11!==i)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(5);if(r instanceof Promise&&(r=await r),r<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=t4[3*o+n];a(void 0!==l),this.seekTo(t),(r=this.ensureBuffered(l))instanceof Promise&&(r=await r);let c=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,c)}else if("eac3"===t){if(11!==i)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(5);if(r instanceof Promise&&(r=await r),r<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=t5[3==a[4]>>6?3:a[4]>>4&3];this.seekTo(t),(r=this.ensureBuffered(s))instanceof Promise&&(r=await r);let o=Math.round(256*n*9e4/e.info.sampleRate);return this.supplyPacket(r,o)}else if("dts"===t){if(127!==i&&100!==i)continue;this.skip(-1);let t=this.currentPos,r=this.ensureBuffered(18);if(r instanceof Promise&&(r=await r),r<18)return;let a=this.readBytes(18),s=ih(a),n=s?null:im(a);if(!s&&!n){this.seekTo(t+1);continue}if(n&&!n.asset){this.seekTo(t);let e=Math.min(n.frameSize,4096),i=this.ensureBuffered(e);i instanceof Promise&&(i=await i),n=im(this.readBytes(i))??n}let o=s?s.frameSize:n.frameSize;if(s){let e=4*Math.ceil(s.frameSize/4);for(;;){this.seekTo(t);let i=e+10,r=this.ensureBuffered(i);if(r instanceof Promise&&(r=await r),r<i)break;this.seekTo(t+e);let a=im(this.readBytes(10));if(!a)break;e+=a.frameSize,o=e}}let l=s?.sampleCount??n.asset?.sampleCount;if(void 0===l){this.seekTo(t+1);continue}this.seekTo(t),(r=this.ensureBuffered(o))instanceof Promise&&(r=await r);let c=Math.round(9e4*l/e.info.sampleRate);return this.supplyPacket(r,c)}else throw Error("Unhandled.")}if(i<128)break}}}supplyPacket(e,t){let i,r=this.getCurrentPesPacket();if(this.lastSuppliedPesPacket===r)a(null!==this.nextPts),i=this.nextPts;else{if(null===r.pts)throw Error(rH);i=r.pts,rZ(this.elementaryStream,r)}this.lastSuppliedPesPacket=r,this.nextPts=i+t;let s=r.sectionStartPos,n=s+(this.currentPos-this.currentPesPacketPos),o=this.readBytes(e),l=r.randomAccessIndicator;0===l&&!this.elementaryStream.canBeTrustedWithKeyPackets&&("audio"===this.elementaryStream.info.type?l=1:this.elementaryStream.info.decoderConfig&&(l=Number("key"===tZ(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,o)))),this.suppliedPacket={pts:i,data:o,sequenceNumber:n,sectionStartPos:s,randomAccessIndicator:l},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class r1{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(),a(this.reorderSize>=0)}async readNext(){let e;if(0===this.decodeOrderPackets.length&&!await this.readNextPacket())return null;await this.ensureCurrentPacketHasNext();let t=this.decodeOrderPackets[0],i=this.presentationOrderPackets.indexOf(t);for(a(-1!==i),i===this.presentationOrderPackets.length-1?e=this.lastDuration:(e=this.presentationOrderPackets[i+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(a(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)=>
1e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}let r2="application/vnd.apple.mpegurl",r3="#EXT-X-STREAM-INF:",r4="#EXT-X-I-FRAME-STREAM-INF:",r8="#EXT-X-MEDIA:",r6="#EXTINF:",r5="#EXT-X-MAP:",r7="#EXT-X-KEY:",r9="#EXT-X-MEDIA-SEQUENCE:",ae="#EXT-X-BYTERANGE:",at="#EXT-X-PROGRAM-DATE-TIME:",ai="#EXT-X-TARGETDURATION:",ar="#EXT-X-PLAYLIST-TYPE:",aa=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class as{constructor(e){this._attributes={};let t="",i="",r=!1,a=!1;for(let s=0;s<e.length;s++){let n=e[s];'"'===n?a=!a:"="!==n||r||a?","!==n||a?r?i+=n:t+=n:(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",r=!1):r=!0}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){let t=this.get(e);if(null===t)return null;let i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}}class an{constructor(e,t,i){this.nextInputCacheAge=0,this.inputCache=[],this.trackBackingsPromise=null,this.firstSegment=null,this.firstSegmentFirstTimestamps=new WeakMap,this.firstTimestampCache=new WeakMap,this.input=e,this.path=t,this.trackDeclarations=i}
1async getDurationFromMetadata(e){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 i=e-t.timestamp;return t.unixEpochTimestamp+i}async getTrackBackings(){return this.trackBackingsPromise??=(async()=>{let e=[];if(this.trackDeclarations){for(let t of this.trackDeclarations)if("video"===t.type){let i=ey(e,e=>"video"===e.getType())+1;e.push(new al(this,t,i))}else if("audio"===t.type){let i=ey(e,e=>"audio"===e.getType())+1;e.push(new ac(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];let t=this.getInputForSegment(this.firstSegment);for(let i of(await t.getTracks()))if("video"===i.type){let t=ey(e,e=>"video"===e.getType())+1;e.push(new al(this,{id:e.length+1,type:"video"},t))}else if("audio"===i.type){let t=ey(e,e=>"audio"===e.getType())+1;e.push(new ac(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 i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){let i,r=e.firstSegment??e;if(this.firstSegmentFirstTimestamps.has(r))i=this.firstSegmentFirstTimestamps.get(r);else{let e=this.getInputForSegment(r);i=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(r,i)}if(r===e)return r.timestamp-i;let a=await this.getFirstTimestampForInput(t),s=e.timestamp-r.timestamp;return Math.abs(a-i-s)<=Math.min(.25,s)?r.timestamp-i:e.timestamp-a}dispose(){for(let e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class ao{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??=(async()=>{if(this.segmentedInput.firstSegment??=await this.segmentedInput.getFirstSegment({}),!this.segmentedInput.firstSegment)throw Error("Missing first segment, can't retrieve track.");let e=this.segmentedInput.firstSegment,t=null;for(;e;){let i=this.segmentedInput.getInputForSegment(e);if(t=(await i.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(),a(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}
1getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){a(e.sequenceNumber>=0),a(this.segmentedInput.firstSegment);let r=await this.segmentedInput.getMediaOffset(t,i.input),s=t.timestamp-this.segmentedInput.firstSegment.timestamp,n=e.clone({timestamp:q(e.timestamp+r,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*s)+e.sequenceNumber});return this.packetInfos.set(n,{segment:t,track:i,sourcePacket:e}),n}async getFirstPacket(e){await this.hydrate(),a(this.firstInputTrack),a(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){let r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,i,t)}if(!(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait})))break;let r=this.segmentedInput.getInputForSegment(i);t=(await r.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,i){let r=this.packetInfos.get(e);if(!r)throw Error("Packet was not created from this track.");let a=i?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(a)return this.createAdjustedPacket(a,r.segment,r.track);let s=r.segment;for(;;){let e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;let i=this.segmentedInput.getInputForSegment(e),a=(await i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.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,i){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){let a=this.segmentedInput.getInputForSegment(r),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}let n=e-await this.segmentedInput.getMediaOffset(r,a),o=i?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(!o){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}return this.createAdjustedPacket(o,r,s)}return null}}class al extends ao{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 ac extends ao{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())}}var ad,au,ah,am,af,ap,ag,ak,ay,aw,ab,aT,aS,aA,av,aP,aC,ax=i(1845),aE=i.t(ax,2);ep();let a_=void 0!==aE?aE:void 0,aI=1/0,aB=null;"undefined"!=typeof FinalizationRegistry&&(aB=new FinalizationRegistry(e=>{e()}));class aF extends eI{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 of;return this._sizePromise??=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,aI),a(void 0!==(e=this._getFileSize()))),e})()}async getSize(){if(this._disposed)throw new of;
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 aX(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new aM(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class aM{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;a(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class aR extends aF{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),i=e=>{if(!(e instanceof aF||e instanceof aM))throw TypeError("requestHandler must return or resolve to a Source or SourceRef.");let t=e instanceof aF?e.ref():e;return t.source._usedForHls||=this._usedForHls,t};return t instanceof Promise?t.then(i):i(t)}}class aD extends aR{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,r){if(!this._root){if(!this._rootRequest){let e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{let t=e instanceof aF?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),a(this._root))}if(this._rootRequest)return this._rootRequest.then(a=>a.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class az extends aF{constructor(e){if(!(e instanceof ArrayBuffer)&&!("undefined"!=typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)&&!ArrayBuffer.isView(e))throw TypeError("buffer must be an ArrayBuffer, SharedArrayBuffer, or ArrayBufferView.");super(),this._onreadCalled=!1,this._bytes=d(e),this._view=u(e)}_getFileSize(){return this._bytes.byteLength}_read(){return this._onreadCalled||(this._dispatchRead(0,this._bytes.byteLength),this._onreadCalled=!0),{bytes:this._bytes,view:this._view,offset:0}}_dispose(){}}class aO extends aF{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&&(!eg(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 aK({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:a$.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){a(e.strictTarget);let t=this._readers.get(e);for(void 0===t&&(t=("stream"in this._blob)&&!et()&&!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:i,value:r}=await t.read();if(i)throw this._orchestrator.onWorkerFinished(e),Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;
1this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}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()}}let aU=(e,t,i)=>{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!=typeof window){let e=null;try{"undefined"!=typeof window&&void 0!==window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch{}if(("undefined"==typeof navigator||"boolean"!=typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return eR._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)},aN=new Set;class aW extends aR{constructor(e,t={}){if("string"!=typeof e&&!(e instanceof URL)&&!("undefined"!=typeof Request&&e instanceof Request))throw TypeError("url must be a string, URL or Request.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!=typeof t.requestInit))throw TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!=typeof t.getRetryDelay)throw TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!eg(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!=typeof t.fetchFn)throw TypeError("options.fetchFn, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new aW(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??aU,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){let e={...Y(t.requestInit.headers)},r=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==r&&(i=e[r],delete e[r],this._requestInit.headers=e)}if(e instanceof Request){let t=e.headers.get("Range");if(null!==t){i??=t;let r=new Request(e);r.headers.delete("Range"),this._url=r}}if(null!==i){let e=aL(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new aK({maxCacheSize:t.maxCacheSize??0x4000000,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:a$.network})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;let e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:W(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;let a=this._offset,s=this._sequentialBacking?this._sequentialBacking._read(a+e,a+t):this._orchestrator.read(a+e,a+t,Math.max(a+i,a),a+Math.min(r,this._length??1/0)),n=e=>e?(e.offset-=this._offset,e):null;return s instanceof Promise?s.then(n):n(s)}async _runWorker(e){for(;;){let t=new AbortController,i=await J(this._options.fetchFn??fetch,this._url,G(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:t.signal}),this._getRetryDelay,()=>this._disposed);if(!i.ok)throw Error(`Error fetching ${String(this._url)}: ${i.status} ${i.statusText}`);i.redirected&&(this.rootPath=i.url);t:if(null===this._orchestrator.fileSize){let t=i.headers.get("Content-Range");if(t){let e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break t}}let r=i.headers.get("Content-Length");if(r){let t=206===i.status?e.currentPos:0;
1this._orchestrator.supplyFileSize(t+Number(r))}}if(this._fileSizeDetermined=!0,!i.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==i.status){if(this._sequentialBacking)return void i.body.cancel();if(!this._usedForHls){let e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!=typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||aN.has(e.origin)||(eR._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),aN.add(e.origin))}this._transitionToSequentialMode(i.body);return}let r=i.body.getReader();for(;;){let i;if(e.currentPos>=e.targetPos||e.aborted){t.abort(),this._orchestrator.signalWorkerStoppedRunning(e);return}try{i=await r.read()}catch(t){if(this._disposed)throw t;let e=this._getRetryDelay(1,t,this._url);if(null!==e){eR._error("Error while reading response stream. Attempting to resume.",t),await eE(1e3*e);break}throw t}if(e.aborted)continue;let{done:a,value:s}=i;if(a){if(e.currentPos>=e.targetPos||!e.strictTarget)return void this._orchestrator.onWorkerFinished(e);break}this._dispatchRead(e.currentPos,e.currentPos+s.length),this._orchestrator.supplyWorkerData(e,s)}}}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0,s=new aQ(new ReadableStream({pull:async e=>{for(;;){let a;try{a=await t.read()}catch(s){if(this._disposed)throw s;let e=this._getRetryDelay(1,s,this._url);if(null===e)throw s;eR._error("Error while reading response stream. Attempting to resume.",s),await eE(1e3*e);let a=await J(this._options.fetchFn??fetch,this._url,G(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!a.ok)throw Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(!a.body)throw Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=a.body.getReader(),r=206===a.status?0:i;continue}if(a.done)return void e.close();let s=a.value;if(r>0){let e=Math.min(r,s.length);r-=e,s=s.subarray(e)}if(0!==s.length){i+=s.length,e.enqueue(s);return}}},cancel:()=>t.cancel()}),{maxCacheSize:this._orchestrator.options.maxCacheSize});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;let n=new Set;for(let e of this._orchestrator.workers){for(let t of e.pendingSlices)n.add(t);e.aborted=!0,e.pendingSlices.length=0}for(let e of this._orchestrator.queuedReads)for(let t of e.pendingSlices)n.add(t);for(let e of(this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0,n)){let t=s._read(e.start,e.start+e.bytes.length);t instanceof Promise?t.then(t=>{t?(a(t.offset===e.start),e.resolve(t.bytes)):e.resolve(null)},t=>e.reject(t)):(a(null===t),e.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}let aV=/^bytes=(\d+)-(\d*)$/,aL=e=>{let t=aV.exec(e.trim());if(!t)return null;let i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&r<i?null:{offset:i,length:null!==r?r-i+1:null}};class aq extends aR{constructor(e,t={}){if("string"!=typeof e)throw TypeError("filePath must be a string.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!eg(t.maxCacheSize)||t.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(!a_.fs)throw Error("FilePathSource is only available in server-side environments (Node.js, Bun, Deno).");super(e,e=>new aq(e.path,t)),this._fileHandle=null,this._customSource=new aH({getSize:async()=>{let t=await a_.fs.open(e,"r");return this._fileHandle=t,aB?.register(this,()=>{t.close()},this),(await t.stat()).size},read:async(e,t)=>{a(this._fileHandle);let i=new Uint8Array(t-e);return await this._fileHandle.read(i,0,t-e,e),i},maxCacheSize:t.maxCacheSize,prefetchProfile:"fileSystem"})}_read(e,t,i,r){return this._customSource._read(e,t,i,r)}_getFileSize(){return this._customSource._getFileSize()}_dispose(){this._customSource._dispose(),this._fileHandle&&(this._fileHandle.close(),this._fileHandle=null,aB?.unregister(this))}}class aH extends aF{constructor(e){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if("function"!=typeof e.getSize)throw TypeError("options.getSize must be a function.");
1if("function"!=typeof e.read)throw TypeError("options.read must be a function.");if(void 0!==e.dispose&&"function"!=typeof e.dispose)throw TypeError("options.dispose, when provided, must be a function.");if(void 0!==e.maxCacheSize&&(!eg(e.maxCacheSize)||e.maxCacheSize<0))throw TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(e.prefetchProfile&&!["none","fileSystem","network"].includes(e.prefetchProfile))throw TypeError("options.prefetchProfile, when provided, must be one of 'none', 'fileSystem' or 'network'.");super(),this._options=e,this._orchestrator=new aK({maxCacheSize:e.maxCacheSize??8388608,maxWorkerCount:2,prefetchProfile:a$[e.prefetchProfile??"none"],runWorker:this._runWorker.bind(this)})}_getFileSize(){return this._orchestrator.fileSize??void 0}_read(e,t,i,r){if(null!==this._orchestrator.fileSize)return this._orchestrator.read(e,t,i,r);let a=this._options.getSize();if(a instanceof Promise)return a.then(a=>{if(!Number.isInteger(a)||a<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=a,this._orchestrator.read(e,t,i,r)});if(!Number.isInteger(a)||a<0)throw TypeError("options.getSize must return or resolve to a non-negative integer.");return this._orchestrator.fileSize=a,this._orchestrator.read(e,t,i,r)}async _runWorker(e){for(;e.currentPos<e.targetPos&&!e.aborted;){let t=e.currentPos,i=e.targetPos,r=this._options.read(e.currentPos,i);if(r instanceof Promise&&(r=await r),e.aborted)break;if(r instanceof Uint8Array){if((r=d(r)).length!==i-e.currentPos)throw Error(`options.read returned a Uint8Array with unexpected length: Requested ${i-e.currentPos} bytes, but got ${r.length}.`);this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else if(r instanceof ReadableStream){let a=r.getReader();for(;e.currentPos<i&&!e.aborted;){let{done:r,value:s}=await a.read();if(r){if(e.currentPos<i)throw Error(`ReadableStream returned by options.read ended before supplying enough data. Requested ${i-t} bytes, but got ${e.currentPos-t}`);break}if(!(s instanceof Uint8Array))throw TypeError("ReadableStream returned by options.read must yield Uint8Array chunks.");if(e.aborted)break;let n=d(s);this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}else throw TypeError("options.read must return or resolve to a Uint8Array or a ReadableStream.")}this._orchestrator.signalWorkerStoppedRunning(e)}_dispose(){this._orchestrator.dispose(),this._options.dispose?.()}}let aj=aH;class aQ extends aF{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&&(!eg(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 i=_(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let a=e,s=new Uint8Array(t-e);if(-1!==i)for(let r=i;r<this._cache.length;r++){let i=this._cache[r];if(i.start>=t)break;let n=Math.max(e,i.start);n>a&&this._throwDueToCacheMiss();let o=Math.min(t,i.end);n<o&&(s.set(i.bytes.subarray(n-i.start,o-i.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}=B();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 i=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(i,r);for(let e=0;e<this._pendingSlices.length;e++){let a=this._pendingSlices[e],s=Math.max(i,a.start),n=Math.min(r,a.end);s<n&&(a.bytes.set(t.subarray(s-i,n-i),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:i,end:r,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 of);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}let a$={none:(e,t)=>({start:e,end:t}),fileSystem:(e,t)=>({start:e=65536*Math.floor((e-65536)/65536),end:t=65536*Math.ceil((t+65536)/65536)}),network:(e,t,i)=>{for(let r of(e=Math.max(0,65536*Math.floor((e-65536)/65536)),i))if(ec(e,t,Math.max((r.startPos+r.targetPos)/2,r.targetPos-8388608),r.targetPos)){let e=r.targetPos-r.startPos,i=8388608*Math.ceil((e+1)/8388608),a=Math.min(2**Math.ceil(Math.log2(e+1)),i);t=Math.max(t,r.startPos+a)}return t=Math.max(t,e+524288),{start:e,end:t}}};class aK{constructor(e){this.options=e,this.fileSize=null,this.nextAge=0,this.workers=[],this.cache=[],this.currentCacheSize=0,this.disposed=!1,this.queuedReads=[]}read(e,t,i,r){a(!this.disposed);let s=this.options.prefetchProfile(e,t,this.workers),n=Math.max(s.start,i),o=Math.min(s.end,this.fileSize??1/0,r);a(n<=e&&t<=o);let l=null,c=_(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=_(this.cache,n,e=>e.start),m=l?null:new Uint8Array(t-e),f=0,p=n,g=[];if(-1!==h){for(let i=h;i<this.cache.length;i++){let r=this.cache[i];if(r.start>=o)break;if(r.end<=n)continue;let s=Math.max(n,r.start),l=Math.min(o,r.end);if(a(s<=l),p<s&&g.push({start:p,end:s}),p=l,m){let i=Math.max(e,r.start),a=Math.min(t,r.end);if(i<a){let t=i-e;m.set(r.bytes.subarray(i-r.start,a-r.start),t),t===f&&(f=a-e)}}r.age=this.nextAge++}p<o&&g.push({start:p,end:o})}else g.push({start:n,end:o});if(m&&f>=m.length&&(l={bytes:m,view:u(m),offset:e}),0===g.length)return a(l),l;let{promise:k,resolve:y,reject:w}=B(),b=[];for(let i of g){let r=Math.max(e,i.start),a=Math.min(t,i.end);r===i.start&&a===i.end?b.push(i):r<a&&b.push({start:r,end:a})}let T=m&&{start:e,bytes:m,holes:b,resolve:y,reject:w};t:for(let e of g){for(let t of this.workers)if(this.checkHoleAgainstWorker(t,e,T?[T]:[])){this.checkQueuedReadsAgainstWorker(t);continue t}let t=e.end<o||null!==this.fileSize,i=this.createWorker(e.start,e.end,t);if(i)T&&(i.pendingSlices=[T]),this.runWorker(i);else{let i=_(this.queuedReads,e.start,e=>e.hole.start),r=-1!==i?this.queuedReads[i]:null;for(r&&e.start<=r.hole.end?(r.hole.end=Math.max(r.hole.end,e.end),r.strictTarget&&=t,T&&r.pendingSlices.push(T)):(i++,r={hole:{start:e.start,end:e.end},strictTarget:t,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(i,0,r));i+1<this.queuedReads.length;){let e=this.queuedReads[i+1];if(e.hole.start>r.hole.end)break;r.hole.end=Math.max(r.hole.end,e.hole.end),r.pendingSlices.push(...e.pendingSlices),r.strictTarget&&=e.strictTarget,r.age=Math.min(r.age,e.age),this.queuedReads.splice(i+1,1)}}}return l?k.catch(e=>{if(!this.disposed)throw e}):(a(m),l=k.then(t=>t&&{bytes:t,view:u(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){if(ec(t.start-131072,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t<i.length;t++){let r=i[t];e.pendingSlices.includes(r)||e.pendingSlices.push(r)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){let r=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,r.hole,r.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){if(this.workers.length>=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i<this.workers.length;i++){let r=this.workers[i];r.running||0!==r.pendingSlices.length||e&&!(r.age<e.age)||(t=i,e=r)}if(!e)return null;a(null!==t),a(0===e.pendingSlices.length),this.workers.splice(t,1)}let r={startPos:e,currentPos:e,targetPos:t,strictTarget:i,running:!1,aborted:this.disposed,pendingSlices:[],age:this.nextAge++};return this.workers.push(r),r}runWorker(e){a(!e.running),a(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],i=this.createWorker(t.hole.start,t.hole.end,t.strictTarget);i&&(this.queuedReads.splice(e,1),i.pendingSlices=t.pendingSlices,this.runWorker(i))}})}supplyWorkerData(e,t){a(!e.aborted);let i=e.currentPos,r=i+t.length;this.insertIntoCache({start:i,end:r,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 a=0;a<e.pendingSlices.length;a++){let s=e.pendingSlices[a],n=Math.max(i,s.start),o=Math.min(r,s.start+s.bytes.length);n<o&&s.bytes.set(t.subarray(n-i,o-i),n-s.start);for(let e=0;e<s.holes.length;e++){let t=s.holes[e];i<=t.start&&r>t.start&&(t.start=r),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(a,1),a--)}for(let t=0;t<this.workers.length;t++){let a=this.workers[t];e!==a&&!a.running&&ec(i,r,a.currentPos,a.targetPos)&&(this.workers.splice(t,1),t--)}}supplyFileSize(e){for(let t of(a(null===this.fileSize),this.fileSize=e,this.workers)){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){let r=t.pendingSlices[i];for(let a of r.holes)if(a.end>e){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){let i=this.queuedReads[t];if(i.hole.start>=e){for(let e of i.pendingSlices)e.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let t=0;t<i.pendingSlices.length;t++){let r=i.pendingSlices[t];r.start>=e&&(r.resolve(null),i.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 i of(a(-1!==t),e.running=!1,this.workers.splice(t,1),null===this.fileSize&&this.supplyFileSize(e.currentPos),e.pendingSlices))i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=_(this.cache,e.start,e=>e.start)+1;if(t>0){let i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){let r=new Uint8Array(e.end-i.start);r.set(i.bytes,0),r.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=r,i.view=u(r),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i<this.cache.length;i++){let t=this.cache[i];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(i,1),this.currentCacheSize-=t.bytes.length,i--;continue}let r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=u(r),e.end=t.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let i=1;i<this.cache.length;i++){let r=this.cache[i];r.age<t.age&&(e=i,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(let e of this.workers){for(let t of e.pendingSlices)t.reject(new of);e.pendingSlices.length=0,e.aborted=!0}for(let e of this.queuedReads)for(let t of e.pendingSlices)t.reject(new of);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class aX extends aF{constructor(e,t,i){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=i??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,i,r){if(null!==this._length&&t>this._length)return null;let a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),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 aG=function(e,t,i){if(null!=t){var r,a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");
1if(i){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!=typeof r)throw TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},aY=(ad="function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r},function(e){function t(t){e.error=e.hasError?new ad(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var i,r=0;return function a(){for(;i=e.stack.pop();)try{if(!i.async&&1===r)return r=0,e.stack.push(i),Promise.resolve().then(a);if(i.dispose){var s=i.dispose.call(i.value);if(i.async)return r|=2,Promise.resolve(s).then(a,function(e){return t(e),a()})}else r|=1}catch(e){t(e)}if(1===r)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()});let aJ=/^0[xX][0-9a-fA-F]+$/,aZ=/^data:.*;base64,/i;class a0 extends an{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??=(async()=>{try{let e=this.getRemainingWaitTimeMs();e>0&&await eE(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 i=aG(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new op(i.source),s=await r.requestEntireFile();a(s),e=oD(s,s.length,{ignore:aa}),i.source instanceof aR&&(this.rootPath=i.source.rootPath)}catch(e){t.error=e,t.hasError=!0}finally{aY(t)}}let t=this.input._formatOptions.hls?.offsetTimestampsByDateTime!==!1,i=!1,r=0,s=null,o=null,l=null,c=0,d=null,h=null,m=null,f=null,p=null,g=null,k=!1,y=n(this.segments)??null,w=e=>{let t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(!Number.isInteger(r=Number(e.slice(t+1)))||r<0))throw Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},b=e=>{c=e,y&&(a(null!==y.sequenceNumber),y.sequenceNumber<e&&(r=y.timestamp+y.duration,d=y.firstSegment,h=y.initSegment,p=y.lastProgramDateTimeSeconds,s=null!==y.unixEpochTimestamp?y.unixEpochTimestamp+y.duration:null,y=null))};for(let a=0;a<e.length;a++){let T=e[a];if(!i){if("#EXTM3U"!==T)throw Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0;continue}if(!T.startsWith("#")){if(!y){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),i=u(t);i.setUint32(8,Math.floor(c/0x100000000)),i.setUint32(12,c),e={...e,iv:t}}let t={path:ek(this.rootPath,T),offset:f?.offset??0,length:f?.length??null},i={timestamp:r,unixEpochTimestamp:s,firstSegment:d,sequenceNumber:c,location:t,duration:o,encryption:e,initSegment:h,lastProgramDateTimeSeconds:p};d??=i,r+=o,null!==s&&(s+=o),this.segments.push(i)}o=null,null===f?m=null:f=null,b(c+1)}if(T.startsWith(r6)){if(y){k=!0;continue}k||(null===p&&c>0&&null!==g&&(r=c*g),k=!0);let e=T.slice(r6.length),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw Error(`Invalid #EXTINF tag duration '${i}'.`);o=a}else if(T.startsWith(r5)){let e=new as(T.slice(r5.length)),t=e.get("uri");if(!t)throw Error("Invalid #EXT-X-MAP tag; missing URI attribute.");let i=e.get("byterange"),a=null;if(null!==i&&(a=w(i)),a&&null===a.offset)throw Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!y){let e={path:ek(this.rootPath,t),offset:a?.offset??0,length:a?.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:r,unixEpochTimestamp:s,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:l,initSegment:null,lastProgramDateTimeSeconds:p}}o=null,null===f?m=null:f=null}else if(T.startsWith(r7)){let e=new as(T.slice(r7.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 i=null,r=e.get("iv");if(r){if(!aJ.test(r))throw Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(16);for(let t=0;t<16;t++){let r=-32+t;i[t]=parseInt(e.slice(r,r+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:ek(this.rootPath,t),iv:i,keyFormat:a}}else if("SAMPLE-AES"===t||"SAMPLE-AES-CTR"===t){let i=e.get("uri");if(!i)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 r=null;if(aZ.test(i)){let e=i.indexOf(","),t=eh(i.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);r=iw(t.subarray(8,Math.min(e,t.length)))}}l={method:t,psshBox:r}}else throw Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`)}else if(T.startsWith(r9)){let e=T.slice(r9.length),t=Number(e);if(!Number.isInteger(t)||t<0)throw Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);b(t)}else if(T.startsWith(ae)){let e=w(T.slice(ae.length));if(null===e.offset){if(null===m)throw Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=m}f=e,m=e.offset+e.length}else if(T.startsWith(at)){if(y)continue;let e=Date.parse(T.slice(at.length));if(!Number.isFinite(e))continue;let i=e/1e3;if(p===i)continue;if(null===p&&this.segments.length>0){let e=n(this.segments),r=i-(e.timestamp+e.duration);for(let e of this.segments)e.unixEpochTimestamp=e.timestamp+r,t&&(e.timestamp=e.unixEpochTimestamp)}p=i,s=i,t&&(r=i)}else if("#EXT-X-DISCONTINUITY"===T)d=null;else if(T.startsWith(ai)){let e=T.slice(ai.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"===T){this.streamHasEnded=!0;break}else T.startsWith(ar)&&"vod"===T.slice(ar.length).toLowerCase()&&(this.streamHasEnded=!0)}if(!i)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 i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){let r=_(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r<this.segments.length-1||this.streamHasEnded||i)return this.segments[r];let a=this.segments[r];if(e<a.timestamp+a.duration)return a;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){let i=this.segments.indexOf(e);a(-1!==i);let r=i+1,s=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(r<this.segments.length)return this.segments[r];if(this.streamHasEnded||s)return null;await this.runUpdateSegments(),t.skipLiveWait&&(s=!0)}}async getPreviousSegment(e){let t=this.segments.indexOf(e);return a(-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 i=null;(e.initSegment||e.firstSegment)&&(i=this.getInputForSegment(e.initSegment??e.firstSegment));let r={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&
1(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 i=t.psshBoxes,{psshBox:r}=e.encryption;return(null===r.keyIds||r.keyIds.includes(t.keyId))&&!i.some(e=>ib(e,r))&&(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...t,psshBoxes:i})})}},s=new oh({source:new aD(e.location.path,async t=>{let i;a(t.isRoot);let r={...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;a(t.iv);let n=await this.input._getSourceCached(r);if(s){let t=n.source.slice(e.location.offset,e.location.length??void 0).ref();n.free(),n=t}let o=((e,t,i)=>{let r=!1,a=0,s=new iD;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(o instanceof Promise&&(o=await o),!o||0===o.length)throw Error("Invalid ciphertext.");let l=o.length;if(l%16!=0)throw Error("Invalid ciphertext.");let c=65552===l?l-16:l,d=oy(o,c),u=new Uint8Array(c);for(let e=0;e<c;e+=16)s.in.set(d.subarray(e,e+16)),s.decrypt(),u.set(s.out,e);if(c<l)n.enqueue(u),a+=c;else{let e=u[c-1];if(0===e||e>16)throw Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");let t=u.subarray(0,c-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new op(n.source),async()=>{let e={stack:[],error:void 0,hasError:!1};try{let i=aG(e,await this.input._getSourceCached({path:t.keyUri,isRoot:!1},ou),!1),r=new op(i.source),a=await r.requestSlice(0,16);if(!a)throw Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:oy(a,16),iv:t.iv}}catch(t){e.error=t,e.hasError=!0}finally{aY(e)}},()=>{n.free()});i=new aQ(o).ref()}else a(!1);else if(i=await this.input._getSourceCached(r),s){let t=i.source.slice(e.location.offset,e.location.length??void 0).ref();i.free(),i=t}return i}),formats:this.input._formats.filter(e=>!(e instanceof sd)),initInput:i??void 0,formatOptions:r});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=ew(this.inputCache,e=>e.age);a(-1!==e),this.inputCache.splice(e,1)}return s}
1async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class a1 extends ip{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??=(async()=>{a(this.input._rootSource instanceof aR);let e=await this.input._reader.requestEntireFile();a(e);let t=oD(e,e.length,{ignore:aa}),{rootPath:i}=this.input._rootSource,r=[],s=[];for(let e=1;e<t.length;e++){let a=t[e];if(a.startsWith(r3)){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=ek(i,n),l=new as(a.slice(r3.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.");r.push({fullPath:o,attributes:l,lineNumber:s,hasOnlyKeyPackets:!1})}else if(a.startsWith(r4)){let t=new as(a.slice(r4.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=ek(i,s);r.push({fullPath:n,attributes:t,lineNumber:e,hasOnlyKeyPackets:!0})}else if(a.startsWith(r8)){let t=new as(a.slice(r8.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 r=null,n=t.get("uri");null!==n&&(r=ek(i,n)),s.push({fullPath:r,attributes:t,lineNumber:e})}else if("#EXT-X-I-FRAMES-ONLY"===a);else if(a.startsWith(r6)){let e=new a0(this,i,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(r.map(async(e,t)=>{let r,l=[],c=e.attributes.get("codecs");if(c)r=c.split(",").map(e=>e.trim());else{let t=this.getSegmentedInputForPath(e.fullPath),i=await t.getTrackBackings(),a=await Promise.all(i.map(async e=>({track:e,codec:await e.getCodec()})));r=await Promise.all(a.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}let d=e.attributes.get("video"),u=e.attributes.get("audio"),h=r.some(e=>e$.includes(ta(e))),m=r.some(e=>eG.includes(ta(e)));if(null!==d&&!h){if(!n.includes(d))throw Error(`Invalid M3U8 file; variant stream references video group "${d}" which is not defined in any #EXT-X-MEDIA tags.`);let e=s.find(e=>{let t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===d&&"video"===i.toLowerCase()});t:if(e){let t=e.attributes.get("uri");if(null===t)break t;let s=ek(i,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);a(null!==l),r.push(l)}}if(null!==u&&!m){if(!o.includes(u))throw Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);let e=s.find(e=>{let t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"audio"===i.toLowerCase()});t:if(e){let t=e.attributes.get("uri");if(null===t)break t;let s=ek(i,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);a(null!==l),r.push(l)}}r=[...new Set(r)];let f=null,p=null,g=e.attributes.getAsNumber("bandwidth");a(null!==g);let k=e.attributes.getAsNumber("average-bandwidth"),y=e.attributes.get("name");for(let i of r){let r=ta(i);if(null!==r){if(e$.includes(r)){if(null!==f)throw Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");f=i;let r=e.attributes.get("video");if(null===r){let i=e.attributes.get("resolution"),r=null,a=null;if(i){let e=i.match(/^(\d+)x(\d+)$/);e&&(r=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:f,pairingMask:1n<<BigInt(t),peakBitrate:g,averageBitrate:k,name:y,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"video",width:r,height:a}})}else{if(!n.includes(r))throw Error(`Invalid M3U8 file; variant stream references video group "${r}" which is not defined in any #EXT-X-MEDIA tags.`);for(let i of s){let a=i.attributes.get("group-id"),s=i.attributes.get("type");if(a!==r||"video"!==s.toLowerCase())continue;let n=i.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:a8(i.attributes),autoselect:a8(i.attributes)||a6(i.attributes),languageCode:a5(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:f,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:i.attributes.get("name"),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"video",width:o,height:c}})}}}else if(eG.includes(r)){if(null!==p)throw Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");p=i;let r=e.attributes.get("audio");if(null===r){let i=e.attributes.get("channels"),r=null!==i?Number(i.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:y,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==r&&Number.isInteger(r)&&r>0?r:null}})}else{if(!o.includes(r))throw Error(`Invalid M3U8 file; variant stream references audio group "${r}" which is not defined in any #EXT-X-MEDIA tags.`);for(let i of s){let a=i.attributes.get("group-id"),s=i.attributes.get("type");if(a!==r||"audio"!==s.toLowerCase())continue;let n=i.attributes.get("channels")??e.attributes.get("channels"),o=null!==n?Number(n.split("/")[0]):null;l.push({id:-1,demuxer:this,backingTrack:null,default:a8(i.attributes),autoselect:a8(i.attributes)||a6(i.attributes),languageCode:a5(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:p,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:i.attributes.get("name"),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==o&&Number.isInteger(o)&&o>0?o:null}})}}}}}return l})),c=[],d=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)d(t);for(let e of(c.sort((e,t)=>
1e.lineNumber-t.lineNumber),this.trackBackings=[],c))"video"===e.info.type?this.trackBackings.push(new a3(e)):this.trackBackings.push(new a4(e));this.internalTracks=c})()}async getTrackBackings(){return await this.readMetadata(),a(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let i=null;return this.internalTracks&&(i=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))),t=new a0(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return r2}dispose(){if(this.segmentedInputs){for(let e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class a2{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??=(async()=>{let e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath),t=null,i=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof a3){for(let e of i)if(await e.getCodec()===this.getCodec()){t=e;break}}else for(let e of(a(this instanceof a4),i))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{...eN,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(){a(this.internalTrack.demuxer.internalTracks);let e=this.internalTrack.info.type,t=0;for(let i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}
vendor: 1,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 a3 extends a2{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ta(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 a4 extends a2{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ta(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 a8=e=>{let t=e.get("default");if(null===t)return!1;let i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},a6=e=>{let t=e.get("autoselect");if(null===t)return!1;let i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},a5=e=>{if(null===e)return"und";let t=e.split("-")[0];return t||"und"};class a7{constructor(){this._isIsobmff=!1}}
1class a9 extends a7{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 i=oR(t,4);return"ftyp"!==i&&"styp"!==i?null:oR(t,4)}_createDemuxer(e){return new iz(e)}}class se extends a9{async _canReadInput(e){let t=await this._getMajorBrand(e);if(null!==t)return"qt  "!==t;let i=e._reader.requestSlice(4,4);if(i instanceof Promise&&(i=await i),!i)return!1;let r=oR(i,4);return"moof"===r||"sidx"===r}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class st extends a9{async _canReadInput(e){return"qt  "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class si extends a7{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,16);if(i instanceof Promise&&(i=await i),!i)return!1;let r=rt(i);if(null===r||r<1||r>8||rr(i,r)!==ab.EBML)return!1;let a=rs(i);if("number"!=typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(s instanceof Promise&&(s=await s),!s)return!1;let n=i.filePos;for(;s.filePos<=n+a-2;){let e=rn(s);if(!e)break;let{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case ab.EBMLVersion:case ab.EBMLReadVersion:if(1!==rr(s,r))return!1;break;case ab.DocType:if(ro(s,r)!==t)return!1;break;case ab.DocTypeVersion:if(rr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new rg(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class sr extends si{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class sa extends a7{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,oO);if(i instanceof Promise&&(i=await i),!i)break;let r=oV(i);if(!r)break;t=i.filePos+r.size}let i=await rb(e._reader,t,t+4096);if(!i)return!1;let r=i.header,a=tk(r.mpegVersionId,r.channel),s=e._reader.requestSlice(i.startPos+a,4);if(s instanceof Promise&&(s=await s),!s)return!1;let n=oP(s);if(0x58696e67===n||0x496e666f===n)return!0;t=i.startPos+i.header.totalSize;let o=await rb(e._reader,t,t+4);if(!o)return!1;let l=o.header;return r.channel===l.channel&&r.sampleRate===l.sampleRate}_createDemuxer(e){return new rT(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class ss extends a7{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=await t),!t)return!1;let i=oR(t,4);return("RIFF"===i||"RIFX"===i||"RF64"===i)&&(t.skip(4),"WAVE"===oR(t,4))}_createDemuxer(e){return new rM(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class sn extends a7{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=await t),!!t&&"OggS"===oR(t,4)}_createDemuxer(e){return new r_(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class so extends a7{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,oO);if(i instanceof Promise&&(i=await i),!i)break;let r=oV(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return i instanceof Promise&&(i=await i),!!i&&"fLaC"===oR(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new rV(e)}}
1class sl extends a7{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,oO);if(i instanceof Promise&&(i=await i),!i)break;let r=oV(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(i instanceof Promise&&(i=await i),!i)return!1;let r=rD(i);if(!r||(t+=r.frameLength,(i=e._reader.requestSliceRange(t,7,9))instanceof Promise&&(i=await i),!i))return!1;let a=rD(i);return!!a&&r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration}_createDemuxer(e){return new rz(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class sc extends a7{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=await t),!t)return!1;let i=oy(t,205);return 71===i[0]&&71===i[188]||71===i[0]&&71===i[204]||71===i[4]&&71===i[196]||!1}_createDemuxer(e){return new r$(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class sd extends a7{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=await t),!t||"#EXTM3U"!==oR(t,7))return!1;if(!(e._rootSource instanceof aR))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 a1(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return r2}}let su=new se,sh=new st,sm=new si,sf=new sr,sp=new sa,sg=new ss,sk=new sn,sy=new sl,sw=new so,sb=new sc,sT=new sd,sS=[sT,su,sh,sm,sf,sg,sk,sw,sp,sy,sb],sA=[sT,su,sh,sp,sy,sb],sv=new Map,sP=new Map,sC=e=>e$.includes(e)?sx(e):!!eG.includes(e)&&sE(e),sx=async(e,t={})=>{if(!e$.includes(e))return!1;((e,t)=>{if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.codec&&"string"!=typeof t.codec)throw TypeError("options.codec, when provided, must be a string.");if(void 0!==t.codec&&ta(t.codec)!==e)throw TypeError(`options.codec, when provided, must match the specified codec (${e}).`);if(void 0!==t.codedWidth&&(!Number.isInteger(t.codedWidth)||t.codedWidth<=0))throw TypeError("options.codedWidth, when provided, must be a positive integer.");if(void 0!==t.codedHeight&&(!Number.isInteger(t.codedHeight)||t.codedHeight<=0))throw TypeError("options.codedHeight, when provided, must be a positive integer.");if(void 0!==t.displayAspectWidth&&(!Number.isInteger(t.displayAspectWidth)||t.displayAspectWidth<=0))throw TypeError("options.displayAspectWidth, when provided, must be a positive integer.");if(void 0!==t.displayAspectHeight&&(!Number.isInteger(t.displayAspectHeight)||t.displayAspectHeight<=0))throw TypeError("options.displayAspectHeight, when provided, must be a positive integer.");if(void 0!==t.description&&!A(t.description))throw TypeError("options.description, when provided, must be a buffer source.");if(void 0!==t.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw TypeError("options.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==t.optimizeForLatency&&"boolean"!=typeof t.optimizeForLatency)throw TypeError("options.optimizeForLatency, when provided, must be a boolean.")})(e,t);let i={...t,codedWidth:t.codedWidth??1280,codedHeight:t.codedHeight??720,codec:t.codec??e5(e,1280,720,1e6,!1)};i.description??=void 0;let r=JSON.stringify(i),a=sv.get(r);if(a)return a;let s=(async()=>!!nO.some(t=>t.supports(e,i))||"undefined"!=typeof VideoDecoder&&!0===(await VideoDecoder.isConfigSupported(i)).supported)();return sv.set(r,s),s},sE=async(e,t={})=>{if(!eG.includes(e))return!1;((e,t)=>{if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.codec&&"string"!=typeof t.codec)throw TypeError("options.codec, when provided, must be a string.");if(void 0!==t.codec&&ta(t.codec)!==e)throw TypeError(`options.codec, when provided, must match the specified codec (${e}).`);if(void 0!==t.numberOfChannels&&(!Number.isInteger(t.numberOfChannels)||t.numberOfChannels<=0))throw TypeError("options.numberOfChannels, when provided, must be a positive integer.");if(void 0!==t.sampleRate&&(!Number.isInteger(t.sampleRate)||t.sampleRate<=0))throw TypeError("options.sampleRate, when provided, must be a positive integer.");if(void 0!==t.description&&!A(t.description))throw TypeError("options.description, when provided, must be a buffer source.")})(e,t);let i={...t,numberOfChannels:t.numberOfChannels??2,sampleRate:t.sampleRate??48e3,codec:t.codec??te(e,2,48e3)};if(void 0===i.description){let e=(e=>{switch(e.codec){case"flac":{let t=eh("ZkxhQ4AAACIQABAAAAYtACWtCsRC8AANRBhVFucAcYu5ASE2m1Dxv8tw");if(e.sampleRate>=1048576||e.numberOfChannels>8)return!1;return t[18]=e.sampleRate>>>12,t[19]=e.sampleRate>>>4,t[20]=(15&e.sampleRate)<<4|e.numberOfChannels-1<<1,t}case"vorbis":{let t=eh
vendor: 5,505 bytes, line 1
1("Ah7/AgF2b3JiaXMAAAAAAoC7AAAAAAAAgLUBAAAAAAC4AQN2b3JiaXMNAAAATGF2ZjU4Ljc2LjEwMAgAAAAMAAAAbGFuZ3VhZ2U9dW5kGQAAAGhhbmRsZXJfbmFtZT1Tb3VuZEhhbmRsZXIWAAAAdmVuZG9yX2lkPVswXVswXVswXVswXSAAAABlbmNvZGVyPUxhdmM1OC4xMzQuMTAwIGxpYnZvcmJpcxAAAABtYWpvcl9icmFuZD1pc29tEQAAAG1pbm9yX3ZlcnNpb249NTEyIgAAAGNvbXBhdGlibGVfYnJhbmRzPWlzb21pc28yYXZjMW1wNDEmAAAAREVTQ1JJUFRJT049TWFkZSB3aXRoIFJlbW90aW9uIDQuMC4yNzgBBXZvcmJpcyVCQ1YBAEAAACRzGCpGpXMWhBAaQlAZ4xxCzmvsGUJMEYIcMkxbyyVzkCGkoEKIWyiB0JBVAABAAACHQXgUhIpBCCGEJT1YkoMnPQghhIg5eBSEaUEIIYQQQgghhBBCCCGERTlokoMnQQgdhOMwOAyD5Tj4HIRFOVgQgydB6CCED0K4moOsOQghhCQ1SFCDBjnoHITCLCiKgsQwuBaEBDUojILkMMjUgwtCiJqDSTX4GoRnQXgWhGlBCCGEJEFIkIMGQcgYhEZBWJKDBjm4FITLQagahCo5CB+EIDRkFQCQAACgoiiKoigKEBqyCgDIAAAQQFEUx3EcyZEcybEcCwgNWQUAAAEACAAAoEiKpEiO5EiSJFmSJVmSJVmS5omqLMuyLMuyLMsyEBqyCgBIAABQUQxFcRQHCA1ZBQBkAAAIoDiKpViKpWiK54iOCISGrAIAgAAABAAAEDRDUzxHlETPVFXXtm3btm3btm3btm3btm1blmUZCA1ZBQBAAAAQ0mlmqQaIMAMZBkJDVgEACAAAgBGKMMSA0JBVAABAAACAGEoOogmtOd+c46BZDppKsTkdnEi1eZKbirk555xzzsnmnDHOOeecopxZDJoJrTnnnMSgWQqaCa0555wnsXnQmiqtOeeccc7pYJwRxjnnnCateZCajbU555wFrWmOmkuxOeecSLl5UptLtTnnnHPOOeecc84555zqxekcnBPOOeecqL25lpvQxTnnnE/G6d6cEM4555xzzjnnnHPOOeecIDRkFQAABABAEIaNYdwpCNLnaCBGEWIaMulB9+gwCRqDnELq0ehopJQ6CCWVcVJKJwgNWQUAAAIAQAghhRRSSCGFFFJIIYUUYoghhhhyyimnoIJKKqmooowyyyyzzDLLLLPMOuyssw47DDHEEEMrrcRSU2011lhr7jnnmoO0VlprrbVSSimllFIKQkNWAQAgAAAEQgYZZJBRSCGFFGKIKaeccgoqqIDQkFUAACAAgAAAAABP8hzRER3RER3RER3RER3R8RzPESVREiVREi3TMjXTU0VVdWXXlnVZt31b2IVd933d933d+HVhWJZlWZZlWZZlWZZlWZZlWZYgNGQVAAACAAAghBBCSCGFFFJIKcYYc8w56CSUEAgNWQUAAAIACAAAAHAUR3EcyZEcSbIkS9IkzdIsT/M0TxM9URRF0zRV0RVdUTdtUTZl0zVdUzZdVVZtV5ZtW7Z125dl2/d93/d93/d93/d93/d9XQdCQ1YBABIAADqSIymSIimS4ziOJElAaMgqAEAGAEAAAIriKI7jOJIkSZIlaZJneZaomZrpmZ4qqkBoyCoAABAAQAAAAAAAAIqmeIqpeIqoeI7oiJJomZaoqZoryqbsuq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq7ruq4LhIasAgAkAAB0JEdyJEdSJEVSJEdygNCQVQCADACAAAAcwzEkRXIsy9I0T/M0TxM90RM901NFV3SB0JBVAAAgAIAAAAAAAAAMybAUy9EcTRIl1VItVVMt1VJF1VNVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVN0zRNEwgNWQkAkAEAkBBTLS3GmgmLJGLSaqugYwxS7KWxSCpntbfKMYUYtV4ah5RREHupJGOKQcwtpNApJq3WVEKFFKSYYyoVUg5SIDRkhQAQmgHgcBxAsixAsiwAAAAAAAAAkDQN0DwPsDQPAAAAAAAAACRNAyxPAzTPAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAA0DwP8DwR8EQRAAAAAAAAACzPAzTRAzxRBAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABA0jRA8zxA8zwAAAAAAAAAsDwP8EQR0DwRAAAAAAAAACzPAzxRBDzRAwAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEOAAABBgIRQasiIAiBMAcEgSJAmSBM0DSJYFTYOmwTQBkmVB06BpME0AAAAAAAAAAAAAJE2DpkHTIIoASdOgadA0iCIAAAAAAAAAAAAAkqZB06BpEEWApGnQNGgaRBEAAAAAAAAAAAAAzzQhihBFmCbAM02IIkQRpgkAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAGHAAAAgwoQwUGrIiAIgTAHA4imUBAIDjOJYFAACO41gWAABYliWKAABgWZooAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAYcAAACDChDBQashIAiAIAcCiKZQHHsSzgOJYFJMmyAJYF0DyApgFEEQAIAAAocAAACLBBU2JxgEJDVgIAUQAABsWxLE0TRZKkaZoniiRJ0zxPFGma53meacLzPM80IYqiaJoQRVE0TZimaaoqME1VFQAAUOAAABBgg6bE4gCFhqwEAEICAByKYlma5nmeJ4qmqZokSdM8TxRF0TRNU1VJkqZ5niiKommapqqyLE3zPFEURdNUVVWFpnmeKIqiaaqq6sLzPE8URdE0VdV14XmeJ4qiaJqq6roQRVE0TdNUTVV1XSCKpmmaqqqqrgtETxRNU1Vd13WB54miaaqqq7ouEE3TVFVVdV1ZBpimaaqq68oyQFVV1XVdV5YBqqqqruu6sgxQVdd1XVmWZQCu67qyLMsCAAAOHAAAAoygk4wqi7DRhAsPQKEhKwKAKAAAwBimFFPKMCYhpBAaxiSEFEImJaXSUqogpFJSKRWEVEoqJaOUUmopVRBSKamUCkIqJZVSAADYgQMA2IGFUGjISgAgDwCAMEYpxhhzTiKkFGPOOScRUoox55yTSjHmnHPOSSkZc8w556SUzjnnnHNSSuacc845KaVzzjnnnJRSSuecc05KKSWEzkEnpZTSOeecEwAAVOAAABBgo8jmBCNBhYasBABSAQAMjmNZmuZ5omialiRpmud5niiapiZJmuZ5nieKqsnzPE8URdE0VZXneZ4oiqJpqirXFUXTNE1VVV2yLIqmaZqq6rowTdNUVdd1XZimaaqq67oubFtVVdV1ZRm2raqq6rqyDFzXdWXZloEsu67s2rIAAPAEBwCgAhtWRzgpGgssNGQlAJABAEAYg5BCCCFlEEIKIYSUUggJAAAYcAAACDChDBQashIASAUAAIyx1lprrbXWQGettdZaa62AzFprrbXWWmuttdZaa6211lJrrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmuttdZaa6211lprrbXWWmstpZRSSimllFJKKaWUUkoppZRSSgUA+lU4APg/2LA6wknRWGChISsBgHAAAMAYpRhzDEIppVQIMeacdFRai7FCiDHnJKTUWmzFc85BKCGV1mIsnnMOQikpxVZjUSmEUlJKLbZYi0qho5JSSq3VWIwxqaTWWoutxmKMSSm01FqLMRYjbE2ptdhqq7EYY2sqLbQYY4zFCF9kbC2m2moNxggjWywt1VprMMYY3VuLpbaaizE++NpSLDHWXAAAd4MDAESCjTOsJJ0VjgYXGrISAAgJACAQUooxxhhzzjnnpFKMOeaccw5CCKFUijHGnHMOQgghlIwx5pxzEEIIIYRSSsaccxBCCCGEkFLqnHMQQgghhBBKKZ1zDkIIIYQQQimlgxBCCCGEEEoopaQUQgghhBBCCKmklEIIIYRSQighlZRSCCGEEEIpJaSUUgohhFJCCKGElFJKKYUQQgillJJSSimlEkoJJYQSUikppRRKCCGUUkpKKaVUSgmhhBJKKSWllFJKIYQQSikFAAAcOAAABBhBJxlVFmGjCRcegEJDVgIAZAAAkKKUUiktRYIipRikGEtGFXNQWoqocgxSzalSziDmJJaIMYSUk1Qy5hRCDELqHHVMKQYtlRhCxhik2HJLoXMOAAAAQQCAgJAAAAMEBTMAwOAA4XMQdAIERxsAgCBEZohEw0JweFAJEBFTAUBigkIuAFRYXKRdXECXAS7o4q4DIQQhCEEsDqCABByccMMTb3jCDU7QKSp1IAAAAAAADADwAACQXAAREdHMYWRobHB0eHyAhIiMkAgAAAAAABcAfAAAJCVAREQ0cxgZGhscHR4fICEiIyQBAIAAAgAAAAAggAAEBAQAAAAAAAIAAAAEBA=="),
1i=u(t);return i.setUint8(15,e.numberOfChannels),i.setUint32(16,e.sampleRate,!0),t}default:return}})(i);if(!1===e)return!1;i.description=e}let r=JSON.stringify(i),a=sP.get(r);if(a)return a;let s=(async()=>!!(nU.some(t=>t.supports(e,i))||eK.includes(e))||"undefined"!=typeof AudioDecoder&&!0===(await AudioDecoder.isConfigSupported(i)).supported)();return sP.set(r,s),s},s_=async()=>{let[e,t]=await Promise.all([sI(),sB()]);return[...e,...t]},sI=async(e=e$,t)=>{let i=await Promise.all(e.map(e=>sx(e,t)));return e.filter((e,t)=>i[t])},sB=async(e=eG,t)=>{let i=await Promise.all(e.map(e=>sE(e,t)));return e.filter((e,t)=>i[t])};var sF=function(e,t,i){if(null!=t){var r,a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");if(i){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!=typeof r)throw TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},sM=(au="function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r},function(e){function t(t){e.error=e.hasError?new au(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var i,r=0;return function a(){for(;i=e.stack.pop();)try{if(!i.async&&1===r)return r=0,e.stack.push(i),Promise.resolve().then(a);if(i.dispose){var s=i.dispose.call(i.value);if(i.async)return r|=2,Promise.resolve(s).then(a,function(e){return t(e),a()})}else r|=1}catch(e){t(e)}if(1===r)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()});ep();let sR=-1/0,sD=-1/0,sz=null;"undefined"!=typeof FinalizationRegistry&&(sz=new FinalizationRegistry(e=>{let t=performance.now();"video"===e.type?(t-sR>=1e3&&(eR._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."),sR=t),"undefined"!=typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-sD>=1e3&&(eR._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."),sD=t),"undefined"!=typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class sO{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}let sU=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],sN=new Set(sU);class sW{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(X*this.timestamp)}get microsecondDuration(){return Math.trunc(X*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||!sN.has(t.format))throw TypeError("init.format must be one of: "+sU.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("Eac
1h 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&&eS(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 i=t.layout??sY(t.format,t.codedWidth,t.codedHeight),r=t.colorSpace??null;null===r&&(r="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._doNotCopy?d(e):d(e).slice(),this._layout=i,this.colorSpace=new sQ(r)}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&&eS(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 sQ(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&&eS(t.visibleRect,"init.visibleRect"),"undefined"!=typeof VideoFrame)return new sW(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*X),duration:Math.trunc((t.duration??0)*X)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;
1if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw TypeError("Could not determine dimensions.");let a=t.visibleRect??{left:0,top:0,width:i,height:r},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 sQ({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else if(e instanceof sO){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&&!sU.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=e.getColorSpace()}else throw TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=eT({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),sz?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw Error("VideoSample is closed.");return(a(null!==this._data),this._data instanceof sO)?new sW(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):s$(this._data)?new sW(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(a(this._layout),new sW(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 sW(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||(sz?.unregister(this),this._data instanceof sO?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):s$(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(sG(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 s$(this._data)?this._data.allocationSize(e):sZ(this,e).allocationSize}async copyTo(e,t={}){let i;if(!A(e))throw TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(sG(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(a(null!==this._data),s$(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 sO){let i={stack:[],error:void 0,hasError:!1};try{let r=sF(i,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(r instanceof sW))throw TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(r.format))throw Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${r.format}' instead.`);return await r.copyTo(e,t)}catch(e){i.error=e,i.hasError=!0}finally{sM(i)}}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 i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}let r=sZ(this,t);a(this.format);let s=d(e);if(s.byteLength<r.allocationSize)throw TypeError(`Destination buffer too small. Required: ${r.allocationSize}, Available: ${s.byteLength}`);let n=sJ(this.format);if(this._data instanceof sO){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.');i=e}else if(this._data instanceof Uint8Array)a(this._layout),a(this._layout.length===n.length),i=this._layout.map((e,t)=>{let i=Math.ceil(this.codedHeight/n[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{let e=this._data.getContext("2d");a(e),i=[{data:d(e.getImageData(0,0,this.codedWidth,this.codedHeight).data),str
1ide:4*this.codedWidth}]}let o=[],l=n.length;for(let e=0;e<l;e++){let t=r.computedLayouts[e],a=i[e].stride,n=i[e].data,l=t.sourceTop*a;l+=t.sourceLeftBytes;let c=t.destinationOffset,d=t.sourceWidthBytes,u={offset:c,stride:t.destinationStride};for(let e=0;e<t.sourceHeight;e++){if(l+d>n.byteLength)throw Error("Source buffer OOB read.");if(c+d>s.byteLength)throw Error("Destination buffer OOB write.");let e=n.subarray(l,l+d);s.set(e,c),l+=a,c+=t.destinationStride}o.push(u)}if(void 0!==t.format){let e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),i=this.format.includes("X")&&t.format.includes("A");if(e||i)for(let t=0;t<r.allocationSize;t+=4){if(e){let e=s[t],i=s[t+2];s[t]=i,s[t+2]=e}i&&(s[t+3]=255)}}return o}toVideoFrame(){if(this._closed)throw Error("VideoSample is closed.");if(a(null!==this._data),this._data instanceof sO){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)),i=0,r=[];for(let a of e)t.set(a.data,i),r.push(i),i+=a.data.byteLength;return new VideoFrame(t,{format:this.format,layout:e.map((e,t)=>({offset:r[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 s$(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(a(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,l){let c=0,d=0,u=this.displayWidth,h=this.displayHeight,m=0,f=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(c=t,d=i,u=r,h=a,m=s,f=n,void 0!==o?(p=o,g=l):(p=u,g=h)):(m=t,f=i,void 0!==r&&(p=r,g=a)),!("undefined"!=typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!=typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(c))throw TypeError("sx must be a number.");if(!Number.isFinite(d))throw TypeError("sy must be a number.");if(!Number.isFinite(u)||u<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(m))throw TypeError("dx must be a number.");if(!Number.isFinite(f))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:d,sWidth:u,sHeight:h}=this._rotateSourceRegion(c,d,u,h,this.rotation));let k=this.toCanvasImageSource();e.save();let y=m+p/2,w=f+g/2;e.translate(y,w),e.rotate(this.rotation*Math.PI/180);let b=this.rotation%180==0?1:p/g;e.scale(1/b,b),e.drawImage(k,c,d,u,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){let i,r,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.");
1if(!["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&&sX(t.crop,"options.");let n=e.canvas.width,o=e.canvas.height,l=t.rotation??this.rotation,[c,d]=l%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],u=t.crop;u&&(u=sK(u,c,d));let{sx:h,sy:m,sWidth:f,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??c,t.crop?.height??d,l);if("fill"===t.fit)i=0,r=0,a=n,s=o;else{let[e,l]=t.crop?[t.crop.width,t.crop.height]:[c,d],u="contain"===t.fit?Math.min(n/e,o/l):Math.max(n/e,o/l);a=e*u,s=l*u,i=(n-a)/2,r=(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,m,f,p,i,r,a,s),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){let r=e.width,a=e.height,[s,n]=i.rotation%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,l=i.crop?i.crop.height:n,c=0;2*r<o&&2*a<l&&(c=Math.floor(Math.log2(Math.min(o/r,l/a))));let d=r*2**c,u=a*2**c,{canvas:h,context:m,isNew:f}=c>0?sj(d,u):{canvas:e,context:t,isNew:i.targetIsFresh};m.imageSmoothingQuality="high",i.fillBlack?(m.fillStyle="black",m.fillRect(0,0,d,u)):f||m.clearRect(0,0,d,u),this.drawWithFit(m,{fit:i.fit,rotation:i.rotation,crop:i.crop}),m.globalCompositeOperation="copy";for(let e=c;e>1;e--){let t=r*2**e,i=a*2**e;m.drawImage(h,0,0,t,i,0,0,t/2,i/2)}m.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw Error("VideoSample is closed.");if(a(null!==this._data),!(this._data instanceof sO||this._data instanceof Uint8Array))return this._data;{let e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}}async transform(e){let t,i;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&&sX(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");let r=s(this.rotation+(e.rotate??0)),[a,n]=r%180==0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=e.crop;o&&(o=sK(o,a,n));let l=o?o.width:a,c=o?o.height:n,d=l/c;void 0!==e.width&&void 0===e.height?i=(t=e.width)/d:void 0===e.width&&void 0!==e.height?t=(i=e.height)*d:void 0!==e.width&&void 0!==e.height?(t=e.width,i=e.height):(t=l,i=c);let u={width:t=L(t,e.roundDimensionsTo??1),height:i=L(i,e.roundDimensionsTo??1),fit:e.fit??"fill",rotation:r,crop:o??{left:0,top:0,width:a,height:n},alpha:e.alpha??"keep"};for(let e of sV){let t=e(this,u);if(t instanceof Promise&&(t=await t),null!==t)return t}let{canvas:h,context:m,isNew:f}=sj(u.width,u.height);return this._drawWithFitAndMipmapping(h,m,{fit:u.fit,rotation:u.rotation,crop:u.crop,targetIsFresh:f,fillBlack:"discard"===u.alpha}),new sW(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 sV=[],sL=e=>{sV.includes(e)||sV.push(e)},sq=[],sH=0,sj=(e,t)=>{let i;for(let i of sq)if(i.canvas.width===e&&i.canvas.height===t)return i.age=sH++,{canvas:i.canvas,context:i.context,isNew:!1};if("undefined"!=typeof OffscreenCanvas)i=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().");(i=document.createElement("canvas")).width=e,i.height=t}let r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return sq.length>=3&&sq.splice(ew(sq,e=>e.age),1),sq.push({canvas:i,context:r,age:sH++}),{canvas:i,context:r,isNew:!0}};class sQ{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(g);if(null!=e.primaries&&!t.includes(e.primaries))throw TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);let i=Object.keys(y);if(null!=e.transfer&&!i.includes(e.transfer))throw TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);let r=Object.keys(b);if(null!=e.matrix&&!r.includes(e.matrix))throw TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.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 s$=e=>"undefined"!=typeof VideoFrame&&e instanceof VideoFrame,sK=(e,t,i)=>{let r=Math.min(e.left,t),s=Math.min(e.top,i),n=Math.min(e.width,t-r),o=Math.min(e.height,i-s);return a(n>=0),a(o>=0),{left:r,top:s,width:n,height:o}},sX=(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.")},sG=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.")}},sY=(e,t,i)=>{let r=sJ(e),a=[],s=0;for(let e of r){let r=Math.ceil(t/e.widthDivisor),n=Math.ceil(i/e.heightDivisor),o=r*e.sampleBytes,l=o*n;a.push({offset:s,stride:o}),s+=l}return a},sJ=e=>{let t=(e,t,i,r,a)=>{let s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:z(e),a(!1)}},sZ=(e,t)=>{let i,r=s0({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))i=t.format;else throw Error("NotSupportedError: Invalid destination format.");else i=e.format;return s2(r,i,a)},s0=(e,t,i,r,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)>i)throw TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)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(!s1(a,s))throw TypeError("visibleRect alignment is invalid for the format.");return s},s1=(e,t)=>{if(null===e)return!0;let i=sJ(e);for(let e=0;e<i.length;e++){let r=i[e],a=r.widthDivisor,s=r.heightDivisor;if((t.x||0)%a!=0||(t.y||0)%s!=0)return!1}return!0},s2=(e,t,i)=>{let r=sJ(t),a=r.length;if(void 0!==i&&i.length!==a)throw TypeError(`Layout must have ${a} planes.`);let s=0,n=[],o=[];for(let t=0;t<a;t++){let a=r[t],l=a.sampleBytes,c=a.widthDivisor,d=a.heightDivisor,u={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(u.sourceTop=Math.ceil(Math.trunc(e.y||0)/d),u.sourceHeight=Math.ceil(Math.trunc(e.height||0)/d),u.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/c)*l,u.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/c)*l,void 0!==i){let e=i[t];if(e.stride<u.sourceWidthBytes)throw TypeError(`Stride for plane ${t} is too small.`);u.destinationOffset=e.offset,u.destinationStride=e.stride}
1else u.destinationOffset=s,u.destinationStride=u.sourceWidthBytes;let h=u.destinationStride*u.sourceHeight+u.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 i=n[e];if(!(o[t]<=i.destinationOffset)&&!(o[e]<=u.destinationOffset))throw TypeError("Planes overlap.")}n.push(u)}return{allocationSize:s,computedLayouts:n}},s3=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class s4{constructor(){this._referenceCount=0}}class s8{get microsecondTimestamp(){return Math.trunc(X*this.timestamp)}get microsecondDuration(){return Math.trunc(X*this.duration)}constructor(e){if(this._closed=!1,ne(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 s4){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!s3.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(!s3.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 i=e.data.byteLength/(s6(e.format)*e.numberOfChannels);if(!Number.isInteger(i))throw TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=i,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=i/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 r=this.numberOfFrames*this.numberOfChannels*s6(this.format);if(t.byteLength<r)throw TypeError("Invalid AudioDataInit: insufficient data size.");this._data=t}sz?.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&&!s3.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,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw RangeError("frameOffset out of range");let r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw RangeError("frameCount out of range");let a=s6(t),s=s5(t);if(s&&e.planeIndex>=this.numberOfChannels||!s&&0!==e.planeIndex)throw RangeError("planeIndex out of range");return(s?r:r*this.numberOfChannels)*a}copyTo(e,t){if(!A(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&&!s3.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:i,frameCount:r,frameOffset:a}=t,{planeIndex:s}=t,n=this.format,o=i??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!==r?r:l-d;if(h>l-d)throw RangeError("frameCount out of range");let m=s6(o),f=s5(o);if(f&&s>=c||!f&&0!==s)throw RangeError("planeIndex out of range");let p=f?h:h*c;if(e.byteLength<p*m)throw RangeError("Destination buffer is too small");let g=u(e),k=s9(o);if(ne(this._data))et()&&c>2&&o!==n?nt(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=s7(n),i=s6(n),r=s5(n);if(this._data instanceof s4){let t=e=>{let t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw TypeError("getDataPlane() must return a Uint8Array.");let a=l*i*(r?1:c);if(t.byteLength!==a)throw TypeError(`Data plane ${e}
1 has invalid size. Expected exactly ${a} bytes, got ${t.byteLength} bytes.`);return t};if(r)if(f)e=t(s),s=0;else{e=new Uint8Array(l*i*c);for(let r=0;r<c;r++){let a=t(r);e.set(a,r*l*i)}}else e=t(0)}else e=this._data;let a=u(e);for(let e=0;e<h;e++)if(f)k(g,e*m,t(a,r?(s*l+(e+d))*i:((e+d)*c+s)*i));else for(let s=0;s<c;s++)k(g,(e*c+s)*m,t(a,r?(s*l+(e+d))*i:((e+d)*c+s)*i))}}clone(){if(this._closed)throw Error("AudioSample is closed.");if(this._data instanceof s4){let e=new s8(this._data);return e.setTimestamp(this.timestamp),e}if(!ne(this._data))return new s8({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data});{let e=new s8(this._data.clone());return e.setTimestamp(this.timestamp),e}}trim(e,t=this.numberOfFrames){let i;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 r=t-e,a=s6(this.format);if(s5(this.format)){let t=r*a;if(i=new Uint8Array(t*this.numberOfChannels),r>0)for(let a=0;a<this.numberOfChannels;a++)this.copyTo(i.subarray(a*t,(a+1)*t),{planeIndex:a,format:this.format,frameOffset:e,frameCount:r})}else i=new Uint8Array(r*this.numberOfChannels*a),r>0&&this.copyTo(i,{planeIndex:0,format:this.format,frameOffset:e,frameCount:r});return new s8({data:i,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(sz?.unregister(this),this._data instanceof s4?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):ne(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 s4?this._createAudioDataFromData():ne(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(s5(this.format)){let e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{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 i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw 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 i=e.numberOfChannels,r=e.sampleRate,a=e.length,s=Math.floor(24e4/i),n=0,o=a;for(;o>0;){let a=Math.min(s,o),l=new Float32Array(i*a);for(let t=0;t<i;t++)e.copyFromChannel(l.subarray(t*a,(t+1)*a),t,n);yield new s8({format:"f32-planar",sampleRate:r,numberOfFrames:a,numberOfChannels:i,timestamp:t+n/r,data:l}),n+=a,o-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let i=e.numberOfChannels,r=e.sampleRate,a=e.length,s=Math.floor(24e4/i),n=0,o=a,l=[];for(;o>0;){let a=Math.min(s,o),c=new Float32Array(i*a);for(let t=0;t<i;t++)e.copyFromChannel(c.subarray(t*a,(t+1)*a),t,n);let d=new s8({format:"f32-planar",sampleRate:r,numberOfFrames:a,numberOfChannels:i,timestamp:t+n/r,data:c});l.push(d),n+=a,o-=a}return l}}let s6=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")}},s5=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},s7=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)}},s9=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,W((i+1)*127.5,0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,W(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,W(Math.round(0x7fffffff*i),-0x80000000,0x7fffffff),
1!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},ne=e=>"undefined"!=typeof AudioData&&e instanceof AudioData,nt=(e,t,i,r,a,s,n,o)=>{let l=s7(i),c=s9(r),d=s6(i),h=s6(r),m=s5(i);if(s5(r))if(m){let r=new ArrayBuffer(o*d),a=u(r);e.copyTo(r,{planeIndex:s,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++){let i=e*d;c(t,e*h,l(a,i))}}else{let r=new ArrayBuffer(o*a*d),m=u(r);e.copyTo(r,{planeIndex:0,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++){let i=(e*a+s)*d;c(t,e*h,l(m,i))}}else if(m){let r=new ArrayBuffer(o*d),s=u(r);for(let u=0;u<a;u++){e.copyTo(r,{planeIndex:u,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++){let i=e*d;c(t,(e*a+u)*h,l(s,i))}}}else{let r=new ArrayBuffer(o*a*d),s=u(r);e.copyTo(r,{planeIndex:0,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++)for(let i=0;i<a;i++){let r=e*a+i,n=r*d;c(t,r*h,l(s,n))}}},ni=new Map,nr=new Map,na=e=>{if(!e||"object"!=typeof e)throw TypeError("Encoding config must be an object.");if(!e$.includes(e.codec))throw TypeError(`Invalid video codec '${e.codec}'. Must be one of: ${e$.join(", ")}.`);let t=e.bitrate;if(void 0===e.quality&&void 0===t)throw TypeError("config.quality must be provided.");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 nd))throw TypeError("config.quality, when provided, must be a Quality.");if(void 0!==t&&!(t instanceof nd)&&(!Number.isInteger(t)||t<=0))throw TypeError("config.bitrate, when provided, must be a positive integer or a quality.");
1if(void 0!==e.keyFrameInterval&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError("config.keyFrameInterval, when provided, must be a non-negative number.");if(void 0!==e.sizeChangeBehavior&&!["deny","passThrough","fill","contain","cover"].includes(e.sizeChangeBehavior))throw TypeError("config.sizeChangeBehavior, when provided, must be 'deny', 'passThrough', 'fill', 'contain' or 'cover'.");if(void 0!==e.transform){if("object"!=typeof e.transform||!e.transform)throw TypeError("config.transform, when provided, must be an object.");if(void 0!==e.transform.width&&(!Number.isInteger(e.transform.width)||e.transform.width<=0))throw TypeError("config.transform.width, when provided, must be a positive integer.");if(void 0!==e.transform.height&&(!Number.isInteger(e.transform.height)||e.transform.height<=0))throw TypeError("config.transform.height, when provided, must be a positive integer.");if(void 0!==e.transform.fit&&!["fill","contain","cover"].includes(e.transform.fit))throw TypeError('config.transform.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.transform.width&&void 0!==e.transform.height&&void 0===e.transform.fit&&!["fill","contain","cover"].includes(e.sizeChangeBehavior))throw TypeError("When both config.transform.width and config.transform.height are provided, config.transform.fit must also be provided.");if(void 0!==e.transform.fit&&["fill","contain","cover"].includes(e.sizeChangeBehavior)&&e.transform.fit!==e.sizeChangeBehavior)throw TypeError("config.transform.fit, when provided, cannot differ from config.sizeChangeBehavior when config.sizeChangeBehavior is 'fill', 'contain' or 'cover', as sizeChangeBehavior already determines the fitting algorithm.");if(void 0!==e.transform.rotate&&![0,90,180,270].includes(e.transform.rotate))throw TypeError("config.transform.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.transform.crop&&sX(e.transform.crop,"config.transform."),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.transform.frameRate&&(!Number.isFinite(e.transform.frameRate)||e.transform.frameRate<=0))throw TypeError("config.transform.frameRate, when provided, must be a finite positive number.");if(void 0!==e.transform.force&&"boolean"!=typeof e.transform.force)throw TypeError("config.transform.force, when provided, must be a boolean.")}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.");ns(e.codec,e)},ns=(e,t)=>{if(!t||"object"!=typeof t)throw TypeError("Encoding options must be an object.");if(void 0!==t.alpha&&!["discard","keep"].includes(t.alpha))throw TypeError("options.alpha, when provided, must be 'discard' or 'keep'.");let i=t.bitrateMode;if(void 0!==i&&!["constant","variable"].includes(i))throw TypeError("bitrateMode, when provided, must be 'constant' or 'variable'.");if(void 0!==t.latencyMode&&!["quality","realtime"].includes(t.latencyMode))throw TypeError("latencyMode, when provided, must be 'quality' or 'realtime'.");if(void 0!==t.fullCodecString&&"string"!=typeof t.fullCodecString)throw TypeError("fullCodecString, when provided, must be a string.");if(void 0!==t.fullCodecString&&ta(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`);if(void 0!==t.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(t.hardwareAcceleration))throw TypeError("hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==t.scalabilityMode&&"string"!=typeof t.scalabilityMode)throw TypeError("scalabilityMode, when provided, must be a string.");if(void 0!==t.contentHint&&"string"!=typeof t.contentHint)throw TypeError("contentHint, when provided, must be a string.")},nn=e=>
1{let t=e.bitrateMode,i=e.quality._toVideoRateControl(e.codec,e.width,e.height,t),r=(t,i,r)=>({codec:e.fullCodecString??e5(e.codec,e.width,e.height,r,"keep"===e.alpha),width:e.width,height:e.height,displayWidth:e.squarePixelWidth,displayHeight:e.squarePixelHeight,bitrate:t,bitrateMode:i,alpha:e.alpha??"discard",framerate:e.framerate,latencyMode:e.latencyMode,hardwareAcceleration:e.hardwareAcceleration,scalabilityMode:e.scalabilityMode,contentHint:e.contentHint,...(e=>"avc"===e?{avc:{format:"avc"}}:"hevc"===e?{hevc:{format:"hevc"}}:{})(e.codec)}),s=[];return null!==i.quantizer&&s.push({config:r(void 0,"quantizer",i.bitrate),quantizer:i.quantizer}),"quantizer"!==i.bitrateMode&&s.push({config:r(i.bitrate,i.bitrateMode,i.bitrate),quantizer:null}),a(s.length>0),s},no=e=>{if(!e||"object"!=typeof e)throw TypeError("Encoding config must be an object.");if(!eG.includes(e.codec))throw TypeError(`Invalid audio codec '${e.codec}'. Must be one of: ${eG.join(", ")}.`);let t=e.bitrate;if(void 0===e.quality&&void 0===t&&!(eK.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 nd))throw TypeError("config.quality, when provided, must be a Quality.");if(void 0!==t&&!(t instanceof nd)&&(!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.");nl(e.codec,e)},nl=(e,t)=>{if(!t||"object"!=typeof t)throw TypeError("Encoding options must be an object.");let i=t.bitrateMode;if(void 0!==i&&!["constant","variable"].includes(i))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&&ta(t.fullCodecString)!==e)throw TypeError(`fullCodecString, when provided, must be a string that matches the specified codec (${e}).`)},nc=e=>{let t=e.bitrateMode;return{codec:e.fullCodecString??te(e.codec,e.numberOfChannels,e.sampleRate),numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,bitrate:e.quality?._toAudioBitrate(e.codec),bitrateMode:e.quality?._bitrateMode??t,...(e=>"aac"===e?{aac:{format:"aac"}}:"opus"===e?{opus:{format:"opus"}}:{})(e.codec)}};class nd{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 nu):"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?nu[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,i,r){let s,n=nh[e],o=null,l=this._bitrateMode??r??"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 if(void 0===this._bitrate&&n&&!this._preferBitrate){let e;a(void 0!==this._quality),o=W(Math.round((e=n.worst,e+(n.best-e)*this._quality)),n.min,n.max)}if(void 0!==this._bitrate)s=this._bitrate;else{let r=this._quality;void 0===r&&(a(null!==o&&n),r=W((o-n.worst)/(n.best-n.worst),0,1)),s=nf(e,t,i,nm(r))}return{quantizer:o,bitrate:s,bitrateMode:l}}_toVideoBitrate(e,t,i){return void 0!==this._bitrate?this._bitrate:(a(void 0!==this._quality),nf(e,t,i,nm(this._quality)))}_toAudioBitrate(e){if(eK.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=nm(this._quality),i={aac:128e3,opus:64e3,mp3:16e4,vorbis:64e3,ac3:384e3,eac3:192e3,dts:768e3}[e];if(!i)throw Error(`Unhandled codec: ${e}`);let r=i*t;return"aac"===e?r=[96e3,128e3,16e4,192e3].reduce((e,t)=>
1Math.abs(t-r)<Math.abs(e-r)?t:e):"opus"===e||"vorbis"===e?r=Math.max(6e3,r):"mp3"===e&&(r=[8e3,16e3,24e3,32e3,4e4,48e3,64e3,8e4,96e3,112e3,128e3,16e4,192e3,224e3,256e3,32e4].reduce((e,t)=>Math.abs(t-r)<Math.abs(e-r)?t:e)),1e3*Math.round(r/1e3)}}let nu={"very-low":0,low:.25,medium:.5,high:.75,"very-high":1},nh={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}},nm=e=>.3*Math.exp(2.5538*e),nf=(e,t,i,r)=>1e3*Math.ceil(3e6*Math.pow(t*i/2073600,.95)*({avc:1,hevc:.6,vp9:.6,av1:.4,vp8:1.2,prores:73.33333333333333})[e]*r/1e3),np=(e,t)=>"avc"===e?{avc:{quantizer:t}}:"hevc"===e?{hevc:{quantizer:t}}:"vp9"===e?{vp9:{quantizer:t}}:"av1"===e?{av1:{quantizer:t}}:void a(!1),ng=new nd("very-low"),nk=new nd("low"),ny=new nd("medium"),nw=new nd("high"),nb=new nd("very-high"),nT=e=>{if(e$.includes(e))return nS(e);if(eG.includes(e))return nA(e);if(eY.includes(e))return nP(e);throw TypeError(`Unknown codec '${e}'.`)},nS=async(e,t={})=>{let i,{width:r=1280,height:a=720,quality:s,bitrate:n,...o}=t;if(!e$.includes(e))return!1;if(!Number.isInteger(r)||r<=0)throw TypeError("width must be a positive integer.");if(!Number.isInteger(a)||a<=0)throw TypeError("height must be a positive integer.");if(void 0!==s&&!(s instanceof nd))throw TypeError("quality, when provided, must be a Quality.");if(void 0!==s&&void 0!==n)throw TypeError("quality and bitrate cannot both be provided.");if(void 0!==n&&!(n instanceof nd)&&(!Number.isInteger(n)||n<=0))throw TypeError("bitrate must be a positive integer or a quality.");ns(e,o);let l=nv(s,n)??new nd("medium");try{i=nn({codec:e,width:r,height:a,quality:l,framerate:void 0,...o,alpha:"discard"})}catch{return!1}let c=JSON.stringify(i),d=ni.get(c);if(d)return d;let u=(async()=>{for(let{config:t}of i)if(nN.some(i=>i.supports(e,t)))return!0;if("undefined"==typeof VideoEncoder||(r%2==1||a%2==1)&&("avc"===e||"hevc"===e))return!1;for(let{config:t,quantizer:s}of i){try{if(!(await VideoEncoder.isConfigSupported(t)).supported)continue}catch{continue}if(!er()||await new Promise(async i=>{try{let n=new VideoEncoder({output:()=>{},error:()=>i(!1)});n.configure(t);let o=new Uint8Array(r*a*4),l=new VideoFrame(o,{format:"RGBA",codedWidth:r,codedHeight:a,timestamp:0});n.encode(l,null!==s?np(e,s):void 0),l.close(),await n.flush(),i(!0)}catch{i(!1)}}))return!0}return!1})();return ni.set(c,u),u},nA=async(e,t={})=>{let{numberOfChannels:i=2,sampleRate:r=48e3,quality:a,bitrate:s,...n}=t;if(!eG.includes(e))return!1;if(!Number.isInteger(i)||i<=0)throw TypeError("numberOfChannels must be a positive integer.");if(!Number.isInteger(r)||r<=0)throw TypeError("sampleRate must be a positive integer.");if(void 0!==a&&!(a instanceof nd))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 nd)&&(!Number.isInteger(s)||s<=0))throw TypeError("bitrate must be a positive integer.");nl(e,n);let o=nc({codec:e,numberOfChannels:i,sampleRate:r,quality:nv(a,s)??new nd("medium"),...n}),l=JSON.stringify(o),c=nr.get(l);if(c)return c;let d=(async()=>{if(nW.some(t=>t.supports(e,o))||eK.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 nr.set(l,d),d},nv=(e,t)=>void 0!==e?e:void 0!==t?t instanceof nd?t:new nd({bitrate:t}):void 0,nP=async e=>!!eY.includes(e),nC=async()=>{let[e,t,i]=await Promise.all([nx(),nE(),n_()]);return[...e,...t,...i]},nx=async(e=e$,t)=>{let i=await Promise.all(e.map(e=>nS(e,t)));return e.filter((e,t)=>i[t])},nE=async(e=eG,t)=>{let i=await Promise.all(e.map(e=>nA(e,t)));return e.filter((e,t)=>i[t])},n_=async(e=eY)=>{let t=await Promise.all(e.map(nP));return e.filter((e,i)=>t[i])},nI=async(e,t)=>{for(let i of e)if(await nS(i,t))return i;return null},nB=async(e,t)=>{for(let i of e)if(await nA(i,t))return i;return null},nF=async e=>{for(let t of e)if(await nP(t))return t;return null};class nM{static supports(e,t){return!1}}
1class nR{static supports(e,t){return!1}}class nD{static supports(e,t){return!1}}class nz{static supports(e,t){return!1}}let nO=[],nU=[],nN=[],nW=[],nV=e=>{if(e.prototype instanceof nM){if(nO.includes(e))return void eR._warn("Video decoder already registered.");nO.push(e),sv.clear()}else if(e.prototype instanceof nR){if(nU.includes(e))return void eR._warn("Audio decoder already registered.");nU.push(e),sP.clear()}else throw TypeError("Decoder must be a CustomVideoDecoder or CustomAudioDecoder.")},nL=e=>{if(e.prototype instanceof nD){if(nN.includes(e))return void eR._warn("Video encoder already registered.");nN.push(e),ni.clear()}else if(e.prototype instanceof nz){if(nW.includes(e))return void eR._warn("Audio encoder already registered.");nW.push(e),nr.clear()}else throw TypeError("Encoder must be a CustomVideoEncoder or CustomAudioEncoder.")},nq=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.")},nH=e=>{if(!eg(e))throw TypeError("timestamp must be a number.")},nj=(e,t,i)=>i.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;let i=await e.determinePacketType(t);return i&&(t.type=i),t}):t;class nQ{constructor(e){if(!(e instanceof n5))throw TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(nq(e),this._track.input._disposed)throw new of;return nj(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){nq(e);let t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(nH(e),nq(t),this._track.input._disposed)throw new of;return nj(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof ik))throw TypeError("packet must be an EncodedPacket.");if(nq(t),this._track.input._disposed)throw new of;return nj(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(nH(e),nq(t),this._track.input._disposed)throw new of;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);let i=await this._track._backing.getKeyPacket(e,t);return i&&(a("key"===i.type),"delta"===await this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i}async getNextKeyPacket(e,t={}){if(!(e instanceof ik))throw TypeError("packet must be an EncodedPacket.");if(nq(t),this._track.input._disposed)throw new of;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);let i=await this._track._backing.getNextKeyPacket(e,t);return i&&(a("key"===i.type),"delta"===await this._track.determinePacketType(i))?this.getNextKeyPacket(i,t):i}packets(e,t,i={}){if(void 0!==e&&!(e instanceof ik))throw TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!i?.metadataOnly)throw TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof ik))throw TypeError("endPacket must be an EncodedPacket.");if(nq(i),this._track.input._disposed)throw new of;let r=[],{promise:a,resolve:s}=B(),{promise:n,resolve:o}=B(),l=!1,c=!1,d=null,u=!1,h=[],m=()=>Math.max(2,h.length);(async()=>{let d=e??await this.getFirstPacket(i);for(;d&&!c&&!this._track.input._disposed&&!(t&&d.sequenceNumber>=t?.sequenceNumber);){if(r.length>m()){({promise:n,resolve:o}=B()),await n;continue}r.push(d),s(),({promise:a,resolve:s}=B()),d=await this.getNextPacket(d,i)}l=!0,s()})().catch(e=>{u||(d=e,u=!0,s())});let f=this._track;return{async next(){for(;;)if(f.input._disposed)throw new of;else if(c)return{value:void 0,done:!0};else if(u)throw d;else if(r.length>0){let e=r.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 n${constructor(e,t){this.onSample=e,this.onError=t}}class nK{mediaSamplesInRange(e=-1/0,t=1/0,i){nH(e),nH(t);let r=[],a=!1,s=null,{promise:n,resolve:o}=B(),{promise:l,resolve:c}=B(),d=!1,u=!1,h=!1,m=null,f=null,p=!1,g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{m=await this._createDecoder(i=>{if(c(),i.timestamp>=t&&(u=!0),u)return void i.close();s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),{promise:n,resolve:o}=B())},e=>{p||(f=e,p=!0,o())});let i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g),y=k,w=i.packets(k??void 0,void 0,g);for(await w.next();y&&!u&&!this._track.input._disposed;){let e=nX(r.length);if(r.length+m.getDecodeQueueSize()>e){({promise:l,resolve:c}=B()),await l;continue}m.decode(y);let t=await w.next();if(t.done)break;y=t.value}await w.return(),h||this._track.input._disposed||await m.flush(),!a&&s&&r.push(s),d=!0,o()})().catch(e=>{p||(f=e,p=!0,o())}).finally(()=>{m?.close()});let k=this._track,y=()=>{for(let e of(s?.close(),r))e.close()};return{async next(){for(;;)if(k.input._disposed)throw y(),new of;else if(h)return{value:void 0,done:!0};else if(p)throw y(),f;else if(r.length>0){let e=r.shift();return c(),{value:e,done:!1}}else{if(d)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,u=!0,c(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw TypeError("Argument must be an iterable or async iterable.");let i=D(e),r=[],s=[],{promise:n,resolve:o}=B(),{promise:l,resolve:c}=B(),d=!1,u=!1,h=null,m=null,f=!1,p=e=>{s.push(e),o(),{promise:n,resolve:o}=B()},g={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i<t;i++)p(i<t-1?e.clone():e);else e.close()},e=>{f||(m=e,f=!0,o())});let e=this._createPacketSink(),t=null,n=null,k=-1,y=async()=>{a(n),a(h);let t=n;for(h.decode(t);t.sequenceNumber<k;){let i=nX(s.length);for(;s.length+h.getDecodeQueueSize()>i&&!u;)({promise:l,resolve:c}=B()),await l;if(u)break;let r=await e.getNextPacket(t,g);a(r),h.decode(r),t=r}k=-1},w=async()=>{a(h),await h.flush();for(let e=0;e<r.length;e++)p(null);r.length=0};for await(let a of i){if(nH(a),u||this._track.input._disposed)break;let i=await e.getPacket(a,g),s=i&&await e.getKeyPacket(a,g);if(!s){-1!==k&&(await y(),await w()),p(null),t=null;continue}t&&(s.sequenceNumber!==n.sequenceNumber||i.timestamp<t.timestamp)&&(await y(),await w()),r.push(i.timestamp),k=Math.max(i.sequenceNumber,k),t=i,n=s}u||this._track.input._disposed||(-1!==k&&await y(),await w()),d=!0,o()})().catch(e=>{f||(m=e,f=!0,o())}).finally(()=>{h?.close()});let k=this._track,y=()=>{for(let e of s)e?.close()};return{async next(){for(;;)if(k.input._disposed)throw y(),new of;else if(u)return{value:void 0,done:!0};else if(f)throw y(),m;else if(s.length>0){let e=s.shift();return a(void 0!==e),c(),{value:e,done:!1}}else{if(d)return{value:void 0,done:!0};await n}},return:async()=>(u=!0,c(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}let nX=e=>0===e?40:8;class nG extends n${constructor(e,t,i,r,s,n){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=s,this.timeResolution=n,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer
1=new Z,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];let o=nO.find(e=>e.supports(i,r));if(o)this.customDecoder=new o,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof sW))throw TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{let e=e=>{if(this.alphaQueue.length>0){let t=this.alphaQueue.shift();a(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===i&&this.decoderConfig.description&&es()){let e=tF(d(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){let t=tR(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"})}}let t=Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(a(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>
10&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(a(this.decoder),et()||I(this.inputTimestamps,e.timestamp,e=>e),es()&&0===this.currentPacketIndex){if("avc"===this.codec){var t,i;let r=[],a=!1;for(let t of tP(e.data,this.decoderConfig)){let i=tC(e.data[t.offset]);if(a||=i>=1&&i<=5,i===ag.AUD)if(a)break;else r.length=0;i>=20&&i<=31||r.push(e.data.subarray(t.offset,t.offset+t.length))}e=new ik((t=r,!(i=this.decoderConfig).description?t_(t):tI(t,(3&d(i.description)[4])+1)),e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){let t=((e,t)=>{var i,r;let a=new Set,s=ay.audAllowed;for(let i of tz(e,t)){if(s===ay.noMoreDataAllowed){a.add(i.offset);continue}let t=tO(e[i.offset]);if(s===ay.eoBitstreamAllowed&&37!==t){a.add(i.offset);continue}let r=!1;35===t?s>ay.audAllowed?r=!0:s=ay.beforeFirstVcl:t<=31?s>ay.afterFirstVcl?r=!0:s=ay.afterFirstVcl:36===t?s!==ay.afterFirstVcl?r=!0:s=ay.eoBitstreamAllowed:37===t?s<ay.afterFirstVcl?r=!0:s=ay.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?s>ay.beforeFirstVcl?r=!0:s=ay.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&s<ay.afterFirstVcl&&(r=!0),r&&a.add(i.offset)}if(0===a.size)return null;let n=[];for(let i of tz(e,t))a.has(i.offset)||n.push(e.subarray(i.offset,i.offset+i.length));return i=n,(r=t).description?tI(i,(3&d(r.description)[21])+1):t_(i)})(e.data,this.decoderConfig);t&&(e=new ik(t,e.type,e.timestamp,e.duration))}}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new nJ),!this.alphaDecoder){let e=e=>{if(this.colorQueue.length>0){let t=this.colorQueue.shift();a(void 0!==t),this.mergeAlpha(t,e)}else this.alphaQueue.push(e);for(this.decodedAlphaChunkCount++;this.nullAlphaFrameQueue.length>0&&this.nullAlphaFrameQueue[0]===this.decodedAlphaChunkCount;)if(this.nullAlphaFrameQueue.shift(),this.colorQueue.length>0){let e=this.colorQueue.shift();a(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(e){this.onError(e)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}let t=tZ(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>
10&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(let t of tz(e,this.decoderConfig)){let i=tO(e[t.offset]);if(i===ak.RASL_N||i===ak.RASL_R)return!0}return!1}sampleHandler(e){if(et()){if(this.sampleQueue.length>0&&e.timestamp>=n(this.sampleQueue).timestamp){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}I(this.sampleQueue,e,e=>e.timestamp)}else{let t=this.inputTimestamps.shift();a(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){let i=B();this.mergeAlphaPromises.push(i.promise);let r={sample:null};this.finalSamples.push(r);try{if(t){a(this.merger);let i=await this.merger.merge(e,t);r.sample=new sW(i)}else r.sample=new sW(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){let e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(e){F(this.finalSamples,r),this.onError(e)}finally{F(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(a(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),et()){for(let e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){for(let e of(this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(a(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close()),this.sampleQueue))e.close();this.sampleQueue.length=0}}let nY=null;class nJ{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!nY){let e=new Blob([`(${nZ.toString()})()`],{type:"application/javascript"});nY=URL.createObjectURL(e)}let e=W(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){let e=new Worker(nY);e.addEventListener("message",e=>{let t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{let t=Error(e.message||"Color/alpha merge worker error.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}let i=this.nextRequestId++,r=B();this.pendingRequests.set(i,r);let a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(let e of this.workers)e.terminate();this.workers.length=0;let e=Error("Color/alpha merger closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}let nZ=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{let{id:t,color:a,alpha:s}=e.data;i=i.then(async()=>{try{let e=await r(a,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{a.close(),s.close()}})});let r=async(e,t)=>{let i=e.format,r=t.format;if(!i||!r)throw Error("CPU color/alpha merging requires a known VideoFrame format.");let o=i.includes("P10"),l=i.includes("P12"),c=r.includes("P10"),d=r.includes("P12");
1if(c!==o||d!==l)throw Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return await a(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return await s(e,t,i);if("NV12"===i)return await n(e,t);throw Error(`CPU color/alpha merging does not support format '${i}'.`)},a=async(e,t,i)=>{let r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=new Uint8Array(4*s);await e.copyTo(n);let l=await o(t,r,a,1);for(let e=0,t=3;e<s;e++,t+=4)n[t]=l[e];let c={format:"RGBX"===i||"RGBA"===i?"RGBA":"BGRA",codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[n.buffer]};return new VideoFrame(n,c)},s=async(e,t,i)=>{let r,a,s=e.visibleRect?.width??e.codedWidth,n=e.visibleRect?.height??e.codedHeight,l=i.includes("P10"),c=i.includes("P12"),d=l||c?2:1;i.startsWith("I420")?(r=Math.ceil(s/2),a=Math.ceil(n/2)):(r=i.startsWith("I422")?Math.ceil(s/2):s,a=n);let u=s*n,h=u*d,m=r*a*d,f=new Uint8Array(h+2*m+u*d);await e.copyTo(f);let p=await o(t,s,n,d);f.set(p,h+2*m);let g={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:s,codedHeight:n,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[f.buffer]};return new VideoFrame(f,g)},n=async(e,i)=>{let r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),l=e.allocationSize();t&&t.byteLength===l||(t=new Uint8Array(l)),await e.copyTo(t);let c=new Uint8Array(s+2*n+s);c.set(t.subarray(0,s),0);let d=s+n;for(let e=0;e<n;e++)c[s+e]=t[s+2*e],c[d+e]=t[s+2*e+1];let u=await o(i,r,a,1);c.set(u,s+2*n);let h={format:"I420A",codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[c.buffer]};return new VideoFrame(c,h)},o=async(t,i,r,a)=>{let s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e);let n=t.format;if("RGBA"!==n&&"BGRA"!==n&&"RGBX"!==n&&"BGRX"!==n)return e.subarray(0,i*r*a);{let t=2*("RGBA"!==n&&"RGBX"!==n),a=i*r;for(let i=0;i<a;i++)e[i]=e[4*i+t];return e.subarray(0,a)}}},n0=e=>{if(!e||"object"!=typeof e)throw TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!=typeof e.optimizeForLatency)throw TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};
1class n1 extends nK{constructor(e,t={}){if(!(e instanceof oe))throw TypeError("videoTrack must be an InputVideoTrack.");n0(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!await this._track.canDecode())throw Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");let i=await this._track.getCodec(),r=await this._track.getRotation(),s=await this._track.getDecoderConfig(),n=await this._track.getTimeResolution();return a(i&&s),new nG(e,t,i,s={...s,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},r,n)}_createPacketSink(){return new nQ(this._track)}async getSample(e,t={}){for await(let i of(nH(e),this.mediaSamplesAtTimestamps([e],t)))return i;throw Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class n2{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof oe))throw TypeError("videoTrack must be an InputVideoTrack.");if(t&&"object"!=typeof t)throw TypeError("options must be an object.");if(void 0!==t.alpha&&"boolean"!=typeof t.alpha)throw TypeError("options.alpha, when provided, must be a boolean.");if(void 0!==t.width&&(!Number.isInteger(t.width)||t.width<=0))throw TypeError("options.width, when defined, must be a positive integer.");if(void 0!==t.height&&(!Number.isInteger(t.height)||t.height<=0))throw TypeError("options.height, when defined, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&sX(t.crop,"options."),void 0!==t.poolSize&&("number"!=typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&n0(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new n1(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??=(async()=>{let e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[s,n]=i%180==0?[r,a]:[a,r],o=e.crop;o&&(o=sK(o,s,n));let[l,c]=o?[o.width,o.height]:[s,n],d=l/c;void 0!==e.width&&void 0===e.height?c=Math.round((l=e.width)/d):void 0===e.width&&void 0!==e.height?l=Math.round((c=e.height)*d):void 0!==e.width&&void 0!==e.height&&(l=e.width,c=e.height),this._width=l,this._height=c,this._rotation=i,this._crop=o})()}_videoSampleToWrappedCanvas(e){let t=this._width,i=this._height,r=this._canvasPool[this._nextCanvasIndex],s=!1;r||("undefined"!=typeof document?((r=document.createElement("canvas")).width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),s=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);let n=r.getContext("2d",{alpha:this._alpha||er()});a(n),e._drawWithFitAndMipmapping(r,n,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:s,fillBlack:!this._alpha&&er()});let o={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),o}async getCanvas(e,t){nH(e),await this._ensureInit();let i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async *canvases(e,t,i){await this._ensureInit(),yield*N(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async *canvasesAtTimestamps(e,t){await this._ensureInit(),yield*N(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class n3 extends n${constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer
1=new Z,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;let a=t=>{let i=t.timestamp;this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);let a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();let s=r.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=nU.find(e=>e.supports(i,r));if(s)this.customDecoder=new s,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof s8))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 s8(e))}catch(e){this.onError(e)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(a(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--)):(a(this.decoder),this.expectedFirstTimestamp??=e.timestamp,this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(a(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(a(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class n4 extends n${constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,a(eK.includes(i.codec)),this.codec=i.codec;let{dataType:r,sampleSize:s,littleEndian:n}=tr(this.codec);switch(this.inputSampleSize=s,s){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1);let a=(1<<(i=((240&r)>>4)+5)|(15&r)<<i-4|1<<i-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=85^e;128&r&&(r&=-129,t=-1);let a=0;return a=4!=(i=((240&r)>>4)+4)?1<<i|(15&r)<<i-4|1<<i-5:r<<1|1,0===t?a:-a})(e.getUint8(t)):a(!1);break;case 2:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint16(t,n)-32768:"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,n):a(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>O(e,t,n)-8388608:"signed"===r?this.readInputValue=(e,t)=>O(e,t,n)<<8>>8:a(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,n)-0x80000000:"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,n):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,n):a(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,n):a(!1);break;default:z(s),a(!1)}switch(s){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:z(s),a(!1)}}getDecodeQueueSize(){return 0}decode(e){let t=u(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=new ArrayBuffer(i*this.decoderConfig.numberOfChannels*this.outputSampleSize),a=new DataView(r);for(let e=0;e<i*this.decoderConfig.numberOfChannels;e++){let i=e*this.inputSampleSize,r=e*this.outputSampleSize,s=this.readInputValue(t,i);this.writeOutputValue(a,r,s)}let s=i/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 s8({format:this.outputFormat,data:r,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:n});this.onSample(o)}async flush(){}close(){}}class n8 extends nK{constructor(e){if(!(e instanceof ot))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 i=await this._track.getCodec(),r=await this._track.getDecoderConfig();return(a(i&&r),eK.includes(r.codec))?new n4(e,t,r):new n3(e,t,i,r)}_createPacketSink(){return new nQ(this._track)}async getSample(e,t={}){for await(let i of(nH(e),this.mediaSamplesAtTimestamps([e],t)))return i;throw Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class n6{constructor(e){if(!(e instanceof ot))throw TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new n8(e)}_audioSampleToWrappedArrayBuffer(e){let t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){nH(e);let i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return N(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return N(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class n5{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof oe}isAudioTrack(){return this instanceof ot}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return n7(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return n7(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return n7(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return n7(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 n7(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 q((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){let i=new nQ(this),r=1/0,a=-1/0,s=0,n=0;for await(let o of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-r)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-r)).toPrecision(16)):0}}
1async isLive(){return await this._backing.getLiveRefreshInterval()!==null}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof n5))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(on({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(on({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(on({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(on({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(on({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){for(let t of(e&&=n9(e),await this.input.getTracks()))if(this.canBePairedWith(t)&&(!e||await e(t)))return!0;return!1}hasPairableVideoTrack(e){return e&&=n9(e),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&=n9(e),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}let n7=(e,t,i)=>{if(e instanceof Promise)throw Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},n9=e=>{if(void 0!==e&&"function"!=typeof e)throw TypeError("predicate, when provided, must be a function.");return e?t=>{let i=e=>{if("boolean"!=typeof e)throw TypeError("predicate must return or resolve to a boolean value.");return e},r=e(t);return r instanceof Promise?r.then(i):i(r)}:void 0};class oe extends n5{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 n7(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 n7(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return n7(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return n7(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return n7(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return n7(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??=eT({num:await this.get
1SquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()})}get pixelAspectRatio(){return this._pixelAspectRatioCache??=eT({num:n7(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*n7(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:n7(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*n7(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=n7(e,"displayWidth","getDisplayWidth");if(null!==t)return t}let t=n7(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180==0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return n7(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=n7(e,"displayHeight","getDisplayHeight");if(null!==t)return t}let t=n7(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180==0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return n7(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(a(null!==t),nO.some(i=>i.supports(t,e)))return!0;if("undefined"==typeof VideoDecoder)return!1;let i=await VideoDecoder.isConfigSupported(e);return!0===i.supported}catch(e){return eR._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ik))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 i=await this.getDecoderConfig();return a(i),tZ(t,i,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(),i=e.targetPacketCount??256,r=new nQ(this),a=[],s=-1/0,n=0;for await(let e of r.packets(void 0,void 0,{metadataOnly:!0})){if(a.length>=i&&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),d=ol(c,t),u=d??t,h=null!==d?t/d:null,m=new Map,f=1/0,p=-1/0,g=0;for(let e=1;e<l;e++){let t=c[e]-c[e-1],i=null!==h?Math.max(1,Math.round(t/h)):t;m.set(i,(m.get(i)??0)+1),f=Math.min(f,i),p=Math.max(p,i),g+=i}let k=l-1,y=[...m.keys()].sort((e,t)=>e-t),w=k-1>>1,b=k>>1,T=0,S=0,A=0;for(let e of y)if(A+=m.get(e),0===T&&A>w&&(T=e),A>b){S=e;break}let v=(u/T+u/S)/2;return{underlyingFrameRate:d,bestGuessFrameRate:null!==d?d:od(v),minFrameRate:u/p,maxFrameRate:u/f,averageFrameRate:u*k/g,medianFrameRate:v,frameRateIsConstant:null!==d&&1===f&&1===p,probedPacketCount:n}}}class ot extends n5{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return n7(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await this._backing.getHasOnlyKeyPackets?.()??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return n7(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return n7(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(a(null!==t),nU.some(i=>i.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 eR._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ik))throw TypeError("packet must be an EncodedPacket.");return await this.getCodec()===null?null:"key"}}let oi=e=>e??1/0,or=e=>-(e??-1/0),oa=e=>-e,os=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 i=e=>{if("boolean"!=typeof e)throw TypeError("query.filter must return or resolve to a boolean.");return e},r=e.filter(t);return r instanceof Promise?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{let i=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},r=e.sortBy(t);return r instanceof Promise?r.then(i):i(r)}:void 0}},on=(e,t)=>({filter:e?.filter||t?.filter?i=>{let r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return r instanceof Promise?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{let r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return r instanceof Promise||a instanceof Promise?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),oo=async(e,t)=>{let i=e;if(t?.filter){let r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){let t=await Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>
1r[t])}if(!t?.sortBy)return i;let r=i.map(e=>t.sortBy(e)),a=r.some(e=>e instanceof Promise)?await Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{let i=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(i.length,r.length);for(let e=0;e<a;e++){let t=i[e]??0,a=r[e]??0;if(t!==a)return t-a}return 0}).map(e=>e.track)},ol=(e,t)=>{let i=1+1e-9;if(e.length<2)return null;let r=new Float64Array(e.length-1);for(let t=1;t<e.length;t++){let i=e[t]-e[t-1];if(!(i>0))return null;r[t-1]=i}let a=r.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 r){let r=Math.max(1,Math.round(a/s));Math.abs(a-r*s)>=i||(e+=a,t+=r)}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 r){let t=Math.max(1,Math.round(e/s));Math.abs(e-t*s)>=i||(n++,o+=e,l+=t)}if(n/r.length<.98)return null;s=o/l;let c=1/Math.min(l,1e3),d=Math.max(Number.EPSILON,s-c),u=s+c,h=t/u,m=t/d,f=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>m)continue;let t=Math.abs(e/f-1);t<g&&(p=e,g=t)}if(null===p){let e=oc(d,u,1e6),i=oc(h,m,1e6);if(i&&(!e||i.den<e.den||i.den===e.den&&i.num<=e.num))p=i.num/i.den;else{if(!e)return null;p=t*e.den/e.num}}let k=t/p,y=0;for(let e of r){let t=Math.max(1,Math.round(e/k));Math.abs(e-t*k)<i&&y++}return y/r.length<.98?null:p},oc=(e,t,i)=>{for(let r=1;r<=i;r++){let i=Math.floor(e*r)+1;if(i/r<t)return eT({num:i,den:r})}return null},od=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,i=1/0;for(let r of[12,15,20,24,25,30,48,50,60,100,120,144,240]){let a=Math.abs(r/e-1);a<=.025&&a<i&&(t=r,i=a)}return t};ep();let ou=2;class oh extends eI{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 a7)))throw TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof aF||e.source instanceof aM))throw TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof aF&&e.source._disposed)throw TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof oh))throw TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((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.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof aF?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){a(this._rootSource instanceof aR);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 i=this._sourceCache.find(i=>{let r;return i.cacheGroup===t&&(r=i.request,r.path===e.path)});if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());let r=this._sourceCachePromises.find(i=>{let r;return i.cacheGroup===t&&(r=i.request,r.path===e.path)});if(r)return r.promise.then(e=>e.sourceRef.source.ref());let s=(async()=>{let i=await this._getSourceUncached(e);if(ey(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){let e=ew(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);a(-1!==e);let i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),F(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);let r=this._sourceCachePromises.findIndex(t=>t.request===e);return a(-1!==r),this._sourceCachePromises.splice(r,1),{request:e,sourceRef:i,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 op(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 om})()}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),a(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof om)return!1;throw e}}async getFirstTimestamp(e){let t=(e??=await this.getTracks()).filter(e=>null!==e);if(0===t.length)return 0;let i=Math.min(...(await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0})))).map(e=>e?.timestamp??1/0));return i===1/0?0:i}async computeDuration(e,t){let i=(e??=await this.getTracks()).filter(e=>null!==e);return 0===i.length?0:Math.max(...await Promise.all(i.map(e=>e.computeDuration(t))))}async getDurationFromMetadata(e,t){let i=(e??=await this.getTracks()).filter(e=>null!==e),r=(await Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)}async getTracks(e){return e&&=os(e),oo((await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e)),e)}async getVideoTracks(e){return e&&=os(e),oo((await this.getTracks()).filter(e=>e.isVideoTrack()),e)}async getAudioTracks(e){return e&&=os(e),oo((await this.getTracks()).filter(e=>e.isAudioTrack()),e)}async getPrimaryVideoTrack(e){let t=on(e&&=os(e),{sortBy:async e=>[oa((await e.getDisposition()).default),oa(await e.hasPairableAudioTrack()),oa(!await e.hasOnlyKeyPackets()),or(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&=os(e);let t=await this.getPrimaryVideoTrack(),i=on(e,{sortBy:async e=>[oa(!t||e.canBePairedWith(t)),oa((await e.getDisposition()).default),or(await e.getBitrate())]});return(await this.getAudioTracks(i))[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 i="video"===e.getType()?new oe(this,e):new ot(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){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 om extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class of extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class op{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 of;if(e<0||null!==this.fileSizeNonStrict&&e+t>this.fileSizeNonStrict)return null;if(0===t){let t=new Uint8Array(0);return new og(t,u(t),0,e,e)}let i=e+t,r=this.source._read(e,i,0,aI);return r instanceof Promise?r.then(t=>t?new og(t.bytes,t.view,t.offset,e,i):null):r?new og(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new of;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,W(this.fileSizeNonStrict-e,t,i));{let r=this.requestSlice(e,i),s=r=>r||(a(null!==this.fileSizeNonStrict),this.requestSlice(e,W(this.fileSizeNonStrict-e,t,i)));return r instanceof Promise?r.then(s):s(r)}}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 i=this.requestSliceRange(t,0,1024);if(i instanceof Promise&&(i=await i),!i||0===i.length)break;let r=oy(i,i.length);e.push(r),t+=i.length}let i=new Uint8Array(t),r=0;for(let t of e)i.set(t,r),r+=t.length;return new og(i,u(i),0,0,t)})()}}class og{constructor(e,t,i,r,a){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=a,this.bufferPos=r-i}static tempFromBytes(e){return new og(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 og(this.bytes,this.view,this.offset,e,e+t)}}let ok=(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.`)},oy=(e,t)=>{ok(e,t);let i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},ow=e=>(ok(e,1),e.view.getUint8(e.bufferPos++)),ob=(e,t)=>
1{ok(e,2);let i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},oT=e=>{ok(e,2);let t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},oS=e=>{ok(e,3);let t=O(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},oA=e=>{ok(e,2);let t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},ov=(e,t)=>{ok(e,4);let i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},oP=e=>{ok(e,4);let t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},oC=e=>{ok(e,4);let t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},ox=e=>{ok(e,4);let t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},oE=(e,t)=>{let i,r;return t?(i=ov(e,!0),r=ov(e,!0)):(r=ov(e,!1),i=ov(e,!1)),0x100000000*r+i},o_=e=>0x100000000*oP(e)+oP(e),oI=e=>0x100000000*ox(e)+oP(e),oB=e=>{let t=oC(e);return 0x100000000*(e=>{ok(e,4);let t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e)+t},oF=e=>{ok(e,4);let t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},oM=e=>{ok(e,8);let t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},oR=(e,t)=>{ok(e,t);let i="";for(let r=0;r<t;r++)i+=String.fromCharCode(e.bytes[e.bufferPos++]);return i},oD=(e,t,i)=>h.decode(oy(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));!function(e){e[e.Unsynchronisation=128]="Unsynchronisation",e[e.ExtendedHeader=64]="ExtendedHeader",e[e.ExperimentalIndicator=32]="ExperimentalIndicator",e[e.Footer=16]="Footer"}(aP||(aP={})),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"}(aC||(aC={}));let oz=128,oO=10,oU=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Po
1p-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"],oN=(e,t)=>{let i,r=e.filePos;t.raw??={},t.raw.TAG??=oy(e,oz-3),e.filePos=r;let a=oW(e,30);a&&(t.title??=a);let s=oW(e,30);s&&(t.artist??=s);let n=oW(e,30);n&&(t.album??=n);let o=Number.parseInt(oW(e,4),10);Number.isInteger(o)&&o>0&&(t.date??=new Date(String(o)));let l=oy(e,30);if(0===l[28]&&0!==l[29]){let r=l[29];r>0&&(t.trackNumber??=r),e.skip(-30),i=oW(e,28),e.skip(2)}else e.skip(-30),i=oW(e,30);i&&(t.comment??=i);let c=ow(e);c<oU.length&&(t.genre??=oU[c])},oW=(e,t)=>{let i=oy(e,t),r=el(i.indexOf(0),i.length),a=i.subarray(0,r),s="";for(let e=0;e<a.length;e++)s+=String.fromCharCode(a[e]);return s.trimEnd()},oV=e=>{let t=e.filePos,i=oR(e,3),r=ow(e),a=ow(e),s=ow(e),n=oP(e);if("ID3"!==i||255===r||255===a||(0x80808080&n)!=0)return e.filePos=t,null;let o=tw(n);return s&aP.Footer&&(o+=oO),{majorVersion:r,revision:a,flags:s,size:o}},oL=(e,t,i)=>{if(![2,3,4].includes(t.majorVersion))return void eR._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);let r=oy(e,t.flags&aP.Footer?t.size-oO:t.size),a=new oq(t,r);if(t.flags&aP.Unsynchronisation&&3===t.majorVersion&&a.ununsynchronizeAll(),t.flags&aP.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 r=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&aP.Unsynchronisation)),n){eR._warn(`Skipping encrypted ID3v2 frame ${e.id}`),a.pos=s;continue}if(o){eR._warn(`Skipping compressed ID3v2 frame ${e.id}`),a.pos=s;continue}if(l&&a.ununsynchronizeRegion(a.pos,s),i.raw??={},"TXXX"===e.id){let e=i.raw.TXXX??={},t=a.readId3V2TextEncoding(),r=a.readId3V2Text(t,s),n=a.readId3V2Text(t,s);e[r]??=n}else"T"===e.id[0]?i.raw[e.id]??=a.readId3V2EncodingAndText(s):i.raw[e.id]??=a.readBytes(e.size);switch(a.pos=r,e.id){case"TIT2":case"TT2":i.title??=a.readId3V2EncodingAndText(s);break;case"TIT3":case"TT3":i.description??=a.readId3V2EncodingAndText(s);break;case"TPE1":case"TP1":i.artist??=a.readId3V2EncodingAndText(s);break;case"TALB":case"TAL":i.album??=a.readId3V2EncodingAndText(s);break;case"TPE2":case"TP2":i.albumArtist??=a.readId3V2EncodingAndText(s);break;case"TRCK":case"TRK":{let e=a.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.trackNumber??=t),r&&Number.isInteger(r)&&r>0&&(i.tracksTotal??=r)}break;case"TPOS":case"TPA":{let e=a.readId3V2EncodingAndText(s).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.discNumber??=t),r&&Number.isInteger(r)&&r>0&&(i.discsTotal??=r)}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!==oU[e]){i.genre??=oU[e];break}}if(t=/^\d+$/.exec(e)){let e=Number.parseInt(t[0]);if(void 0!==oU[e]){i.genre??=oU[e];break}}i.genre??=e}break;case"TDRC":case"TDAT":{let e=new Date(a.readId3V2EncodingAndText(s));Number.isNaN(e.getTime())||(i.date??=e)}break;case"TYER":case"TYE":{let e=Number.parseInt(a.readId3V2EncodingAndText(s),10);Number.isInteger(e)&&(i.date??=new Date(String(e)))}break;case"USLT":case"ULT":{let e=a.readU8();a.pos+=3,a.readId3V2Text(e,s),i.lyrics??=a.readId3V2Text(e,s)}break;case"COMM":case"COM":{let e=a.readU8();a.pos+=3,a.readId3V2Text(e,s),i.comment??=a.readId3V2Text(e,s)}break;case"APIC":case"PIC":{let e,r=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(r,s);let n=a.readU8(),o=a.readId3V2Text(r,s).trimEnd(),l=s-a.pos;if(l>=0){let t=a.readBytes(l);i.images||(i.images=[]),i.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 oq{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 i=this.bytes[t];e.push(i),255===i&&t!==this.bytes.length-1&&0===this.bytes[t]&&t++}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){let i=[];for(let r=e;r<t;r++){let e=this.bytes[r];i.push(e),255===e&&r!==t-1&&0===this.bytes[r+1]&&r++}let r=this.bytes.subarray(0,e),a=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+i.length+a.length),this.bytes.set(r,0),this.bytes.set(i,r.length),this.bytes.set(a,r.length+i.length),this.view=new DataView(this.bytes.buffer)}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 i=0;i<e;i++)t+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,t}readId3V2Frame(){if(2===this.header.majorVersion){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(),i=4===this.header.majorVersion?tw(t):t,r=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(i)){let e=4===this.header.majorVersion?t:tw(t);s(e)&&(i=e)}return this.pos=a,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){let e=this.readU8();if(e>3)throw Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){let i=this.pos,r=this.readBytes(t-this.pos);switch(e){case aC.ISO_8859_1:{let e="";for(let t=0;t<r.length;t++){let a=r[t];if(0===a){this.pos=i+t+1;break}e+=String.fromCharCode(a)}return e}case aC.UTF_16_WITH_BOM:if(255===r[0]&&254===r[1]){let e=new TextDecoder("utf-16le"),t=el(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2==0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(254===r[0]&&255===r[1]){let e=new TextDecoder("utf-16be"),t=el(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2==0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{let e=el(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),h.decode(r.subarray(0,e))}case aC.UTF_16_BE_NO_BOM:{let e=new TextDecoder("utf-16be"),t=el(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2==0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(0,t))}case aC.UTF_8:{let e=el(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),h.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";let t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class oH{constructor(e){this.helper=new Uint8Array(8),this.helperView=u(this.helper),this.writer=e}writeId3V2Tag(e){let t=this.writer.getPos();this.writeAscii("ID3"),this.writeU8(4),this.writeU8(0),this.writeU8(0),this.writeSynchsafeU32(0);let i=this.writer.getPos(),r=new Set;for(let{key:t,value:i}of ed(e))switch(t){case"title":this.writeId3V2TextFrame("TIT2",i),r.add("TIT2");break;case"description":this.writeId3V2TextFrame("TIT3",i),r.add("TIT3");break;case"artist":this.writeId3V2TextFrame("TPE1",i),r.add("TPE1");break;case"album":this.writeId3V2TextFrame("TALB",i),r.add("TALB");break;case"albumArtist":this.writeId3V2TextFrame("TPE2",i),r.add("TPE2");break;case"trackNumber":{let t=void 0!==e.tracksTotal?`${i}/${e.tracksTotal}`:i.toString();this.writeId3V2TextFrame("TRCK",t),r.add("TRCK")}break;case"discNumber":{let t=void 0!==e.discsTotal?`${i}/${e.discsTotal}`:i.toString();this.writeId3V2TextFrame("TPOS",t),r.add("TPOS")}break;case"genre":this.writeId3V2TextFrame("TCON",i),r.add("TCON");break;case"date":this.writeId3V2TextFrame("TDRC",i.toISOString().slice(0,10)),r.add("TDRC");break;case"lyrics":this.writeId3V2LyricsFrame(i),r.add("USLT");break;case"comment":this.writeId3V2CommentFrame(i),r.add("COMM");break;case"images":{let e={coverFront:3,coverBack:4,unknown:0};for(let t of i){let i=e[t.kind]??0,r=t.description??"";this.writeId3V2ApicFrame(t.mimeType,i,r,t.data)}}break;case"tracksTotal":case"discsTotal":case"raw":break;default:z(t)}if(e.raw)for(let t in e.raw){let i,a=e.raw[t];if(!(null==a||4!==t.length||r.has(t))){if("string"==typeof a)if(f(a)){(i=new Uint8Array(a.length+2))[0]=aC.ISO_8859_1;for(let e=0;e<a.length;
1e++)i[e+1]=a.charCodeAt(e)}else{let e=m.encode(a);(i=new Uint8Array(e.byteLength+2))[0]=aC.UTF_8,i.set(e,1)}else if(a instanceof Uint8Array)i=a;else{if(!("TXXX"===t&&eM(a)))continue;for(let e in a){let t=a[e],i=f(e)&&f(t),r=i?null:m.encode(e),s=i?null:m.encode(t),n=1+(i?e.length:r.byteLength)+1+(i?t.length:s.byteLength)+1;this.writeAscii("TXXX"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(i?aC.ISO_8859_1:aC.UTF_8),i?(this.writeIsoString(e),this.writeIsoString(t)):(this.writer.write(r),this.writeU8(0),this.writer.write(s),this.writeU8(0))}continue}this.writeAscii(t),this.writeSynchsafeU32(i.byteLength),this.writeU16(0),this.writer.write(i)}}let a=this.writer.getPos(),s=a-i;return this.writer.seek(t+6),this.writeSynchsafeU32(s),this.writer.seek(a),s+10}writeU8(e){this.helper[0]=e,this.writer.write(this.helper.subarray(0,1))}writeU16(e){this.helperView.setUint16(0,e,!1),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeAscii(e){for(let t=0;t<e.length;t++)this.helper[t]=e.charCodeAt(t);this.writer.write(this.helper.subarray(0,e.length))}writeSynchsafeU32(e){this.writeU32((e=>{let t=127,i=0,r=e;for(;(0x7fffffff^t)!=0;)i=(r&~t)<<1|r&t,t=(t+1<<8)-1,r=i;return i})(e))}writeIsoString(e){let t=new Uint8Array(e.length+1);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);this.writer.write(t)}writeUtf8String(e){let t=m.encode(e);this.writer.write(t),this.writeU8(0)}writeId3V2TextFrame(e,t){let i=f(t),r=i?t.length:m.encode(t).byteLength;this.writeAscii(e),this.writeSynchsafeU32(1+r+1),this.writeU16(0),this.writeU8(i?aC.ISO_8859_1:aC.UTF_8),i?this.writeIsoString(t):this.writeUtf8String(t)}writeId3V2LyricsFrame(e){let t=f(e),i=5+e.length+1;this.writeAscii("USLT"),this.writeSynchsafeU32(i),this.writeU16(0),this.writeU8(t?aC.ISO_8859_1:aC.UTF_8),this.writeAscii("und"),t?(this.writeIsoString(""),this.writeIsoString(e)):(this.writeUtf8String(""),this.writeUtf8String(e))}writeId3V2CommentFrame(e){let t=f(e),i=t?e.length:m.encode(e).byteLength;this.writeAscii("COMM"),this.writeSynchsafeU32(5+i+1),this.writeU16(0),this.writeU8(t?aC.ISO_8859_1:aC.UTF_8),this.writeU8(117),this.writeU8(110),this.writeU8(100),t?(this.writeIsoString(""),this.writeIsoString(e)):(this.writeUtf8String(""),this.writeUtf8String(e))}writeId3V2ApicFrame(e,t,i,r){let a=f(e)&&f(i),s=a?i.length:m.encode(i).byteLength,n=1+e.length+1+1+s+1+r.byteLength;this.writeAscii("APIC"),this.writeSynchsafeU32(n),this.writeU16(0),this.writeU8(a?aC.ISO_8859_1:aC.UTF_8),a?this.writeIsoString(e):this.writeUtf8String(e),this.writeU8(t),a?this.writeIsoString(i):this.writeUtf8String(i),this.writer.write(r)}}class oj{constructor(e){this.mutex=new v,this.trackTimestampInfo=new WeakMap,this.output=e}onTrackClose(e){}validateTimestamp(e,t,i){if(t<0)throw Error(`Timestamps must be non-negative (got ${t}s).`);let r=this.trackTimestampInfo.get(e);if(r){if(i&&(r.maxTimestampBeforeLastKeyPacket=r.maxTimestamp),null!==r.maxTimestampBeforeLastKeyPacket&&t<r.maxTimestampBeforeLastKeyPacket)throw Error(`Timestamps cannot be smaller than the largest timestamp of the previous GOP (a GOP begins with a key packet and ends right before the next key packet). Got ${t}s, but largest timestamp is ${r.maxTimestampBeforeLastKeyPacket}s.`);r.maxTimestamp=Math.max(r.maxTimestamp,t)}else{if(!i)throw Error("First packet must be a key packet.");r={maxTimestamp:t,maxTimestampBeforeLastKeyPacket:null},this.trackTimestampInfo.set(e,r)}}}class oQ extends oj{constructor(e,t){super(e),this.header=null,this.headerBitstream=null,this.inputIsAdts=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),eU(this.output._metadataTags)||new oH(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/aac"}async addEncodedVideoPacket(){throw Error("ADTS does not support video.")}async addEncodedAudioPacket(e,t,i){let r=await this.mutex.acquire();try{if(this.validateTimestamp(e,t.timestamp,"key"===t.type),null===this.inputIsAdts){th(i,e.source._codec);let t=i?.decoderConfig?.description;if(this.inputIsAdts=!t,!this.inputIsAdts){let e=eq(d(t)),i=ej(e);this.header=i.header,this.headerBitstream=i.bitstream}}if(this.inputIsAdts){let e=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,e)}else{a(this.header);let e=t.data.byteLength+this.header.byteLength;eQ(this.headerBitstream,e);let i=this.writer.getPos();if(this.writer.write(this.header),this.writer.write(t.data),this.format._options.onFrame){let r=new Uint8Array(e);r.set(this.header,0),r.set(t.data,this.header.byteLength),this.format._options.onFrame(r,i)}}await this.writer.flush()}finally{r()}}async addSubtitleCue(){throw Error("ADTS does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(null===this.inputIsAdts)throw Error("Cannot finalize an empty ADTS file: not a single packet was added.");e()}}let o$=new Uint8Array([102,76,97,67]);class oK extends oj{constructor(e,t){super(e),this.metadataWritten=!1,this.blockSizes=[],this.frameSizes=[],this.sampleRate=null,this.channels=null,this.bitsPerSample=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.writer.write(o$);let t=this.output.tracks[0];a(t?.isAudioTrack()),t.metadata.decoderConfig&&(th({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.applyDecoderConfig(t.metadata.decoderConfig)),e()}applyDecoderConfig(e){a(e.description),this.sampleRate=e.sampleRate,this.channels=e.numberOfChannels;let t=new eW(d(e.description));t.skipBits(167),this.bitsPerSample=t.readBits(5)+1,this.format._options.appendOnly&&this.writeHeader({minimumBlockSize:16,maximumBlockSize:65535,minimumFrameSize:0,maximumFrameSize:0,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:0})}writeHeader({bitsPerSample:e,minimumBlockSize:t,maximumBlockSize:i,minimumFrameSize:r,maximumFrameSize:s,sampleRate:n,channels:o,totalSamples:l}){a(4===this.writer.getPos());
1let c=!eU(this.output._metadataTags),d=new eW(new Uint8Array(4));d.writeBits(1,Number(!c)),d.writeBits(7,aw.STREAMINFO),d.writeBits(24,34),this.writer.write(d.bytes);let u=new eW(new Uint8Array(18));if(u.writeBits(16,t),u.writeBits(16,i),u.writeBits(24,r),u.writeBits(24,s),u.writeBits(20,n),u.writeBits(3,o-1),u.writeBits(5,e-1),l>=0x100000000)throw Error("This muxer only supports writing up to 2 ** 32 samples");u.writeBits(4,0),u.writeBits(32,l),this.writer.write(u.bytes),this.writer.write(new Uint8Array(16))}writePictureBlock(e){let t=32+e.mimeType.length+(e.description?.length??0)+e.data.length,i=new Uint8Array(t),r=0,s=u(i);s.setUint32(r,"coverFront"===e.kind?3:4*("coverBack"===e.kind)),r+=4,s.setUint32(r,e.mimeType.length),r+=4,i.set(m.encode(e.mimeType),8),r+=e.mimeType.length,s.setUint32(r,e.description?.length??0),r+=4,i.set(m.encode(e.description??""),r),r+=e.description?.length??0,r+=16,s.setUint32(r,e.data.length),r+=4,i.set(e.data,r),a((r+=e.data.length)===t);let n=new eW(new Uint8Array(4));n.writeBits(1,0),n.writeBits(7,aw.PICTURE),n.writeBits(24,t),this.writer.write(n.bytes),this.writer.write(i)}writeVorbisCommentAndPictureBlock(){if(this.format._options.appendOnly||this.writer.seek(38+o$.byteLength),eU(this.output._metadataTags)){this.metadataWritten=!0;return}for(let e of this.output._metadataTags.images??[])this.writePictureBlock(e);let e=t1(new Uint8Array(0),this.output._metadataTags,!1),t=new eW(new Uint8Array(4));t.writeBits(1,1),t.writeBits(7,aw.VORBIS_COMMENT),t.writeBits(24,e.length),this.writer.write(t.bytes),this.writer.write(e),this.metadataWritten=!0}async getMimeType(){return"audio/flac"}async addEncodedVideoPacket(){throw Error("FLAC does not support video.")}async addEncodedAudioPacket(e,t,i){let r=await this.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,"key"===t.type),null===this.sampleRate&&(th(i,e.source._codec),a(i),a(i.decoderConfig),this.applyDecoderConfig(i.decoderConfig)),this.metadataWritten||this.writeVorbisCommentAndPictureBlock();let r=og.tempFromBytes(t.data);r.skip(2);let s=oy(r,2),n=new eW(s),o=rU(n.readBits(4));if(null===o)throw Error("Invalid FLAC frame: Invalid block size.");rN(r);let l=rW(r,o);this.format._options.appendOnly||(this.blockSizes.push(l),this.frameSizes.push(t.data.length));let c=this.writer.getPos();this.writer.write(t.data),this.format._options.onFrame&&this.format._options.onFrame(t.data,c),await this.writer.flush()}finally{r()}}addSubtitleCue(){throw Error("FLAC does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(null===this.sampleRate)throw Error("Cannot finalize an empty FLAC file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");if(this.metadataWritten||this.writeVorbisCommentAndPictureBlock(),!this.format._options.appendOnly){let e=1/0,t=0,i=1/0,r=0,s=0;for(let a=0;a<this.blockSizes.length;a++)i=Math.min(i,this.frameSizes[a]),r=Math.max(r,this.frameSizes[a]),t=Math.max(t,this.blockSizes[a]),s+=this.blockSizes[a],a!==this.blockSizes.length-1&&(e=Math.min(e,this.blockSizes[a]));0===this.blockSizes.length&&(e=16,t=65535,i=0,r=0),a(null!==this.channels),a(null!==this.bitsPerSample),this.writer.seek(4),this.writeHeader({minimumBlockSize:e,maximumBlockSize:t,minimumFrameSize:i,maximumFrameSize:r,sampleRate:this.sampleRate,channels:this.channels,bitsPerSample:this.bitsPerSample,totalSamples:s})}e()}}let oX=/(?:(.+?)\n)?((?:\d{2}:)?\d{2}:\d{2}.\d{3})\s+-->\s+((?:\d{2}:)?\d{2}:\d{2}.\d{3})/g,oG=/^WEBVTT(.|\n)*?\n{2}/,oY=/<(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})>/g;class oJ{constructor(e){this.preambleText=null,this.preambleEmitted=!1,this.options=e}parse(e){let t;if(e=e.replaceAll("\r\n","\n").replaceAll("\r","\n"),oX.lastIndex=0,!this.preambleText){if(!oG.test(e))throw Error("WebVTT preamble incorrect.");t=oX.exec(e);let i=e.slice(0,t?.index??e.length).trimEnd();if(!i)throw Error("No WebVTT preamble provided.");this.preambleText=i,t&&(e=e.slice(t.index),oX.lastIndex=0)}for(;t=oX.exec(e);){let i=e.slice(0,t.index),r=t[1],a=t.index+t[0].length,s=e.indexOf("\n",a)+1,n=e.slice(a,s).trim(),o=e.indexOf("\n\n",a);-1===o&&(o=e.length);let l=o0(t[2]),c=o0(t[3])-l,d=e.slice(s,o).trim();e=e.slice(o).trimStart(),oX.lastIndex=0;let u={timestamp:l/1e3,duration:c/1e3,text:d,identifier:r,settings:n,notes:i},h={};this.preambleEmitted||(h.config={description:this.preambleText},this.preambleEmitted=!0),this.options.output(u,h)}}}let oZ=/(?:(\d{2}):)?(\d{2}):(\d{2}).(\d{3})/,o0=e=>
1{let t=oZ.exec(e);if(!t)throw Error("Expected match.");return 36e5*Number(t[1]||"0")+6e4*Number(t[2])+1e3*Number(t[3])+Number(t[4])},o1=e=>{let t=Math.floor(e/36e5),i=Math.floor(e%36e5/6e4),r=Math.floor(e%6e4/1e3);return t.toString().padStart(2,"0")+":"+i.toString().padStart(2,"0")+":"+r.toString().padStart(2,"0")+"."+(e%1e3).toString().padStart(3,"0")};class o2{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 i=this.writer.getPos(),r=e.size??i-t;this.writer.seek(t),this.writeBoxHeader(e,r),this.writer.seek(i)}}writeBoxHeader(e,t){this.writeU32(e.largeSize?1:t),this.writeAscii(e.type),e.largeSize&&this.writeU64(t)}measureBoxHeader(e){return 8+8*!!e.largeSize}patchBox(e){let t=this.offsets.get(e);a(void 0!==t);let i=this.writer.getPos();this.writer.seek(t),this.writeBox(e),this.writer.seek(i)}measureBox(e){if(e.contents&&!e.children)return this.measureBoxHeader(e)+e.contents.byteLength;{let t=this.measureBoxHeader(e);if(e.contents&&(t+=e.contents.byteLength),e.children)for(let i of e.children)i&&(t+=this.measureBox(i));return t}}}let o3=new Uint8Array(8),o4=new DataView(o3.buffer),o8=e=>[(e%256+256)%256],o6=e=>(o4.setUint16(0,e,!1),[o3[0],o3[1]]),o5=e=>(o4.setInt16(0,e,!1),[o3[0],o3[1]]),o7=e=>(o4.setUint32(0,e,!1),[o3[1],o3[2],o3[3]]),o9=e=>(o4.setUint32(0,e,!1),[o3[0],o3[1],o3[2],o3[3]]),le=e=>(o4.setInt32(0,e,!1),[o3[0],o3[1],o3[2],o3[3]]),lt=e=>(o4.setUint32(0,Math.floor(e/0x100000000),!1),o4.setUint32(4,e,!1),[o3[0],o3[1],o3[2],o3[3],o3[4],o3[5],o3[6],o3[7]]),li=e=>(o4.setInt32(0,Math.floor(e/0x100000000),!1),o4.setUint32(4,e,!1),[o3[0],o3[1],o3[2],o3[3],o3[4],o3[5],o3[6],o3[7]]),lr=e=>(o4.setInt16(0,256*e,!1),[o3[0],o3[1]]),la=e=>(o4.setInt32(0,65536*e,!1),[o3[0],o3[1],o3[2],o3[3]]),ls=e=>(o4.setInt32(0,0x40000000*e,!1),[o3[0],o3[1],o3[2],o3[3]]),ln=(e,t)=>{let i=[],r=e;do{let e=127&r;r>>=7,i.length>0&&(e|=128),i.push(e),void 0!==t&&t--}while(r>0||t);return i.reverse()},lo=(e,t=!1)=>{let i=Array(e.length).fill(null).map((t,i)=>e.charCodeAt(i));return t&&i.push(0),i},ll=e=>{let t=Math.PI/180*e,i=Math.round(Math.cos(t)),r=Math.round(Math.sin(t));return[i,r,0,-r,i,0,0,0,1]},lc=ll(0),ld=e=>[la(e[0]),la(e[1]),ls(e[2]),la(e[3]),la(e[4]),ls(e[5]),la(e[6]),la(e[7]),ls(e[8])],lu=(e,t,i)=>({type:e,contents:t&&new Uint8Array(t.flat(10)),children:i}),lh=(e,t,i,r,a)=>lu(e,[o8(t),o7(i),r??[]],a),lm=()=>lu("styp",[lo("iso5"),o9(0),lo("iso5"),lo("iso6"),lo("mp41"),lo("cmfc"),lo("dash")]),lf=(e,t)=>{let i=e.maxWrittenEndTimestamp-e.minWrittenTimestamp;return Number.isFinite(i)||(i=0),lh("sidx",1,0,[o9(1),o9(cB),lt(cM(e.minWrittenTimestamp,cB)),lt(0),o6(0),o6(1),o9(0x7fffffff&t),o9(cM(i,cB)),o9(0)])},lp=e=>({type:"mdat",largeSize:e}),lg=e=>lu("moov",void 0,[lk(e.creationTime,e.trackDatas),...e.trackDatas.map(t=>lw(t,e.creationTime)),e.isFragmented?l3(e.trackDatas):null,cn(e)]),lk=(e,t)=>{let i=Math.max(0,...t.map(e=>cM(ly(e),cB)+cM(e.startTimestampOffset??0,cB))),r=Math.max(0,...t.map(e=>e.track.id))+1,a=!o(e)||!o(i),s=a?lt:o9;return lh("mvhd",+a,0,[s(e),s(e),o9(cB),s(i),la(1),lr(1),Array(10).fill(0),ld(lc),Array(24).fill(0),o9(r)])},ly=e=>{if(0===e.samples.length)return 0;let t=1/0,i=-1/0;for(let r=0;r<e.samples.length;r++){let a=e.samples[r];a.timestamp<t&&(t=a.timestamp),a.timestamp+a.duration>i&&(i=a.timestamp+a.duration)}return t===1/0?0:i-t},lw=(e,t)=>{let i=cF(e),r=null!==e.startTimestampOffset&&e.startTimestampOffset>0;return lu("trak",void 0,[lb(e,t),r?lT(e,e.startTimestampOffset):null,lS(e,t),void 0!==i.name?lu("udta",void 0,[lu("name",[...m.encode(i.name)])]):null])},lb=(e,t)=>{let i,r=cM(ly(e),cB)+cM(e.startTimestampOffset??0,cB),a=!o(t)||!o(r),s=a?lt:o9;i="video"===e.type?ll(e.track.metadata.rotation??0):lc;let n=2;e.track.metadata.disposition?.default!==!1&&(n|=1);let l="video"===e.type?0:"audio"===e.type?1:"subtitle"===e.type?2:z(e);return lh("tkhd",+a,n,[s(t),s(t),o9(e.track.id),o9(0),s(r),Array(8).fill(0),o6(0),o6(l),lr(+("audio"===e.type)),o6(0),ld(i),la("video"===e.type?e.info.width:0),la("video"===e.type?e.info.height:0)])},lT=(e,t)=>
1{let i=cM(t,cB),r=cM(ly(e),cB),a=!o(i)||!o(r),s=a?lt:o9,n=a?li:le;return lu("edts",void 0,[lh("elst",+!!a,0,[o9(2),s(i),n(-1),la(1),s(r),n(0),la(1)])])},lS=(e,t)=>lu("mdia",void 0,[lA(e,t),lC(!0,lv[e.type],lP[e.type]),lx(e)]),lA=(e,t)=>{let i=cM(ly(e),e.timescale),r=!o(t)||!o(i),a=r?lt:o9;return lh("mdhd",+r,0,[a(t),a(t),o9(e.timescale),a(i),o6(cb(e.track.metadata.languageCode??"und")),o6(0)])},lv={video:"vide",audio:"soun",subtitle:"text"},lP={video:"MediabunnyVideoHandler",audio:"MediabunnySoundHandler",subtitle:"MediabunnyTextHandler"},lC=(e,t,i,r="\0\0\0\0")=>lh("hdlr",0,0,[e?lo("mhlr"):o9(0),lo(t),lo(r),o9(0),o9(0),lo(i,!0)]),lx=e=>lu("minf",void 0,[lE[e.type](),l_(),lF(e)]),lE={video:()=>lh("vmhd",0,1,[o6(0),o6(0),o6(0),o6(0)]),audio:()=>lh("smhd",0,0,[o6(0),o6(0)]),subtitle:()=>lh("nmhd",0,0)},l_=()=>lu("dinf",void 0,[lI()]),lI=()=>lh("dref",0,0,[o9(1)],[lB()]),lB=()=>lh("url ",0,1),lF=e=>{let t=e.compositionTimeOffsetTable.length>1||e.compositionTimeOffsetTable.some(e=>0!==e.sampleCompositionTimeOffset);return lu("stbl",void 0,[lM(e),lG(e),t?l1(e):null,t?l2(e):null,lJ(e),lZ(e),l0(e),lY(e)])},lM=e=>{let t;if("video"===e.type)t=lR(cf(e.track.source._codec,e.info.decoderConfig.codec),e);else if("audio"===e.type){let i=cg(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime);a(i),t=lU(i,e)}else"subtitle"===e.type&&(t=lX(cy[e.track.source._codec],e));return a(t),lh("stsd",0,0,[o9(1)],[t])},lR=(e,t)=>lu(e,[Array(6).fill(0),o6(1),o6(0),o6(0),Array(12).fill(0),o6(t.info.width),o6(t.info.height),o9(4718592),o9(4718592),o9(0),o6(1),o8(10),lo("Mediabunny"),Array(21).fill(0),o6(t.info.hasAlphaChannel?32:24),o5(65535)],[cp[t.track.source._codec]?.(t)??null,lD(t),S(t.info.decoderConfig.colorSpace)?lz(t):null]),lD=e=>e.info.pixelAspectRatio.num===e.info.pixelAspectRatio.den?null:lu("pasp",[o9(e.info.pixelAspectRatio.num),o9(e.info.pixelAspectRatio.den)]),lz=e=>lu("colr",[lo(e.muxer.isQuickTime?"nclc":"nclx"),o6(g[e.info.decoderConfig.colorSpace.primaries]),o6(y[e.info.decoderConfig.colorSpace.transfer]),o6(b[e.info.decoderConfig.colorSpace.matrix]),e.muxer.isQuickTime?[]:o8(!!e.info.decoderConfig.colorSpace.fullRange<<7)]),lO=e=>{if(!e.info.decoderConfig)return null;let t=e.info.decoderConfig,i=t.codec.split("."),r=Number(i[1]),a=Number(i[2]),s=Number(i[3]),n=i[4]?Number(i[4]):1,o=i[8]?Number(i[8]):Number(t.colorSpace?.fullRange??0),l=i[5]?Number(i[5]):t.colorSpace?.primaries?g[t.colorSpace.primaries]:2,c=i[6]?Number(i[6]):t.colorSpace?.transfer?y[t.colorSpace.transfer]:2,d=i[7]?Number(i[7]):t.colorSpace?.matrix?b[t.colorSpace.matrix]:2;return lh("vpcC",1,0,[o8(r),o8(a),o8((s<<4)+(n<<1)+o),o8(l),o8(c),o8(d),o6(0)])},lU=(e,t)=>{let i=0,r=16,a=eK.includes(t.track.source._codec);if(a){let{sampleSize:e}=tr(t.track.source._codec);(r=8*e)>16&&(i=1)}return t.muxer.isQuickTime&&(i=1),lu(e,0===i?[Array(6).fill(0),o6(1),o6(i),o6(0),o9(0),o6(t.info.numberOfChannels),o6(r),o6(0),o6(0),o6(t.info.sampleRate<65536?t.info.sampleRate:0),o6(0)]:[Array(6).fill(0),o6(1),o6(i),o6(0),o9(0),o6(t.info.numberOfChannels),o6(Math.min(r,16)),o5(a?0:-2),o6(0),o6(t.info.sampleRate<65536?t.info.sampleRate:0),o6(0),a?[o9(1),o9(r/8),o9(t.info.numberOfChannels*r/8)]:[o9(0),o9(0),o9(0)],o9(2)],[ck(t.track.source._codec,t.muxer.isQuickTime)?.(t)??null])},lN=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 i=[...o8(t),...o8(21),...o7(0),...o9(0),...o9(0)];if(e.info.decoderConfig.description){let t=d(e.info.decoderConfig.description);i=[...i,...o8(5),...ln(t.byteLength),...t]}return i=[...o6(1),...o8(0),...o8(4),...ln(i.length),...i,...o8(6),...o8(1),...o8(2)],lh("esds",0,0,i=[...o8(3),...ln(i.length),...i])},lW=e=>lu("wave",void 0,[lV(e),lL(e),lu("\0\0\0\0")]),lV=e=>lu("frma",[lo(cg(e.track.source._codec,e.info.decoderConfig.codec,e.muxer.isQuickTime))]),lL=e=>{let{littleEndian:t}=tr(e.track.source._codec);return lu("enda",[o6(+t)])},lq=e=>{let t=e.info.numberOfChannels,i=3840,r=e.info.sampleRate,s=0,n=0,o=new Uint8Array(0),l=e.info.decoderConfig?.description;if(l){a(l.byteLength>=18);let e=tG(d(l));t=e.outputChannelCount,i=e.preSkip,r=e.inputSampleRate,s=e.outputGain,n=e.channelMappingFamily,e.channelMappingTable&&(o=e.channelMappingTable)}return lu("dOps",[o8(0),o8(t),o6(i),o9(r),o5(s),o8(n),...o])},lH=e=>{let t=e.info.decoderConfig?.description;return a(t),lh("dfLa",0,0,[...d(t).subarray(4)])},lj=e=>{let{littleEndian:t,sampleSize:i}=tr(e.track.source._codec);return lh("pcmC",0,0,[o8(+t),o8(8*i)])},lQ=e=>{a(e.info.primingPacket);let t=t3(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 i=new Uint8Array(3),r=new eW(i);return r.writeBits(2,t.fscod),r.writeBits(5,t.bsid),r.writeBits(3,t.bsmod),r.writeBits(3,t.acmod),r.writeBits(1,t.lfeon),r.writeBits(5,t.bitRateCo
1de),r.writeBits(5,0),lu("dac3",[...i])},l$=e=>{a(e.info.primingPacket);let t=t7(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 i=16;for(let e of t.substreams)i+=23,e.numDepSub>0?i+=9:i+=1;let r=new Uint8Array(Math.ceil(i/8)),s=new eW(r);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 lu("dec3",[...r])},lK=e=>{a(e.info.primingPacket);let t=id(e.info.primingPacket.data);if(!t)throw Error("Couldn't extract DTS frame info from the audio packet. Ensure the packets contain valid DTS frames as specified in ETSI TS 102 114.");return lu("ddts",[...(e=>{let t=new Uint8Array(20),i=u(t);i.setUint32(0,e.sampleRate),i.setUint32(4,e.bitRate),i.setUint32(8,e.bitRate),t[12]=e.pcmResolution;let r=e.core&&!e.hasExtensions?1:0,a=new eW(t);return a.seekToByte(13),a.writeBits(2,Math.max(ic.indexOf(e.sampleCount),0)),a.writeBits(5,r),a.writeBits(1,+!!e.core?.lfePresent),a.writeBits(6,e.core?.amode??0),a.writeBits(14,e.core?e.core.frameSize-1:0),a.writeBits(1,0),a.writeBits(3,0),a.writeBits(16,e.channelLayout),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(1,0),a.writeBits(5,0),t})(t)])},lX=(e,t)=>lu(e,[Array(6).fill(0),o6(1)],[cw[t.track.source._codec](t)]),lG=e=>lh("stts",0,0,[o9(e.timeToSampleTable.length),e.timeToSampleTable.map(e=>[o9(e.sampleCount),o9(e.sampleDelta)])]),lY=e=>{if(e.samples.every(e=>"key"===e.type))return null;let t=[...e.samples.entries()].filter(([,e])=>"key"===e.type);return lh("stss",0,0,[o9(t.length),t.map(([e])=>o9(e+1))])},lJ=e=>lh("stsc",0,0,[o9(e.compactlyCodedChunkTable.length),e.compactlyCodedChunkTable.map(e=>[o9(e.firstChunk),o9(e.samplesPerChunk),o9(1)])]),lZ=e=>{if("audio"===e.type&&e.info.requiresPcmTransformation){let{sampleSize:t}=tr(e.track.source._codec);return lh("stsz",0,0,[o9(t*e.info.numberOfChannels),o9(e.samples.reduce((t,i)=>t+cM(i.duration,e.timescale),0))])}return lh("stsz",0,0,[o9(0),o9(e.samples.length),e.samples.map(e=>o9(e.size))])},l0=e=>e.finalizedChunks.length>0&&n(e.finalizedChunks).offset>=0x100000000?lh("co64",0,0,[o9(e.finalizedChunks.length),e.finalizedChunks.map(e=>lt(e.offset))]):lh("stco",0,0,[o9(e.finalizedChunks.length),e.finalizedChunks.map(e=>o9(e.offset))]),l1=e=>lh("ctts",1,0,[o9(e.compositionTimeOffsetTable.length),e.compositionTimeOffsetTable.map(e=>[o9(e.sampleCount),le(e.sampleCompositionTimeOffset)])]),l2=e=>{let t=1/0,i=-1/0,r=1/0,s=-1/0;a(e.compositionTimeOffsetTable.length>0),a(e.samples.length>0);for(let r=0;r<e.compositionTimeOffsetTable.length;r++){let a=e.compositionTimeOffsetTable[r];t=Math.min(t,a.sampleCompositionTimeOffset),i=Math.max(i,a.sampleCompositionTimeOffset)}for(let t=0;t<e.samples.length;t++){let i=e.samples[t];r=Math.min(r,cM(i.timestamp,e.timescale)),s=Math.max(s,cM(i.timestamp+i.duration,e.timescale))}let n=Math.max(-t,0);return s>=0x80000000?null:lh("cslg",0,0,[le(n),le(t),le(i),le(r),le(s)])},l3=e=>lu("mvex",void 0,e.map(l4)),l4=e=>lh("trex",0,0,[o9(e.track.id),o9(1),o9(0),o9(0),o9(0)]),l8=(e,t)=>lu("moof",void 0,[l6(e),...t.map(l7)]),l6=e=>lh("mfhd",0,0,[o9(e)]),l5=e=>{let t=0,i=0,r="delta"===e.type;return i|=r,r?t|=1:t|=2,t<<24|i<<16},l7=e=>lu("traf",void 0,[l9(e),ce(e),ct(e)]),l9=e=>{a(e.currentChunk);let t=e.currentChunk.samples[1]??e.currentChunk.samples[0],i={duration:t.timescaleUnitsToNextSample,size:t.size,flags:l5(t)};return lh("tfhd",0,131128,[o9(e.track.id),o9(i.duration),o9(i.size),o9(i.flags)])},ce=e=>(a(e.currentChunk),lh("tfdt",1,0,[lt(cM(e.currentChunk.startTimestamp,e.timescale))])),ct=e=>{a(e.currentChunk);let t=e.currentChunk.samples.map(e=>e.timescaleUnitsToNextSample),i=e.currentChunk.samples.map(e=>e.size),r=e.currentChunk.samples.map(l5),s=e.currentChunk.samples.map(t=>cM(t.timestamp-t.decodeTimestamp,e.timescale)),n=new Set(t),o=new Set(i),l=new Set(r),c=new Set(s),d=2===l.size&&r[0]!==r[1],u=n.size>1,h=o.size>1,m=!d&&l.size>1,f=c.size>1||[...c].some(e=>0!==e);return lh("trun",1,1|4*d|256*u|512*h|1024*m|2048*f,[o9(e.currentChunk.samples.length),o9(e.currentChunk.offset-e.currentChunk.moofOff
1set||0),d?o9(r[0]):[],e.currentChunk.samples.map((e,a)=>[u?o9(t[a]):[],h?o9(i[a]):[],m?o9(r[a]):[],f?le(s[a]):[]])])},ci=e=>lh("tfra",1,0,[o9(e.track.id),o9(63),o9(e.finalizedChunks.length),e.finalizedChunks.map(t=>[lt(cM(t.samples[0].timestamp,e.timescale)),lt(t.moofOffset),o9(t.trafIndex+1),o9(1),o9(1)])]),cr=()=>lu("vtte"),ca=(e,t,i,r,a)=>lu("vttc",void 0,[null!==a?lu("vsid",[le(a)]):null,null!==i?lu("iden",[...m.encode(i)]):null,null!==t?lu("ctim",[...m.encode(o1(t))]):null,null!==r?lu("sttg",[...m.encode(r)]):null,lu("payl",[...m.encode(e)])]),cs=e=>lu("vtta",[...m.encode(e)]),cn=e=>{let t=[],i=e.format._options.metadataFormat??"auto",r=e.output._metadataTags;if("mdir"!==i&&("auto"!==i||e.isQuickTime))if("mdta"===i){let e=ch(r);e&&t.push(e)}else("udta"===i||"auto"===i&&e.isQuickTime)&&co(t,e.output._metadataTags);else{let e=cu(r);e&&t.push(e)}return 0===t.length?null:lu("udta",void 0,t)},co=(e,t)=>{for(let{key:i,value:r}of ed(t))switch(i){case"title":e.push(cl("\xa9nam",r));break;case"description":e.push(cl("\xa9des",r));break;case"artist":e.push(cl("\xa9ART",r));break;case"album":e.push(cl("\xa9alb",r));break;case"albumArtist":e.push(cl("albr",r));break;case"genre":e.push(cl("\xa9gen",r));break;case"date":e.push(cl("\xa9day",r.toISOString().slice(0,10)));break;case"comment":e.push(cl("\xa9cmt",r));break;case"lyrics":e.push(cl("\xa9lyr",r));break;case"raw":case"discNumber":case"discsTotal":case"trackNumber":case"tracksTotal":case"images":break;default:z(i)}if(t.raw)for(let i in t.raw){let r=t.raw[i];!(null==r||4!==i.length||e.some(e=>e.type===i))&&("string"==typeof r?e.push(cl(i,r)):r instanceof Uint8Array&&e.push(lu(i,Array.from(r))))}},cl=(e,t)=>{let i=m.encode(t);return lu(e,[o6(i.length),o6(cb("und")),Array.from(i)])},cc={"image/jpeg":13,"image/png":14,"image/bmp":27},cd=(e,t)=>{let i=[];for(let{key:r,value:a}of ed(e))switch(r){case"title":i.push({key:t?"title":"\xa9nam",value:cm(a)});break;case"description":i.push({key:t?"description":"\xa9des",value:cm(a)});break;case"artist":i.push({key:t?"artist":"\xa9ART",value:cm(a)});break;case"album":i.push({key:t?"album":"\xa9alb",value:cm(a)});break;case"albumArtist":i.push({key:t?"album_artist":"aART",value:cm(a)});break;case"comment":i.push({key:t?"comment":"\xa9cmt",value:cm(a)});break;case"genre":i.push({key:t?"genre":"\xa9gen",value:cm(a)});break;case"lyrics":i.push({key:t?"lyrics":"\xa9lyr",value:cm(a)});break;case"date":i.push({key:t?"date":"\xa9day",value:cm(a.toISOString().slice(0,10))});break;case"images":for(let e of a)"coverFront"===e.kind&&i.push({key:"covr",value:lu("data",[o9(cc[e.mimeType]??0),o9(0),Array.from(e.data)])});break;case"trackNumber":if(t){let t=void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString();i.push({key:"track",value:cm(t)})}else i.push({key:"trkn",value:lu("data",[o9(0),o9(0),o6(0),o6(a),o6(e.tracksTotal??0),o6(0)])});break;case"discNumber":t||i.push({key:"disc",value:lu("data",[o9(0),o9(0),o6(0),o6(a),o6(e.discsTotal??0),o6(0)])});break;case"tracksTotal":case"discsTotal":case"raw":break;default:z(r)}if(e.raw)for(let r in e.raw){let a=e.raw[r];!(null==a||!t&&4!==r.length||i.some(e=>e.key===r))&&("string"==typeof a?i.push({key:r,value:cm(a)}):a instanceof Uint8Array?i.push({key:r,value:lu("data",[o9(0),o9(0),Array.from(a)])}):a instanceof eD&&i.push({key:r,value:lu("data",[o9(cc[a.mimeType]??0),o9(0),Array.from(a.data)])}))}return i},cu=e=>{let t=cd(e,!1);return 0===t.length?null:lh("meta",0,0,void 0,[lC(!1,"mdir","","appl"),lu("ilst",void 0,t.map(e=>lu(e.key,void 0,[e.value])))])},ch=e=>{let t=cd(e,!0);return 0===t.length?null:lu("meta",void 0,[lC(!1,"mdta",""),lh("keys",0,0,[o9(t.length)],t.map(e=>lu("mdta",[...m.encode(e.key)]))),lu("ilst",void 0,t.map((e,t)=>lu(String.fromCharCode(...o9(t+1)),void 0,[e.value])))])},cm=e=>lu("data",[o9(1),o9(0),...m.encode(e)]),cf=(e,t)=>{switch(e){case"avc":return t.startsWith("avc3")?"avc3":"avc1";case"hevc":return"hvc1";case"vp8":return"vp08";case"vp9":return"vp09";case"av1":return"av01";
1case"prores":return t}},cp={avc:e=>e.info.decoderConfig&&lu("avcC",[...d(e.info.decoderConfig.description)]),hevc:e=>e.info.decoderConfig&&lu("hvcC",[...d(e.info.decoderConfig.description)]),vp8:lO,vp9:lO,av1:e=>lu("av1C",e7(e.info.decoderConfig.codec)),prores:null},cg=(e,t,i)=>{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";case"dts":return t}if(i)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"}},ck=(e,t)=>{switch(e){case"aac":case"mp3":case"vorbis":return lN;case"opus":return lq;case"flac":return lH;case"ac3":return lQ;case"eac3":return l$;case"dts":return lK}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 lW}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 lj}return null},cy={webvtt:"wvtt"},cw={webvtt:e=>lu("vttC",[...m.encode(e.info.config.description)])},cb=e=>{a(3===e.length);let t=0;for(let i=0;i<3;i++)t<<=5,t+=e.charCodeAt(i)-96;return t};class cT{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(){a(!this.started),this.target._start(),this.started=!0}write(e){a(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 a(this.started&&!this.finalized),this.target._flush()}async finalize(){a(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 i=t+e.byteLength-this.trackedStart,r=this.trackedWrites.byteLength;for(;r<i;)r*=2;if(r!==this.trackedWrites.byteLength){let e=new Uint8Array(r);e.set(this.trackedWrites,0),this.trackedWrites=e}this.trackedWrites.set(e,t-this.trackedStart),this.trackedEnd=Math.max(this.trackedEnd,t+e.byteLength)}startTrackingWrites(){this.trackedWrites=new Uint8Array(1024),this.trackedStart=this.getPos(),this.trackedEnd=this.trackedStart}stopTrackingWrites(){if(!this.trackedWrites)throw 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}}let cS=void 0!==aE?aE:void 0;class cA extends eI{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 c_(this,e)}}class cv extends cA{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),i=new Uint8Array(e);
1i.set(this._bytes,0),this._buffer=e,this._bytes=i}}}_start(){}_write(e,t){this._ensureSize(t+e.byteLength),this._bytes.set(e,t),this._maxPos=Math.max(this._maxPos,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this.buffer=this._buffer.slice(0,this._maxPos),this._options.onFinalize&&await this._options.onFinalize(this.buffer),this._emit("finalized")}async _close(){}_getSlice(e,t){return this._bytes.slice(e,t)}}class cP extends cA{constructor(e,t={}){if(super(),this._sections=[],this._lastWriteEnd=0,this._lastFlushEnd=0,this._streamWriter=null,this._writeError=null,this._chunks=[],!(e instanceof WritableStream))throw TypeError("StreamTarget requires a WritableStream instance.");if(null!=t&&"object"!=typeof t)throw TypeError("StreamTarget options, when provided, must be an object.");if(void 0!==t.chunked&&"boolean"!=typeof t.chunked)throw TypeError("options.chunked, when provided, must be a boolean.");if(void 0!==t.chunkSize&&(!Number.isInteger(t.chunkSize)||t.chunkSize<1024))throw TypeError("options.chunkSize, when provided, must be an integer and not smaller than 1024.");this._writable=e,this._options=t,this._chunked=t.chunked??!1,this._chunkSize=t.chunkSize??0x1000000}_start(){this._streamWriter=this._writable.getWriter()}_write(e,t){if(t>this._lastWriteEnd){let e=t-this._lastWriteEnd;this._write(new Uint8Array(e),this._lastWriteEnd)}this._sections.push({data:e.slice(),start:t}),this._lastWriteEnd=Math.max(this._lastWriteEnd,t+e.byteLength),this._dispatchWrite(t,t+e.byteLength)}async _flush(){if(null!==this._writeError)throw this._writeError;if(a(this._streamWriter),0===this._sections.length)return;let e=[],t=[...this._sections].sort((e,t)=>e.start-t.start);e.push({start:t[0].start,size:t[0].data.byteLength});for(let i=1;i<t.length;i++){let r=e[e.length-1],a=t[i];a.start<=r.start+r.size?r.size=Math.max(r.size,a.start+a.data.byteLength-r.start):e.push({start:a.start,size:a.data.byteLength})}for(let t of e){for(let e of(t.data=new Uint8Array(t.size),this._sections))t.start<=e.start&&e.start<t.start+t.size&&t.data.set(e.data,e.start-t.start);if(null!==this._streamWriter.desiredSize&&this._streamWriter.desiredSize<=0&&await this._streamWriter.ready,this._chunked)this._writeDataIntoChunks(t.data,t.start),this._tryToFlushChunks();else{if(!0===this._monotonicity&&t.start!==this._lastFlushEnd)throw Error("Internal error: Monotonicity violation.");this._streamWriter.write({type:"write",data:t.data,position:t.start}).catch(e=>{this._writeError??=e}),this._lastFlushEnd=t.start+t.data.byteLength}}this._sections.length=0}_writeDataIntoChunks(e,t){let i=this._chunks.findIndex(e=>e.start<=t&&t<e.start+this._chunkSize);-1===i&&(i=this._createChunk(t));let r=this._chunks[i],a=t-r.start,s=e.subarray(0,Math.min(this._chunkSize-a,e.byteLength));r.data.set(s,a);let n={start:a,end:a+s.byteLength};if(this._insertSectionIntoChunk(r,n),0===r.written[0].start&&r.written[0].end===this._chunkSize&&(r.shouldFlush=!0),this._chunks.length>2){for(let e=0;e<this._chunks.length-1;e++)this._chunks[e].shouldFlush=!0;this._tryToFlushChunks()}s.byteLength<e.byteLength&&this._writeDataIntoChunks(e.subarray(s.byteLength),t+s.byteLength)}_insertSectionIntoChunk(e,t){let i=0,r=e.written.length-1,a=-1;for(;i<=r;){let s=Math.floor(i+(r-i+1)/2);e.written[s].start<=t.start?(i=s+1,a=s):r=s-1}for(e.written.splice(a+1,0,t),(-1===a||e.written[a].end<t.start)&&a++;a<e.written.length-1&&e.written[a].end>=e.written[a+1].start;)e.written[a].end=Math.max(e.written[a].end,e.written[a+1].end),e.written.splice(a+1,1)}_createChunk(e){let t={start:Math.floor(e/this._chunkSize)*this._chunkSize,data:new Uint8Array(this._chunkSize),written:[],shouldFlush:!1};return this._chunks.push(t),this._chunks.sort((e,t)=>e.start-t.start),this._chunks.indexOf(t)}_tryToFlushChunks(e=!1){a(this._streamWriter);for(let t=0;t<this._chunks.length;t++){let i=this._chunks[t];if(i.shouldFlush||e){for(let e of i.written){let t,r=i.start+e.start;if(!0===this._monotonicity&&r!==this._lastFlushEnd)throw Error("Internal error: Monotonicity violation.");t=(0!==e.start||e.end!==i.data.byteLength)&&et()?i.data.slice(e.start,e.end):i.data.subarray(e.start,e.end),this._streamWriter.write({type:"write",data:t,position:r}).catch(e=>{this._writeError??=e}),this._lastFlushEnd=i.start+e.end}this._chunks.splice(t--,1)}}}async _finalize(){if(this._chunked&&this._tryToFlushChunks(!0),null!==this._writeError)throw this._writeError;a(this._streamWriter),await this._streamWriter.ready,await this._streamWriter.close(),this._emit("finalized")}async _close(){return this._streamWriter?.close()}}class cC extends cA{constructor(e){super(),this._writer=null,this._nextWritePos=0,this._writable=e,this._streamTarget=new cP(new WritableStream({start:()=>{this._writer=this._writable.getWriter()},write:e=>
1{if(!0!==this._monotonicity)throw Error("AppendOnlyStreamTarget requires that data be written monotonically (always appended to the end). You must use a format that guarantees this behavior.");return a(e.position===this._nextWritePos),this._nextWritePos+=e.data.byteLength,a(this._writer),this._writer.write(e.data)},close:()=>this._writer?.close()}))}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t)}_flush(){return this._streamTarget._flush()}_finalize(){return this._streamTarget._finalize()}_close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class cx extends cA{constructor(e,t={}){if("string"!=typeof e)throw TypeError("filePath must be a string.");if(!t||"object"!=typeof t)throw TypeError("options must be an object.");if(!cS.fs)throw Error("FilePathTarget is only available in server-side environments (Node.js, Bun, Deno).");super(),this._fileHandle=null;let i=new WritableStream({start:async()=>{this._fileHandle=await cS.fs.open(e,"w")},write:async e=>
1{a(this._fileHandle),await this._fileHandle.write(e.data,0,e.data.byteLength,e.position)},close:async()=>{this._fileHandle&&(await this._fileHandle.close(),this._fileHandle=null)}});this._streamTarget=new cP(i,{chunked:!0,...t})}_start(){this._streamTarget._start()}_write(e,t){this._streamTarget._write(e,t),this._dispatchWrite(t,t+e.byteLength)}async _flush(){return this._streamTarget._flush()}async _finalize(){await this._streamTarget._finalize(),this._emit("finalized")}async _close(){return this._streamTarget._close()}_setMonotonicity(e){super._setMonotonicity(e),this._streamTarget._setMonotonicity(e)}}class cE extends cA{_start(){}_write(e,t){this._dispatchWrite(t,t+e.byteLength)}async _flush(){}async _finalize(){this._emit("finalized")}async _close(){}}class c_ extends cA{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 cI{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 cB=57600,cF=e=>{let t={},i=e.track;return void 0!==i.metadata.name&&(t.name=i.metadata.name),t},cM=(e,t,i=!0)=>{let r=e*t;return i?Math.round(r):r};class cR extends oj{constructor(e,t){super(e),this.writer=null,this.boxWriter=null,this.initWriter=null,this.initBoxWriter=null,this.auxTarget=new cv,this.auxWriter=new cT(this.auxTarget,!1),this.auxBoxWriter=new o2(this.auxWriter),this.mdat=null,this.ftypSize=null,this.trackDatas=[],this.allTracksKnown=B(),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 dv,this.isCmaf=t instanceof dA,this.minimumFragmentDuration=this.formatOptions.minimumFragmentDuration??(t instanceof dA?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 cv),this.boxWriter=new o2(this.writer),this.fastStart=this.formatOptions.fastStart??(this.writer.target instanceof cv&&"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 cT(await this.output._getInitTarget(),!0);e.start(),this.initWriter=e,this.initBoxWriter=new o2(e)}let t=this.output.tracks.some(e=>e.isVideoTrack()&&"avc"===e.source._codec);{let e=this.initBoxWriter??this.boxWriter;if(a(e),this.formatOptions.onFtyp&&e.writer.startTrackingWrites(),e.writeBox((e=>{if(e.isQuickTime)return lu("ftyp",[lo("qt  "),o9(512),lo("qt  ")]);if(e.fragmented)if(e.cmaf)return lu("ftyp",[lo("iso5"),o9(512),lo("iso5"),lo("iso6"),lo("mp41"),lo("cmfc"),lo("dash")]);else return lu("ftyp",[lo("iso5"),o9(512),lo("iso5"),lo("iso6"),lo("mp41")]);return lu("ftyp",[lo("isom"),o9(512),lo("isom"),e.holdsAvc?lo("avc1"):[],lo("mp41")])})({isQuickTime:this.isQuickTime,holdsAvc:t,fragmented:this.isFragmented,cmaf:this.isCmaf})),this.formatOptions.onFtyp){let{data:t,start:i}=e.writer.stopTrackingWrites();this.formatOptions.onFtyp(t,i)}this.ftypSize=e.writer.getPos(),this.isCmaf&&await this.initWriter.flush()}if("in-memory"===this.fastStart);else if("reserve"===this.fastStart){for(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||(a(this.writer),a(this.boxWriter),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=lp(!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 iy({isQuickTime:this.isQuickTime,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,i){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;td(i,e.source._codec),a(i),a(i.decoderConfig);let s={...i.decoderConfig};a(void 0!==s.codedWidth),a(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=tN(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=(e=>{let t=[];for(let i 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&i.arrayCompleteness)<<7|63&i.nalUnitType),t.push(i.nalUnits.length>>8&255),t.push(255&i.nalUnits.length),i.nalUnits)){t.push(e.length>>8&255),t.push(255&e.length);for(let i=0;i<e.length;i++)t.push(e[i])}return new Uint8Array(t)})(e),n=!0}}else{if(!t)throw Error("No AVC description provided; you must therefore provide a priming packet.");let e=tB(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=(e=>{let t=[];for(let i 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=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}for(let i of(t.push(e.pictureParameterSets.length),e.pictureParameterSets)){let e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}if(100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication)for(let i of(a(null!==e.chromaFormat),a(null!==e.bitDepthLumaMinus8),a(null!==e.bitDepthChromaMinus8),a(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=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}return new Uint8Array(t)})(e),n=!0}let o=((e,t)=>{let i=e<0?-1:1,r=0,a=1,s=1,n=0,o=e=Math.abs(e);for(;;){let e=Math.floor(o),i=e*s+r,l=e*n+a;if(l>t||(r=s,a=n,s=i,n=l,!isFinite(o=1/(o-e))))break}return{num:i*s,den:n}})(1/(e.metadata.frameRate??cB),1e6).den,l=s.displayAspectWidth,c=s.displayAspectHeight,d=void 0===l||void 0===c?{num:1,den:1}:eT({num:l*s.codedHeight,den:c*s.codedWidth}),u="ap4h"===s.codec||"ap4x"===s.codec,h={muxer:this,track:e,type:"video",info:{width:s.codedWidth,height:s.codedHeight,pixelAspectRatio:d,decoderConfig:s,requiresAnnexBTransformation:n,hasAlphaChannel:u},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,i){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;th(i,e.source._codec),a(i),a(i.decoderConfig);let s={...i.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=rD(og.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 i=eV[e.samplingFrequencyIndex],r=eL[e.channelConfiguration];if(void 0===i||void 0===r)throw Error("Invalid ADTS frame header.");s.description=eH({objectType:e.objectType,sampleRate:i,numberOfChannels:r}),n=!0}if(!t){if("ac3"===e.source._codec||"eac3"===e.source._codec)throw Error("AC-3/E-AC-3 require a priming packet.");if("dts"===e.source._codec)throw Error("DTS requires a priming packet.")}let o={muxer:this,track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresPcmTransformation:!this.isFragmented&&eK.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 i=this.trackDatas.find(t=>t.track===e);if(i)return i;tm(t),a(t),a(t.config);let r={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(r),this.trackDatas.sort((e,t)=>
1e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,i){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,i),a=t.data;if(r.info.requiresAnnexBTransformation){let e=[...tA(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=tI(e,4)}this.validateTimestamp(r.track,t.timestamp,"key"===t.type);let s=this.createSampleForTrack(r,a,t.timestamp,t.duration,t.type);await this.registerSample(r,s)}finally{r()}}async addEncodedAudioPacket(e,t,i){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,i),a=t.data;if(r.info.requiresAdtsStripping){let e=rD(og.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(r.track,t.timestamp,"key"===t.type);let s=t.timestamp,n=t.duration;if(r.info.requiresPcmTransformation){let e=tr(r.info.decoderConfig.codec).sampleSize*r.info.numberOfChannels;if(n=a.byteLength/e/r.info.sampleRate,null!==r.info.expectedNextPcmPacketTimestamp){let e=s-r.info.expectedNextPcmPacketTimestamp;if(e<.01)s=r.info.expectedNextPcmPacketTimestamp;else{let t=await this.padWithSilence(r,r.info.expectedNextPcmPacketTimestamp,e);s=r.info.expectedNextPcmPacketTimestamp+t}}r.info.expectedNextPcmPacketTimestamp=s+n}let o=this.createSampleForTrack(r,a,s,n,t.type);await this.registerSample(r,o)}finally{r()}}async padWithSilence(e,t,i){let r=cM(i,e.timescale);if(i=r/e.timescale,r>0){let{sampleSize:a,silentValue:s}=tr(e.info.decoderConfig.codec),n=new Uint8Array(a*(r*e.info.numberOfChannels)).fill(s),o=this.createSampleForTrack(e,new Uint8Array(n.buffer),t,i,"key");await this.registerSample(e,o)}return i}async addSubtitleCue(e,t,i){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,!0),"webvtt"===e.source._codec&&(r.cueQueue.push(t),await this.processWebVTTCues(r,t.timestamp))}finally{r()}}async processWebVTTCues(e,t){for(;e.cueQueue.length>0;){let i=new Set([]);for(let r of e.cueQueue)a(r.timestamp<=t),a(e.lastCueEndTimestamp<=r.timestamp+r.duration),i.add(Math.max(r.timestamp,e.lastCueEndTimestamp)),i.add(r.timestamp+r.duration);let r=[...i].sort((e,t)=>e-t),s=r[0],n=r[1]??s;if(t<n)break;if(e.lastCueEndTimestamp<s){this.auxWriter.seek(0);let t=cr();this.auxBoxWriter.writeBox(t);let i=this.auxTarget._getSlice(0,this.auxWriter.getPos()),r=this.createSampleForTrack(e,i,e.lastCueEndTimestamp,s-e.lastCueEndTimestamp,"key");await this.registerSample(e,r),e.lastCueEndTimestamp=s}this.auxWriter.seek(0);for(let t=0;t<e.cueQueue.length;t++){let i=e.cueQueue[t];if(i.timestamp>=n)break;oY.lastIndex=0;let r=oY.test(i.text),a=i.timestamp+i.duration,o=e.cueToSourceId.get(i);if(void 0===o&&n<a&&(o=e.nextSourceId++,e.cueToSourceId.set(i,o)),i.notes){let e=cs(i.notes);this.auxBoxWriter.writeBox(e)}let l=ca(i.text,r?s:null,i.identifier??null,i.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,i,r,a){return{timestamp:i,decodeTimestamp:i,duration:r,data:t,size:t.byteLength,type:a,timescaleUnitsToNextSample:cM(r,e.timescale)}}processTimestamps(e,t){if(0===e.timestampProcessingQueue.length)return;if("audio"===e.type&&e.info.requiresPcmTransformation){this.isFragmented||(e.startTimestampOffset??=e.timestampProcessingQueue[0].timestamp);let t=0;for(let i=0;i<e.timestampProcessingQueue.length;i++)t+=cM(e.timestampProcessingQueue[i].duration,e.timescale);if(0===e.timeToSampleTable.length)e.timeToSampleTable.push({sampleCount:t,sampleDelta:1});else{let i=n(e.timeToSampleTable);i.sampleCount+=t}e.timestampProcessingQueue.length=0;return}let i=e.timestampProcessingQueue.map(e=>e.timestamp).sort((e,t)=>e-t);this.isFragmented||(e.startTimestampOffset??=i[0]);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=i[t];let s=cM(r.timestamp-r.decodeTimestamp,e.timescale),o=cM(r.duration,e.timescale);if(null!==e.lastTimescaleUnits){a(e.lastSample);let t=Math.round(cM(r.decodeTimestamp,e.timescale,!1)-e.lastTimescaleUnits);if(a(t>=0),e.lastTimescaleUnits+=t,e.lastSample.timescaleUnitsToNextSample=t,!this.isFragmented){let i=n(e.timeToSampleTable);if(a(i),1===i.sampleCount){i.sampleDelta=t;let r=e.timeToSampleTable[e.timeToSampleTable.length-2];
1r&&r.sampleDelta===t&&(r.sampleCount++,e.timeToSampleTable.pop(),i=r)}else i.sampleDelta!==t&&(i.sampleCount--,e.timeToSampleTable.push(i={sampleCount:1,sampleDelta:t}));i.sampleDelta===o?i.sampleCount++:e.timeToSampleTable.push({sampleCount:1,sampleDelta:o});let r=n(e.compositionTimeOffsetTable);a(r),r.sampleCompositionTimeOffset===s?r.sampleCount++:e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:s})}}else e.lastTimescaleUnits=cM(r.decodeTimestamp,e.timescale,!1),this.isFragmented||(e.timeToSampleTable.push({sampleCount:1,sampleDelta:o}),e.compositionTimeOffsetTable.push({sampleCount:1,sampleCompositionTimeOffset:s}));e.lastSample=r}if(e.timestampProcessingQueue.length=0,a(e.lastSample),a(null!==e.lastTimescaleUnits),void 0!==t&&0===e.lastSample.timescaleUnitsToNextSample){a("key"===t.type);let i=Math.round(cM(t.timestamp,e.timescale,!1)-e.lastTimescaleUnits);e.lastSample.timescaleUnitsToNextSample=i}}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(a(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 i=!1;if(e.currentChunk){e.currentChunk.startTimestamp=Math.min(e.currentChunk.startTimestamp,t.timestamp);let r=t.timestamp-e.currentChunk.startTimestamp;if(this.isFragmented){let a=this.trackDatas.every(i=>{if(e===i)return"key"===t.type;let r=i.sampleQueue[0];return r?"key"===r.type:i.closed});r>=this.minimumFragmentDuration&&a&&t.timestamp>this.maxWrittenTimestamp&&(i=!0,await this.finalizeFragment())}else i=r>=.5}else i=!0;i&&(e.currentChunk&&await this.finalizeCurrentChunk(e),e.currentChunk={startTimestamp:t.timestamp,samples:[],offset:null,moofOffset:null,trafIndex:null}),a(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(a(!this.isFragmented),a(this.writer),!e.currentChunk)return;e.finalizedChunks.push(e.currentChunk),this.finalizedChunks.push(e.currentChunk);let t=e.currentChunk.samples.length;if("audio"===e.type&&e.info.requiresPcmTransformation&&(t=e.currentChunk.samples.reduce((t,i)=>t+cM(i.duration,e.timescale),0)),(0===e.compactlyCodedChunkTable.length||n(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))a(t.data),this.writer.write(t.data),t.data=null;await this.writer.flush()}async interleaveSamples(e=!1){if(a(this.isFragmented),e||this.allTracksAreKnown())t:for(;;){let t=null,i=1/0;for(let r of this.trackDatas){if(!e&&0===r.sampleQueue.length&&!r.closed)break t;r.sampleQueue.length>0&&r.sampleQueue[0].timestamp<i&&(t=r,i=r.sampleQueue[0].timestamp)}if(!t)break;let r=t.sampleQueue.shift();await this.addSampleToTrack(t,r)}}async finalizeFragment(e=!this.isCmaf){if(a(this.isFragmented),!this.wroteFragmentedHeader){this.wroteFragmentedHeader=!0;let e=this.initBoxWriter??this.boxWriter;a(e),this.formatOptions.onMoov&&e.writer.startTrackingWrites(),this.ensureOneEnabledTrack();let t=lg(this);if(e.writeBox(t),this.formatOptions.onMoov){let{data:t,start:i}=e.writer.stopTrackingWrites();this.formatOptions.onMoov(t,i)}if(this.isCmaf){a(this.initWriter),await this.initWriter.flush(),await this.initWriter.finalize(),this.writer=await this.output._getRootWriter(!0),this.boxWriter=new o2(this.writer);let e=this.boxWriter.measureBox(lm()),t=this.boxWriter.measureBox(lf(this,0));this.segmentHeaderSize=e+t,this.writer.seek(this.segmentHeaderSize)}}a(this.writer),a(this.boxWriter);let t=this.trackDatas.filter(e=>e.currentChunk);if(0===t.length){e&&await this.writer.flush();return}let i=this.nextFragmentNumber++,r=l8(i,t),s=this.writer.getPos(),n=s+this.boxWriter.measureBox(r),o=n+8,l=1/0;for(let e=0;e<t.length;e++){let i=t[e];
1for(let t of(i.currentChunk.offset=o,i.currentChunk.moofOffset=s,i.currentChunk.trafIndex=e,i.currentChunk.samples))o+=t.size;l=Math.min(l,i.currentChunk.startTimestamp)}let c=o-n,d=c>=0x100000000;if(d)for(let e of t)e.currentChunk.offset+=8;this.formatOptions.onMoof&&this.writer.startTrackingWrites();let u=l8(i,t);if(this.boxWriter.writeBox(u),this.formatOptions.onMoof){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoof(e,t,l)}a(this.writer.getPos()===n),this.formatOptions.onMdat&&this.writer.startTrackingWrites();let h=lp(d);for(let e of(h.size=c,this.boxWriter.writeBox(h),this.writer.seek(n+(d?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(){a(this.writer),a(this.boxWriter),this.ensureOneEnabledTrack();let e=lg(this),t=this.boxWriter.measureBox(e)+this.computeSampleTableSizeUpperBound()+4096;for(let e of(a(null!==this.ftypSize),this.writer.seek(this.ftypSize+t),this.formatOptions.onMdat&&this.writer.startTrackingWrites(),this.mdat=lp(!0),this.boxWriter.writeBox(this.mdat),this.trackDatas)){for(let t of e.sampleQueue)await this.addSampleToTrack(e,t);e.sampleQueue.length=0}}computeSampleTableSizeUpperBound(){a("reserve"===this.fastStart);let e=0;for(let t of this.trackDatas){let i=t.track.metadata.maximumPacketCount;a(void 0!==i),e+=8*Math.ceil(2/3*i)+4*i+8*Math.ceil(2/3*i)+12*Math.ceil(2/3*i)+4*i+8*i}return e}async onTrackClose(e){let t=await this.mutex.acquire(),i=this.trackDatas.find(t=>t.track===e);i&&(i.closed=!0,"subtitle"===i.type&&"webvtt"===e.source._codec&&await this.processWebVTTCues(i,1/0),this.processTimestamps(i)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),this.isFragmented&&await this.interleaveSamples(),t()}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(){a(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 i=e.samples[t];i.timestamp-=e.startTimestampOffset,i.decodeTimestamp-=e.startTimestampOffset}if(a(this.writer),a(this.boxWriter),"in-memory"===this.fastStart){let e;this.mdat=lp(!1);for(let t=0;t<2;t++){let t=lg(this),i=this.boxWriter.measureBox(t);e=this.boxWriter.measureBox(this.mdat);let r=this.writer.getPos()+i+e;for(let t of this.finalizedChunks)for(let{data:i}of(t.offset=r,t.samples))a(i),r+=i.byteLength,e+=i.byteLength;if(r<0x100000000)break;e>=0x100000000&&(this.mdat.largeSize=!0)}this.formatOptions.onMoov&&this.writer.startTrackingWrites();let t=lg(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)a(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(lm()),this.boxWriter.writeBox(lf(this,e))}else{let e=this.writer.getPos(),t=lu("mfra",void 0,[...this.trackDatas.map(ci),lh("mfro",0,0,[o9(0)])]);this.boxWriter.writeBox(t);let i=this.writer.getPos()-e;this.writer.seek(this.writer.getPos()-4),this.boxWriter.writeU32(i)}else{a(this.mdat);let e=this.boxWriter.offsets.get(this.mdat);a(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 i=lg(this);if("reserve"===this.fastStart){a(null!==this.ftypSize),this.writer.seek(this.ftypSize),this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);let e=this.boxWriter.offsets.get(this.mdat)-this.writer.getPos();this.boxWriter.writeBox({type:"free",size:e})}else this.formatOptions.onMoov&&this.writer.startTrackingWrites(),this.boxWriter.writeBox(i);if(this.formatOptions.onMoov){let{data:e,start:t}=this.writer.stopTrackingWrites();this.formatOptions.onMoov(e,t)}}e()}}let cD="Mediabunny",cz={video:1,audio:2,subtitle:17};class cO extends oj{constructor(e,t){super(e),this.trackDatas=[],this.allTracksKnown=B(),this.segment=null,this.segmentInfo=null,this.seekHead=null,this.tracksElement=null,this.tagsElement=null,this.attachmentsElement=null,this.segmentDuration=null,this.cues=null,this.currentCluster=null,this.currentClusterStartMsTimestamp=null,this.currentClusterMa
1xMsTimestamp=null,this.trackDatasInCurrentCluster=new Map,this.startTimestamp=1/0,this.endTimestamp=-1/0,this.format=t}async start(){let e=await this.mutex.acquire();for(let e of(this.writer=await this.output._getRootWriter(!!this.format._options.appendOnly),this.ebmlWriter=new re(this.writer),this.writeEBMLHeader(),this.createSegmentInfo(),this.createCues(),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()}writeEBMLHeader(){this.format._options.onEbmlHeader&&this.writer.startTrackingWrites();let e={id:ab.EBML,data:[{id:ab.EBMLVersion,data:1},{id:ab.EBMLReadVersion,data:1},{id:ab.EBMLMaxIDLength,data:4},{id:ab.EBMLMaxSizeLength,data:8},{id:ab.DocType,data:this.format instanceof dC?"webm":"matroska"},{id:ab.DocTypeVersion,data:2},{id:ab.DocTypeReadVersion,data:2}]};if(this.ebmlWriter.writeEBML(e),this.format._options.onEbmlHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onEbmlHeader(e,t)}}maybeCreateSeekHead(e){if(this.format._options.appendOnly)return;let t=new Uint8Array([28,83,187,107]),i=new Uint8Array([21,73,169,102]),r=new Uint8Array([22,84,174,107]),a=new Uint8Array([25,65,164,105]),s=new Uint8Array([18,84,195,103]),n={id:ab.SeekHead,data:[{id:ab.Seek,data:[{id:ab.SeekID,data:t},{id:ab.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.cues)-this.segmentDataOffset:0}]},{id:ab.Seek,data:[{id:ab.SeekID,data:i},{id:ab.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.segmentInfo)-this.segmentDataOffset:0}]},{id:ab.Seek,data:[{id:ab.SeekID,data:r},{id:ab.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tracksElement)-this.segmentDataOffset:0}]},this.attachmentsElement?{id:ab.Seek,data:[{id:ab.SeekID,data:a},{id:ab.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.attachmentsElement)-this.segmentDataOffset:0}]}:null,this.tagsElement?{id:ab.Seek,data:[{id:ab.SeekID,data:s},{id:ab.SeekPosition,size:5,data:e?this.ebmlWriter.offsets.get(this.tagsElement)-this.segmentDataOffset:0}]}:null]};this.seekHead=n}createSegmentInfo(){let e={id:ab.Duration,data:new i0(0)};this.segmentDuration=e;let t={id:ab.Info,data:[{id:ab.TimestampScale,data:1e6},{id:ab.MuxingApp,data:cD},{id:ab.WritingApp,data:cD},this.format._options.appendOnly?null:e]};this.segmentInfo=t}createTracks(){let e={id:ab.Tracks,data:[]};for(let t of(this.tracksElement=e,this.trackDatas)){let i=rh[t.track.source._codec];a(i),"audio"===t.type&&"dts"===t.track.source._codec&&("dtse"===t.info.decoderConfig.codec?i="A_DTS/EXPRESS":"dtsl"===t.info.decoderConfig.codec&&(i="A_DTS/LOSSLESS"));let r=0;if("audio"===t.type&&"opus"===t.track.source._codec){r=1e6*80;let e=t.info.decoderConfig.description;e&&(r=Math.round(1e9*(tG(d(e)).preSkip/48e3)))}e.data.push({id:ab.TrackEntry,data:[{id:ab.TrackNumber,data:t.track.id},{id:ab.TrackUID,data:t.track.id},{id:ab.TrackType,data:cz[t.type]},t.track.metadata.disposition?.default===!1?{id:ab.FlagDefault,data:0}:null,t.track.metadata.disposition?.forced?{id:ab.FlagForced,data:1}:null,t.track.metadata.disposition?.hearingImpaired?{id:ab.FlagHearingImpaired,data:1}:null,t.track.metadata.disposition?.visuallyImpaired?{id:ab.FlagVisualImpaired,data:1}:null,t.track.metadata.disposition?.original?{id:ab.FlagOriginal,data:1}:null,t.track.metadata.disposition?.commentary?{id:ab.FlagCommentary,data:1}:null,{id:ab.FlagLacing,data:0},{id:ab.Language,data:t.track.metadata.languageCode??"und"},{id:ab.CodecID,data:i},t.codecPrivate?{id:ab.CodecPrivate,data:d(t.codecPrivate)}:null,{id:ab.CodecDelay,data:0},{id:ab.SeekPreRoll,data:r},void 0!==t.track.metadata.name?{id:ab.Name,data:new i2(t.track.metadata.name)}:null,"video"===t.type?this.videoSpecificTrackInfo(t):null,"audio"===t.type?this.audioSpecificTrackInfo(t):null,"subtitle"===t.type?this.subtitleSpecificTrackInfo(t):null]})}}videoSpecificTrackInfo(e){let{frameRate:t,rotation:i}=e.track.metadata,r=[t?{id:ab.DefaultDuration,data:1e9/t}
1:null],a=i?s(-i):0,n=!!e.info.aspectRatio&&e.info.aspectRatio.num*e.info.height!=e.info.aspectRatio.den*e.info.width,o=e.info.decoderConfig.colorSpace;return r.push({id:ab.Video,data:[{id:ab.PixelWidth,data:e.info.width},{id:ab.PixelHeight,data:e.info.height},n?{id:ab.DisplayWidth,data:e.info.aspectRatio.num}:null,n?{id:ab.DisplayHeight,data:e.info.aspectRatio.den}:null,n?{id:ab.DisplayUnit,data:3}:null,e.info.alphaMode?{id:ab.AlphaMode,data:1}:null,S(o)?{id:ab.Colour,data:[{id:ab.MatrixCoefficients,data:b[o.matrix]},{id:ab.TransferCharacteristics,data:y[o.transfer]},{id:ab.Primaries,data:g[o.primaries]},{id:ab.Range,data:o.fullRange?2:1}]}:null,a?{id:ab.Projection,data:[{id:ab.ProjectionType,data:0},{id:ab.ProjectionPoseRoll,data:new iZ((a+180)%360-180)}]}:null]}),r}audioSpecificTrackInfo(e){let t=eK.includes(e.track.source._codec)?tr(e.track.source._codec):null;return[{id:ab.Audio,data:[{id:ab.SamplingFrequency,data:new iZ(e.info.sampleRate)},{id:ab.Channels,data:e.info.numberOfChannels},t?{id:ab.BitDepth,data:8*t.sampleSize}:null]}]}subtitleSpecificTrackInfo(e){return[]}maybeCreateTags(){let e=[],t=(t,i)=>{e.push({id:ab.SimpleTag,data:[{id:ab.TagName,data:new i2(t)},"string"==typeof i?{id:ab.TagString,data:new i2(i)}:{id:ab.TagBinary,data:i}]})},i=this.output._metadataTags,r=new Set;for(let{key:e,value:a}of ed(i))switch(e){case"title":t("TITLE",a),r.add("TITLE");break;case"description":t("DESCRIPTION",a),r.add("DESCRIPTION");break;case"artist":t("ARTIST",a),r.add("ARTIST");break;case"album":t("ALBUM",a),r.add("ALBUM");break;case"albumArtist":t("ALBUM_ARTIST",a),r.add("ALBUM_ARTIST");break;case"genre":t("GENRE",a),r.add("GENRE");break;case"comment":t("COMMENT",a),r.add("COMMENT");break;case"lyrics":t("LYRICS",a),r.add("LYRICS");break;case"date":t("DATE",a.toISOString().slice(0,10)),r.add("DATE");break;case"trackNumber":t("PART_NUMBER",void 0!==i.tracksTotal?`${a}/${i.tracksTotal}`:a.toString()),r.add("PART_NUMBER");break;case"discNumber":t("DISC",void 0!==i.discsTotal?`${a}/${i.discsTotal}`:a.toString()),r.add("DISC");break;case"tracksTotal":case"discsTotal":case"images":case"raw":break;default:z(e)}if(i.raw)for(let e in i.raw){let a=i.raw[e];!(null==a||r.has(e))&&("string"==typeof a||a instanceof Uint8Array)&&t(e,a)}0!==e.length&&(this.tagsElement={id:ab.Tags,data:[{id:ab.Tag,data:[{id:ab.Targets,data:[{id:ab.TargetTypeValue,data:50},{id:ab.TargetType,data:"MOVIE"}]},...e]}]})}maybeCreateAttachments(){let e=this.output._metadataTags,t=[],i=new Set,r=e.images??[];for(let e of r){let r,a=e.name;for(void 0===a&&(a=("coverFront"===e.kind?"cover":"coverBack"===e.kind?"back":"image")+(eu(e.mimeType)??""));;){r=0n;for(let e=0;e<8;e++)r<<=8n,r|=BigInt(Math.floor(256*Math.random()));if(0n!==r&&!i.has(r))break}i.add(r),t.push({id:ab.AttachedFile,data:[void 0!==e.description?{id:ab.FileDescription,data:new i2(e.description)}:null,{id:ab.FileName,data:new i2(a)},{id:ab.FileMediaType,data:e.mimeType},{id:ab.FileData,data:e.data},{id:ab.FileUID,data:r}]})}for(let[i,a]of Object.entries(e.raw??{}))a instanceof ez&&/^\d+$/.test(i)&&(r.find(e=>
1e.mimeType===a.mimeType&&ef(e.data,a.data))||t.push({id:ab.AttachedFile,data:[void 0!==a.description?{id:ab.FileDescription,data:new i2(a.description)}:null,{id:ab.FileName,data:new i2(a.name??"")},{id:ab.FileMediaType,data:a.mimeType??""},{id:ab.FileData,data:a.data},{id:ab.FileUID,data:BigInt(i)}]}));0!==t.length&&(this.attachmentsElement={id:ab.Attachments,data:t})}createSegment(){this.createTracks(),this.maybeCreateTags(),this.maybeCreateAttachments(),this.maybeCreateSeekHead(!1);let e={id:ab.Segment,size:this.format._options.appendOnly?-1:6,data:[this.seekHead,this.segmentInfo,this.tracksElement,this.attachmentsElement,this.tagsElement]};if(this.segment=e,this.format._options.onSegmentHeader&&this.writer.startTrackingWrites(),this.ebmlWriter.writeEBML(e),this.format._options.onSegmentHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onSegmentHeader(e,t)}}createCues(){this.cues={id:ab.Cues,data:[]}}get segmentDataOffset(){return a(this.segment),this.ebmlWriter.dataOffsets.get(this.segment)}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 rf({isWebM:this.format instanceof dC,hasVideo:this.trackDatas.some(e=>"video"===e.type),hasAudio:this.trackDatas.some(e=>"audio"===e.type),codecStrings:e})}getVideoTrackData(e,t,i){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;td(i,e.source._codec),a(i),a(i.decoderConfig),a(void 0!==i.decoderConfig.codedWidth),a(void 0!==i.decoderConfig.codedHeight);let s=i.decoderConfig.displayAspectWidth,n=i.decoderConfig.displayAspectHeight,o=void 0===s||void 0===n?null:eT({num:s,den:n}),l={track:e,type:"video",info:{width:i.decoderConfig.codedWidth,height:i.decoderConfig.codedHeight,aspectRatio:o,decoderConfig:i.decoderConfig,alphaMode:t?!!t.sideData.alpha:null},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:i.decoderConfig.description??null,closed:!1};return"vp9"===e.source._codec?l.codecPrivate=new Uint8Array((e=>{let t=e.split("."),i=Number(t[1]),r=Number(t[2]);return[1,1,i,2,1,r,3,1,Number(t[3]),4,1,t[4]?Number(t[4]):1]})(l.info.decoderConfig.codec)):"av1"===e.source._codec?l.codecPrivate=new Uint8Array(e7(l.info.decoderConfig.codec)):"prores"===e.source._codec&&(l.codecPrivate=m.encode(i.decoderConfig.codec)),this.trackDatas.push(l),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),l}getAudioTrackData(e,t,i){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;th(i,e.source._codec),a(i),a(i.decoderConfig);let s={...i.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=rD(og.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 i=eV[e.samplingFrequencyIndex],r=eL[e.channelConfiguration];if(void 0===i||void 0===r)throw Error("Invalid ADTS frame header.");s.description=eH({objectType:e.objectType,sampleRate:i,numberOfChannels:r}),n=!0}let o={track:e,type:"audio",info:{numberOfChannels:i.decoderConfig.numberOfChannels,sampleRate:i.decoderConfig.sampleRate,decoderConfig:s,requiresAdtsStripping:n},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:s.description??null,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 i=this.trackDatas.find(t=>t.track===e);if(i)return i;tm(t),a(t),a(t.config);let r={track:e,type:"subtitle",info:{config:t.config},chunkQueue:[],lastWrittenMsTimestamp:null,codecPrivate:m.encode(t.config.description),closed:!1}
1;return this.trackDatas.push(r),this.trackDatas.sort((e,t)=>e.track.id-t.track.id),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),r}async addEncodedVideoPacket(e,t,i){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,t,i);r.info.alphaMode??=!!t.sideData.alpha;let a=t.data;if("prores"===e.source._codec){if(a.byteLength<8)throw Error("ProRes packet too small, expected at least 8 bytes.");a=a.subarray(8)}let s="key"===t.type;this.validateTimestamp(r.track,t.timestamp,s);let n=t.timestamp,o=t.duration;void 0!==e.metadata.frameRate&&(n=q(n,e.metadata.frameRate),o=q(o,e.metadata.frameRate));let l=r.info.alphaMode?t.sideData.alpha??null:null,c=this.createInternalChunk(a,n,o,t.type,l);"vp9"===e.source._codec&&this.fixVP9ColorSpace(r,c),r.chunkQueue.push(c),await this.interleaveChunks()}finally{r()}}async addEncodedAudioPacket(e,t,i){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,t,i),a=t.data;if(r.info.requiresAdtsStripping){let e=rD(og.tempFromBytes(a));if(!e)throw Error("Expected ADTS frame, didn't get one.");let t=null===e.crcCheck?7:9;a=a.subarray(t)}let s="key"===t.type;this.validateTimestamp(r.track,t.timestamp,s);let n=this.createInternalChunk(a,t.timestamp,t.duration,t.type);r.chunkQueue.push(n),await this.interleaveChunks()}finally{r()}}async addSubtitleCue(e,t,i){let r=await this.mutex.acquire();try{let r=this.getSubtitleTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,!0);let a=t.text,s=Math.round(1e3*t.timestamp);oY.lastIndex=0,a=a.replace(oY,e=>{let t=o0(e.slice(1,-1));return`<${o1(t-s)}>`});let n=m.encode(a),o=`${t.settings??""}
2${t.identifier??""}
3${t.notes??""}`,l=this.createInternalChunk(n,t.timestamp,t.duration,"key",o.trim()?m.encode(o):null);r.chunkQueue.push(l),await this.interleaveChunks()}finally{r()}}async interleaveChunks(e=!1){if(e||this.allTracksAreKnown()){t:for(;;){let t=null,i=1/0;for(let r of this.trackDatas){if(!e&&0===r.chunkQueue.length&&!r.closed)break t;r.chunkQueue.length>0&&r.chunkQueue[0].timestamp<i&&(t=r,i=r.chunkQueue[0].timestamp)}if(!t)break;let r=t.chunkQueue.shift();this.writeBlock(t,r)}e||await this.writer.flush()}}fixVP9ColorSpace(e,t){if("key"!==t.type||!e.info.decoderConfig.colorSpace||!e.info.decoderConfig.colorSpace.matrix)return;let i=new eW(t.data);i.skipBits(2);let r=i.readBits(1),a=(i.readBits(1)<<1)+r;if(3===a&&i.skipBits(1),i.readBits(1)||0!==i.readBits(1)||(i.skipBits(2),4817730!==i.readBits(24)))return;a>=2&&i.skipBits(1);let s={rgb:7,bt709:2,bt470bg:1,smpte170m:3}[e.info.decoderConfig.colorSpace.matrix];((e,t,i,r)=>{for(let a=t;a<i;a++){let t=Math.floor(a/8),s=e[t],n=7-(7&a);s&=~(1<<n),s|=(r&1<<i-a-1)>>i-a-1<<n,e[t]=s}})(t.data,i.pos,i.pos+3,s)}createInternalChunk(e,t,i,r,a=null){return{data:e,type:r,timestamp:t,duration:i,additions:a}}writeBlock(e,t){this.segment||this.createSegment();let i=Math.round(1e3*t.timestamp),r=this.trackDatas.every(i=>{if(e===i)return"key"===t.type;let r=i.chunkQueue[0];return r?"key"===r.type:i.closed}),s=!1;if(this.currentCluster){a(null!==this.currentClusterStartMsTimestamp),a(null!==this.currentClusterMaxMsTimestamp);let e=i-this.currentClusterStartMsTimestamp;s=r&&i>this.currentClusterMaxMsTimestamp&&e>=1e3*(this.format._options.minimumClusterDuration??1)||e>32767}else s=!0;s&&this.createNewCluster(i);let n=i-this.currentClusterStartMsTimestamp;if(n<-32768)return;let o=new Uint8Array(4),l=new DataView(o.buffer);l.setUint8(0,128|e.track.id),l.setInt16(1,n,!1);let c=Math.round(1e3*t.duration);if(t.additions||"subtitle"===e.type){let r={id:ab.BlockGroup,data:[{id:ab.Block,data:[o,t.data]},"delta"===t.type?{id:ab.ReferenceBlock,data:new i1(e.lastWrittenMsTimestamp-i)}:null,t.additions?{id:ab.BlockAdditions,data:[{id:ab.BlockMore,data:[{id:ab.BlockAddID,data:1},{id:ab.BlockAdditional,data:t.additions}]}]}:null,c>0?{id:ab.BlockDuration,data:c}:null]};this.ebmlWriter.writeEBML(r)}else{l.setUint8(3,Number("key"===t.type)<<7);let e={id:ab.SimpleBlock,data:[o,t.data]};this.ebmlWriter.writeEBML(e)}this.startTimestamp=Math.min(this.startTimestamp,i),this.endTimestamp=Math.max(this.endTimestamp,i+c),e.lastWrittenMsTimestamp=i,this.trackDatasInCurrentCluster.has(e)||this.trackDatasInCurrentCluster.set(e,{firstMsTimestamp:i}
3),this.currentClusterMaxMsTimestamp=Math.max(this.currentClusterMaxMsTimestamp,i)}createNewCluster(e){this.currentCluster&&this.finalizeCurrentCluster(),this.format._options.onCluster&&this.writer.startTrackingWrites(),this.currentCluster={id:ab.Cluster,size:this.format._options.appendOnly?-1:5,data:[{id:ab.Timestamp,data:e}]},this.ebmlWriter.writeEBML(this.currentCluster),this.currentClusterStartMsTimestamp=e,this.currentClusterMaxMsTimestamp=e,this.trackDatasInCurrentCluster.clear()}finalizeCurrentCluster(){if(a(this.currentCluster),!this.format._options.appendOnly){let e=this.writer.getPos()-this.ebmlWriter.dataOffsets.get(this.currentCluster),t=this.writer.getPos();this.writer.seek(this.ebmlWriter.offsets.get(this.currentCluster)+4),this.ebmlWriter.writeVarInt(e,5),this.writer.seek(t)}if(this.format._options.onCluster){a(null!==this.currentClusterStartMsTimestamp);let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onCluster(e,t,this.currentClusterStartMsTimestamp/1e3)}let e=this.ebmlWriter.offsets.get(this.currentCluster)-this.segmentDataOffset,t=new Map;for(let[e,{firstMsTimestamp:i}]of this.trackDatasInCurrentCluster)t.has(i)||t.set(i,[]),t.get(i).push(e);for(let[i,r]of[...t.entries()].sort((e,t)=>e[0]-t[0]))a(this.cues),this.cues.data.push({id:ab.CuePoint,data:[{id:ab.CueTime,data:i},...r.map(t=>({id:ab.CueTrackPositions,data:[{id:ab.CueTrack,data:t.track.id},{id:ab.CueClusterPosition,data:e}]}))]})}async onTrackClose(e){let t=await this.mutex.acquire(),i=this.trackDatas.find(t=>t.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleaveChunks(),t()}async finalize(){let e=await this.mutex.acquire();for(let e of(this.allTracksKnown.resolve(),this.trackDatas))e.closed=!0;if(this.segment||this.createSegment(),await this.interleaveChunks(!0),this.currentCluster&&this.finalizeCurrentCluster(),a(this.cues),this.ebmlWriter.writeEBML(this.cues),!this.format._options.appendOnly){let e=this.writer.getPos()-this.segmentDataOffset;this.writer.seek(this.ebmlWriter.offsets.get(this.segment)+4),this.ebmlWriter.writeVarInt(e,6);let t=this.startTimestamp===1/0?0:this.endTimestamp-this.startTimestamp;this.segmentDuration.data=new i0(t),this.writer.seek(this.ebmlWriter.offsets.get(this.segmentDuration)),this.ebmlWriter.writeEBML(this.segmentDuration),a(this.seekHead),this.writer.seek(this.ebmlWriter.offsets.get(this.seekHead)),this.maybeCreateSeekHead(!0),this.ebmlWriter.writeEBML(this.seekHead)}e()}}class cU{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU32(e){this.helperView.setUint32(0,e,!1),this.writer.write(this.helper.subarray(0,4))}writeXingFrame(e){let t,i=this.writer.getPos(),r=224|e.mpegVersionId<<3|e.layer<<1;t=2&e.mpegVersionId&&1&e.mpegVersionId?0:1;let a=-1,s=16*t*4+16*e.layer;for(let i=0;i<16;i++){let r=tp[s+i];if(tg(t,e.layer,1e3*r,e.sampleRate,0)>=155){a=i;break}}if(-1===a)throw Error("No suitable bitrate found.");let n=a<<4|e.frequencyIndex<<2,o=e.channel<<6|e.modeExtension<<4|e.copyright<<3|e.original<<2|e.emphasis;this.helper[0]=255,this.helper[1]=r,this.helper[2]=n,this.helper[3]=o,this.writer.write(this.helper.subarray(0,4));let l=tk(e.mpegVersionId,e.channel);this.writer.seek(i+l),this.writeU32(0x58696e67);let c=0;null!==e.frameCount&&(c|=ap.FrameCount),null!==e.fileSize&&(c|=ap.FileSize),null!==e.toc&&(c|=ap.Toc),this.writeU32(c),this.writeU32(e.frameCount??0),this.writeU32(e.fileSize??0),this.writer.write(e.toc??new Uint8Array(100));let d=tp[s+a],u=tg(t,e.layer,1e3*d,e.sampleRate,0);this.writer.write(new Uint8Array(i+u-this.writer.getPos()))}}class cN extends oj{constructor(e,t){super(e),this.xingFrameData=null,this.frameCount=0,this.framePositions=[],this.xingFramePos=null,this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1===this.format._options.xingHeader),this.mp3Writer=new cU(this.writer),eU(this.output._metadataTags)||new oH(this.writer).writeId3V2Tag(this.output._metadataTags),e()}async getMimeType(){return"audio/mpeg"}async addEncodedVideoPacket(){throw Error("MP3 does not support video.")}async addEncodedAudioPacket(e,t){let i=await this.mutex.acquire();try{let i=!1!==this.format._options.xingHeader;if(!this.xingFrameData&&i){let e=u(t.data);if(e.byteLength<4)throw Error("Invalid MP3 header in sample.");let i=e.getUint32(0,!1),r=ty(i,null).header;if(!r)throw Error("Invalid MP3 header in sample.");let a=tk(r.mpegVersionId,r.channel);if(e.byteLength>=a+4){let t=e.getUint32(a,!1);if(0x58696e67===t||0x496e666f===t)return}this.xingFrameData={mpegVersionId:r.mpegVersionId,layer:r.layer,frequencyIndex:r.frequencyIndex,sampleRate:r.sampleRate,channel:r.channel,modeExtension:r.modeExtension,copyright:r.copyright,original:r.original,emphasis:r.emphasis,frameCount:null,fileSize:null,toc:null},this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}this.validateTimestamp(e,t.timestamp,"key"===t.type),i&&this.framePositions.push(this.writer.getPos()),this.writer.write(t.data),this.frameCount++,await this.writer.flush()}finally{i()}}async addSubtitleCue(){throw Error("MP3 does not support subtitles.")}async finalize(){let e=await this.mutex.acquire();if(!this.xingFrameData&&!1===this.format._options.xingHeader)throw Error("Cannot finalize an empty MP3 file: not a single packet was added and the Xing header is disabled, so there's no frame we could write.");if(!this.xingFrameData){let e=this.output.tracks[0];a(e?.isAudioTrack());let t=e.metadata.primingPacket;if(t){let e=u(t.data);if(e.byteLength<4)throw Error("Invalid MP3 header in priming packet.");let i=ty(e.getUint32(0,!1),null).header;if(!i)throw Error("Invalid MP3 header in priming packet.");this.xingFrameData={mpegVersionId:i.mpegVersionId,layer:i.layer,frequencyIndex:i.frequencyIndex,sampleRate:i.sampleRate,channel:i.channel,modeExtension:i.modeExtension,copyright:i.copyright,original:i.original,emphasis:i.emphasis,frameCount:null,fileSize:null,toc:null}}else if(e.metadata.decoderConfig){let{sampleRate:t,numberOfChannels:i}=e.metadata.decoderConfig,r=[3,2,0],a=null,s=-1;for(let e=0;e<r.length;e++)if(-1!==(s=tf.indexOf(t<<e))){a=r[e];break}if(null===a)throw Error(`${t} Hz is not a valid MP3 sample rate.`);this.xingFrameData={mpegVersionId:a,layer:1,frequencyIndex:s,sampleRate:t,channel:3*(1===i),modeExtension:0,copyright:0,original:0,emphasis:0,frameCount:null,fileSize:null,toc:null}}else throw Error("Cannot finalize an empty MP3 file: no packets were added and the track specified neither a decoderConfig nor a primingPacket in its metadata, so there's no telling what the file should look like.");this.xingFramePos=this.writer.getPos(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.frameCount++}
3a(null!==this.xingFramePos);let t=this.writer.getPos()-this.xingFramePos;if(this.writer.seek(this.xingFramePos),this.framePositions.length>0){let e=new Uint8Array(100);for(let i=0;i<100;i++){let r=Math.floor(this.framePositions.length*(i/100)),a=this.framePositions[r]-this.xingFramePos;e[i]=a/t*256}this.xingFrameData.toc=e}if(this.xingFrameData.frameCount=this.frameCount,this.xingFrameData.fileSize=t,this.format._options.onXingFrame&&this.writer.startTrackingWrites(),this.mp3Writer.writeXingFrame(this.xingFrameData),this.format._options.onXingFrame){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onXingFrame(e,t)}e()}}class cW extends oj{constructor(e,t){super(e),this.trackDatas=[],this.bosPagesWritten=!1,this.allTracksKnown=B(),this.pageBytes=new Uint8Array(65307),this.pageView=new DataView(this.pageBytes.buffer),this.format=t}async start(){let e=await this.mutex.acquire();for(let e of(this.writer=await this.output._getRootWriter(!0),this.output.tracks))a(e.isAudioTrack()),e.metadata.decoderConfig&&this.getTrackData(e,{decoderConfig:e.metadata.decoderConfig});e()}async getMimeType(){return await this.allTracksKnown.promise,rC({codecStrings:this.trackDatas.map(e=>e.codecInfo.codec)})}addEncodedVideoPacket(){throw Error("Video tracks are not supported.")}getTrackData(e,t){let i,r=this.trackDatas.find(t=>t.track===e);if(r)return r;do i=Math.floor(0x100000000*Math.random());while(this.trackDatas.some(e=>e.serialNumber===i));a("vorbis"===e.source._codec||"opus"===e.source._codec),th(t,e.source._codec),a(t),a(t.decoderConfig);let s={track:e,serialNumber:i,internalSampleRate:"opus"===e.source._codec?48e3:t.decoderConfig.sampleRate,codecInfo:{codec:e.source._codec,vorbisInfo:null,opusInfo:null},vorbisLastBlocksize:null,packetQueue:[],currentTimestampInSamples:0,pagesWritten:0,currentGranulePosition:0,
3currentLacingValues:[],currentPageData:[],currentPageSize:27,currentPageStartsWithFreshPacket:!0,currentPageStartTimestampInSamples:0,closed:!1};return this.queueHeaderPackets(s,t),this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}queueHeaderPackets(e,t){if(a(t.decoderConfig),"vorbis"===e.track.source._codec){a(t.decoderConfig.description);let i=d(t.decoderConfig.description);if(2!==i[0])throw TypeError("First byte of Vorbis decoder description must be 2.");let r=1,s=()=>{let e=0;for(;;){let t=i[r++];if(void 0===t)throw TypeError("Vorbis decoder description is too short.");if(e+=t,t<255)return e}},n=s(),o=s();if(i.length-r<=0)throw TypeError("Vorbis decoder description is too short.");let l=i.subarray(r,r+=n);r+=o;let c=i.subarray(r),h=new Uint8Array(7);h[0]=3,h[1]=118,h[2]=111,h[3]=114,h[4]=98,h[5]=105,h[6]=115;let m=t1(h,this.output._metadataTags,!0);e.packetQueue.push({data:l,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:m,timestampInSamples:0,durationInSamples:0,forcePageFlush:!1},{data:c,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0});let f=u(l).getUint8(28);e.codecInfo.vorbisInfo={blocksizes:[1<<(15&f),1<<(f>>4)],modeBlockflags:tJ(c).modeBlockflags}}else if("opus"===e.track.source._codec){if(!t.decoderConfig.description)throw TypeError("For Ogg, Opus decoder description is required.");let i=d(t.decoderConfig.description),r=new Uint8Array(8),a=u(r);a.setUint32(0,0x4f707573,!1),a.setUint32(4,0x54616773,!1);let s=t1(r,this.output._metadataTags,!0);e.packetQueue.push({data:i,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0},{data:s,timestampInSamples:0,durationInSamples:0,forcePageFlush:!0}),e.codecInfo.opusInfo={preSkip:tG(i).preSkip}}}async addEncodedAudioPacket(e,t,i){let r=await this.mutex.acquire();try{let r=this.getTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,"key"===t.type);let a=r.currentTimestampInSamples,{durationInSamples:s,vorbisBlockSize:n}=rP(t.data,r.codecInfo,r.vorbisLastBlocksize);r.currentTimestampInSamples+=s,r.vorbisLastBlocksize=n,r.packetQueue.push({data:t.data,timestampInSamples:a,durationInSamples:s,forcePageFlush:!1}),await this.interleavePages()}finally{r()}}addSubtitleCue(){throw Error("Subtitle tracks are not supported.")}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async interleavePages(e=!1){if(!this.bosPagesWritten){if(!this.allTracksAreKnown()&&!e)return;for(let e of this.trackDatas)for(;e.packetQueue.length>0;){let t=e.packetQueue.shift();if(this.writePacket(e,t,!1),t.forcePageFlush)break}this.bosPagesWritten=!0}t:for(;;){let t=null,i=1/0;for(let r of this.trackDatas){if(!e&&r.packetQueue.length<=1&&!r.closed)break t;r.packetQueue.length>0&&r.packetQueue[0].timestampInSamples<i&&(t=r,i=r.packetQueue[0].timestampInSamples)}if(!t)break;let r=t.packetQueue.shift(),a=0===t.packetQueue.length;this.writePacket(t,r,a)}e||await this.writer.flush()}writePacket(e,t,i){let r=t.timestampInSamples+t.durationInSamples;if(void 0!==this.format._options.maximumPageDuration){let t=this.format._options.maximumPageDuration*e.internalSampleRate;e.currentLacingValues.length>0&&r-e.currentPageStartTimestampInSamples>t&&this.writePage(e,!1)}let a=t.data.length,s=0,n=0;for(;;){0===e.currentLacingValues.length&&s>0&&(e.currentPageStartsWithFreshPacket=!1);let r=Math.min(255,a);e.currentLacingValues.push(r),e.currentPageSize++,n+=r;let o=a<255;if(255===e.currentLacingValues.length){let r=t.data.subarray(s,n);if(s=n,e.currentPageData.push(r),e.currentPageSize+=r.length,this.writePage(e,i&&o),o)return}if(o)break;a-=255}let o=t.data.subarray(s);e.currentPageData.push(o),e.currentPageSize+=o.length,e.currentGranulePosition=r,(e.currentPageSize>=8192||t.forcePageFlush)&&this.writePage(e,i)}writePage(e,t){var i;this.pageView.setUint32(0,0x5367674f,!0),this.pageView.setUint8(4,0);let r=0;e.currentPageStartsWithFreshPacket||(r|=1),0===e.pagesWritten&&(r|=2),t&&(r|=4),this.pageView.setUint8(5,r);let a=e.currentLacingValues.every(e=>255===e)?-1:e.currentGranulePosition;i=this.pageView,i.setUint32(6,a,!0),i.setInt32(10,Math.floor(a/0x100000000),!0),this.pageView.setUint32(14,e.serialNumber,!0),this.pageView.setUint32(18,e.pagesWritten,!0),this.pageView.setUint32(22,0,!0),this.pageView.setUint8(26,e.currentLacingValues.length),this.pageBytes.set(e.currentLacingValues,27);let s=27+e.currentLacingValues.length;for(let t of e.currentPageData)this.pageBytes.set(t,s),s+=t.length;let n=this.pageBytes.subarray(0,s),o=rv(n);if(this.pageView.setUint32(22,o,!0),e.pagesWritten++,e.currentLacingValues.length=0,e.currentPageData.length=0,e.currentPageSize=27,e.currentPageStartsWithFreshPacket=!0,e.currentPageStartTimestampInSamples=e.currentGranulePosition,this.format._options.onPage&&this.writer.startTrackingWrites(),this.writer.write(n),this.format._options.onPage){let{data:t,start:i}=this.writer.stopTrackingWrites();this.format._options.onPage(t,i,e.track.source)}}async onTrackClose(e){let t=await this.mutex.acquire(),i=this.trackDatas.find(t=>t.track===e);i&&(i.closed=!0),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePages(),t()}async finalize(){let e=await this.mutex.acquire();for(let e of(this.allTracksKnown.resolve(),this.trackDatas))e.closed=!0;for(let e of(await this.interleavePages(!0),this.trackDatas))e.currentLacingValues.length>0&&this.writePage(e,!0);e()}}let cV=new Uint8Array([9,240]),cL=new Uint8Array([70,1]);class cq extends oj{constructor(e,t){super(e),this.trackDatas=[],this.tablesWritten=!1,this.continuityCounters=new Map,this.packetBuffer=new Uint8Array(188),this.packetView=u(this.packetBuffer),this.allTracksKnown=B(),this.videoTrackIndex=0,this.audioTrackIndex=0,this.adaptationFieldBuffer=new Uint8Array(184),this.payloadBuffer=new Uint8Array(184),this.format=t}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!0),e()}async getMimeType(){return await this.allTracksKnown.promise,rq(this.trackDatas.map(e=>e.codecString))}getVideoTrackData(e,t){let i=this.trackDatas.find(t=>t.track===e);if(i)return i;td(t,e.source._codec),a(t?.decoderConfig);let r=e.source._codec;a("avc"===r||"hevc"===r);let s={track:e,pid:256+this.trackDatas.length,streamType:"avc"===r?27:36,streamId:224+this.videoTrackIndex++,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1}
3;return this.trackDatas.push(s),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),s}getAudioTrackData(e,t){let i,r,s=this.trackDatas.find(t=>t.track===e);if(s)return s;th(t,e.source._codec),a(t?.decoderConfig);let n=e.source._codec;switch(a("aac"===n||"mp3"===n||"ac3"===n||"eac3"===n||"dts"===n),n){case"aac":i=15,r=192+this.audioTrackIndex++;break;case"mp3":i=3,r=192+this.audioTrackIndex++;break;case"ac3":i=129,r=189;break;case"eac3":i=135,r=189;break;case"dts":i=130,r=189}let o={track:e,pid:256+this.trackDatas.length,streamType:i,streamId:r,codecString:t.decoderConfig.codec,timestampProcessingQueue:[],packetQueue:[],inputIsAnnexB:null,inputIsAdts:null,avcDecoderConfig:null,hevcDecoderConfig:null,adtsHeader:null,adtsHeaderBitstream:null,firstPacketWritten:!1,closed:!1};return this.trackDatas.push(o),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),o}async addEncodedVideoPacket(e,t,i){let r=await this.mutex.acquire();try{let r=this.getVideoTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,"key"===t.type);let a=this.prepareVideoPacket(r,t,i);"key"===t.type&&await this.flushTimestampQueue(r),r.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:"key"===t.type})}finally{r()}}async addEncodedAudioPacket(e,t,i){let r=await this.mutex.acquire();try{let r=this.getAudioTrackData(e,i);this.validateTimestamp(r.track,t.timestamp,"key"===t.type);let a=this.prepareAudioPacket(r,t,i);"key"===t.type&&await this.flushTimestampQueue(r),r.timestampProcessingQueue.push({data:a,presentationTimestamp:t.timestamp,decodeTimestamp:null,isKeyframe:"key"===t.type})}finally{r()}}async addSubtitleCue(){throw Error("MPEG-TS does not support subtitles.")}prepareVideoPacket(e,t,i){let r=e.track.source._codec;if(null===e.inputIsAnnexB){let t=i?.decoderConfig?.description;if(e.inputIsAnnexB=!t,!e.inputIsAnnexB){let i=d(t);"avc"===r?e.avcDecoderConfig=tF(i):e.hevcDecoderConfig=(e=>{try{let t=u(e),i=0,r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint32(i,!1);i+=4;let n=e.subarray(i,i+6);i+=6;let o=t.getUint8(i++),l=(15&t.getUint8(i++))<<8|t.getUint8(i++),c=3&t.getUint8(i++),d=3&t.getUint8(i++),h=7&t.getUint8(i++),m=7&t.getUint8(i++),f=t.getUint16(i,!1);i+=2;let p=t.getUint8(i++),g=t.getUint8(i++),k=[];for(let r=0;r<g;r++){let r=t.getUint8(i++),a=r>>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;let o=[];for(let r=0;r<n;r++){let r=t.getUint16(i,!1);i+=2,o.push(e.subarray(i,i+r)),i+=r}k.push({arrayCompleteness:a,nalUnitType:s,nalUnits:o})}return{configurationVersion:r,generalProfileSpace:a>>6&3,generalTierFlag:a>>5&1,generalProfileIdc:31&a,generalProfileCompatibilityFlags:s,generalConstraintIndicatorFlags:n,generalLevelIdc:o,minSpatialSegmentationIdc:l,parallelismType:c,chromaFormatIdc:d,bitDepthLumaMinus8:h,bitDepthChromaMinus8:m,avgFrameRate:f,constantFrameRate:p>>6&3,numTemporalLayers:p>>3&7,temporalIdNested:p>>2&1,lengthSizeMinusOne:3&p,arrays:k}}catch(e){return eR._error("Error deserializing HEVC Decoder Configuration Record:",e),null}})(i)}}return e.inputIsAnnexB?this.prepareAnnexBVideoPacket(t.data,r):this.prepareLengthPrefixedVideoPacket(e,t,r)}prepareAnnexBVideoPacket(e,t){let i=[];for(let r of tA(e)){let a=e.subarray(r.offset,r.offset+r.length);("avc"===t?tC(a[0])===ag.AUD:tO(a[0])===ak.AUD_NUT)||i.push(a)}return i.unshift("avc"===t?cV:cL),t_(i)}prepareLengthPrefixedVideoPacket(e,t,i){let r=t.data,a="avc"===i?e.avcDecoderConfig.lengthSizeMinusOne+1:e.hevcDecoderConfig.lengthSizeMinusOne+1,s=[];for(let e of tv(r,a)){let t=r.subarray(e.offset,e.offset+e.length);("avc"===i?tC(t[0])===ag.AUD:tO(t[0])===ak.AUD_NUT)||s.push(t)}if("key"===t.type)if("avc"===i){let t=e.avcDecoderConfig;for(let e of t.pictureParameterSets)s.unshift(e);for(let e of t.sequenceParameterSets)s.unshift(e)}else{let t=e.hevcDecoderConfig;for(let e of t.arrays)if(e.nalUnitType===ak.PPS_NUT)for(let t of e.nalUnits)s.unshift(t);for(let e of t.arrays)if(e.nalUnitType===ak.SPS_NUT)for(let t of e.nalUnits)s.unshift(t);for(let e of t.arrays)if(e.nalUnitType===ak.VPS_NUT)for(let t of e.nalUnits)s.unshift(t)}return s.unshift("avc"===i?cV:cL),t_(s)}prepareAudioPacket(e,t,i){let r=e.track.source._codec;if("mp3"===r||"ac3"===r||"eac3"===r||"dts"===r)return t.data;if(null===e.inputIsAdts){let t=i?.decoderConfig?.description;if(e.inputIsAdts=!t,!e.inputIsAdts){let i=ej(eq(d(t)));e.adtsHeader=i.header,e.adtsHeaderBitstream=i.bitstream}}if(e.inputIsAdts)return t.data;a(e.adtsHeader),a(e.adtsHeaderBitstream);let s=e.adtsHeader,n=t.data.byteLength+s.byteLength;eQ(e.adtsHeaderBitstream,n);let o=new Uint8Array(n);return o.set(s,0),o.set(t.data,s.byteLength),o}allTracksAreKnown(){for(let e of this.output.tracks)if(!e.source._closed&&!this.trackDatas.some(t=>t.track===e))return!1;return!0}async flushTimestampQueue(e,t=!0){if(0===e.timestampProcessingQueue.length)return;let i=e.timestampProcessingQueue.map(e=>e.presentationTimestamp).sort((e,t)=>
3e-t);for(let t=0;t<e.timestampProcessingQueue.length;t++){let r=e.timestampProcessingQueue[t];r.decodeTimestamp=i[t],e.packetQueue.push(r)}e.timestampProcessingQueue.length=0,t&&await this.interleavePackets()}async interleavePackets(e=!1){if(!this.tablesWritten){if(!this.allTracksAreKnown()&&!e)return;this.writeTables()}t:for(;;){let t=null,i=1/0;for(let r of this.trackDatas){if(!e&&0===r.packetQueue.length&&!r.closed)break t;r.packetQueue.length>0&&r.packetQueue[0].presentationTimestamp<i&&(t=r,i=r.packetQueue[0].presentationTimestamp)}if(!t)break;let r=t.packetQueue.shift();this.writePesPacket(t,r)}e||await this.writer.flush()}writeTables(){a(!this.tablesWritten),this.writePsiSection(0,cQ),this.writePsiSection(4096,c$(this.trackDatas)),this.tablesWritten=!0}writePsiSection(e,t){let i=0,r=!0;for(;i<t.length;){let a,s=Math.min(184-!!r,t.length-i);r?((a=this.payloadBuffer.subarray(0,1+s))[0]=0,a.set(t.subarray(i,i+s),1)):a=t.subarray(i,i+s),this.writeTsPacket(e,r,null,a),i+=s,r=!1}}writePesPacket(e,t){let i="video"===e.track.type,r=i?10:5,s=new Uint8Array(9+r),n=u(s),o=new eW(s.subarray(9));U(n,0,1,!1),s[3]=e.streamId;let l="video"===e.track.type?0:Math.min(8+t.data.length,65535);n.setUint16(4,l,!1),n.setUint8(6,132),n.setUint8(7,i?192:128),n.setUint8(8,r);let c=Math.round(9e4*t.presentationTimestamp);if(o.pos=0,o.writeBits(4,i?3:2),o.writeBits(3,c>>>30&7),o.writeBits(1,1),o.writeBits(15,c>>>15&32767),o.writeBits(1,1),o.writeBits(15,32767&c),o.writeBits(1,1),i){a(null!==t.decodeTimestamp);let e=Math.round(9e4*t.decodeTimestamp);o.writeBits(4,1),o.writeBits(3,e>>>30&7),o.writeBits(1,1),o.writeBits(15,e>>>15&32767),o.writeBits(1,1),o.writeBits(15,32767&e),o.writeBits(1,1)}let d=s.length+t.data.length,h=0,m=!0;for(;h<d;){let i,r=m,a=d-h,n=m&&t.isKeyframe,o=m&&!e.firstPacketWritten,l=Math.max(0,184-a),c=null;if((i=n||o?Math.max(2,l):l)>0){let e=this.adaptationFieldBuffer;1===i?e[0]=0:(e[0]=i-1,e[1]=Number(o)<<7|Number(n)<<6,e.fill(255,2,i)),c=e.subarray(0,i)}let u=Math.min(184-i,a),f=this.payloadBuffer.subarray(0,u),p=0;if(h<s.length){let e=Math.min(s.length-h,u);f.set(s.subarray(h,h+e),0),p=e}let g=Math.max(0,h-s.length),k=g+(u-p);p<u&&f.set(t.data.subarray(g,k),p),this.writeTsPacket(e.pid,r,c,f),h+=u,m=!1}e.firstPacketWritten=!0}writeTsPacket(e,t,i,r){let a=this.continuityCounters.get(e)??0,s=r.length>0,n=i?s?3:2:+!!s;this.packetBuffer[0]=71,this.packetView.setUint16(1,16384*!!t|8191&e,!1),this.packetBuffer[3]=n<<4|15&a,s&&this.continuityCounters.set(e,a+1&15);let o=4;i&&(this.packetBuffer.set(i,o),o+=i.length),this.packetBuffer.set(r,o),(o+=r.length)<188&&this.packetBuffer.fill(255,o);let l=this.writer.getPos();this.writer.write(this.packetBuffer),this.format._options.onPacket&&this.format._options.onPacket(this.packetBuffer.slice(),l)}async onTrackClose(e){let t=await this.mutex.acquire(),i=this.trackDatas.find(t=>t.track===e);i&&(i.closed=!0,await this.flushTimestampQueue(i,!1)),this.allTracksAreKnown()&&this.allTracksKnown.resolve(),await this.interleavePackets(),t()}async finalize(){let e=await this.mutex.acquire();for(let e of(this.allTracksKnown.resolve(),this.trackDatas))e.closed=!0,await this.flushTimestampQueue(e,!1);await this.interleavePackets(!0),e()}}let cH=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;cH[e]=t>>>0}let cj=e=>{let t=0xffffffff;for(let i=0;i<e.length;i++)t=(t<<8^cH[t>>>24^e[i]])>>>0;return t},cQ=new Uint8Array(16);{let e=u(cQ);cQ[0]=0,e.setUint16(1,45069,!1),e.setUint16(3,1,!1),cQ[5]=193,cQ[6]=0,cQ[7]=0,e.setUint16(8,1,!1),e.setUint16(10,61440,!1),e.setUint32(12,cj(cQ.subarray(0,12)),!1)}let c$=e=>{let t=0;for(let i of e)t+=5,129===i.streamType?t+=t8.length:135===i.streamType&&(t+=t6.length);let i=9+t+4,r=new Uint8Array(3+i-4),a=u(r);r[0]=2,a.setUint16(1,45056|4095&i,!1),a.setUint16(3,1,!1),r[5]=193,r[6]=0,r[7]=0,a.setUint16(8,65535,!1),a.setUint16(10,61440,!1);let s=12;for(let t of e)r[s++]=t.streamType,a.setUint16(s,57344|8191&t.pid,!1),s+=2,129===t.streamType?(a.setUint16(s,61440|t8.length,!1),s+=2,r.set(t8,s),s+=t8.length):135===t.streamType?(a.setUint16(s,61440|t6.length,!1),s+=2,r.set(t6,s),s+=t6.length):(a.setUint16(s,61440,!1),s+=2);let n=cj(r),o=new Uint8Array(r.length+4);return o.set(r,0),u(o).setUint32(r.length,n,!1),o};class cK{constructor(e){this.writer=e,this.helper=new Uint8Array(8),this.helperView=new DataView(this.helper.buffer)}writeU16(e){this.helperView.setUint16(0,e,!0),this.writer.write(this.helper.subarray(0,2))}writeU32(e){this.helperView.setUint32(0,e,!0),this.writer.write(this.helper.subarray(0,4))}writeU64(e){this.helperView.setUint32(0,e,!0),this.helperView.setUint32(4,Math.floor(e/0x100000000),!0),this.writer.write(this.helper)}writeAscii(e){this.writer.write(new TextEncoder().encode(e))}}class cX extends oj{constructor(e,t){super(e),this.headerWritten=!1,this.dataSize=0,this.sampleRate=null,this.sampleCount=0,this.riffSizePos=null,this.dataSizePos=null,this.ds64RiffSizePos=null,this.ds64DataSizePos=null,this.ds64SampleCountPos=null,this.format=t,this.isRf64=!!t._options.large}async start(){let e=await this.mutex.acquire();this.writer=await this.output._getRootWriter(!1),this.riffWriter=new cK(this.writer);let t=this.output.tracks[0];a(t?.isAudioTrack()),t.metadata.decoderConfig&&(th({decoderConfig:t.metadata.decoderConfig},t.source._codec),this.writeHeader(t,t.metadata.decoderConfig),this.sampleRate=t.metadata.decoderConfig.sampleRate,this.headerWritten=!0),e()}async getMimeType(){return"audio/wav"}async addEncodedVideoPacket(){throw Error("WAVE does not support video.")}async addEncodedAudioPacket(e,t,i){let r=await this.mutex.acquire();try{if(this.headerWritten||(th(i,e.source._codec),a(i),a(i.decoderConfig),this.writeHeader(e,i.decoderConfig),this.sampleRate=i.decoderConfig.sampleRate,this.headerWritten=!0),this.validateTimestamp(e,t.timestamp,"key"===t.type),!this.isRf64&&this.writer.getPos()+t.data.byteLength>=0x100000000)throw Error("Adding more audio data would exceed the maximum RIFF size of 4 GiB. To write larger files, use RF64 by setting `large: true` in the WavOutputFormatOptions.");this.writer.write(t.data),this.dataSize+=t.data.byteLength,this.sampleCount+=Math.round(t.duration*this.sampleRate),await this.writer.flush()}finally{r()}}async addSubtitleCue(){throw Error("WAVE does not support subtitles.")}writeHeader(e,t){let i;this.format._options.onHeader&&this.writer.startTrackingWrites();let r=tr(e.source._codec);i="ulaw"===r.dataType?av.MULAW:"alaw"===r.dataType?av.ALAW:"float"===r.dataType?av.IEEE_FLOAT:av.PCM;let a=t.numberOfChannels,s=t.sampleRate,n=r.sampleSize*a;if(this.riffWriter.writeAscii(this.isRf64?"RF64":"RIFF"),this.isRf64?this.riffWriter.writeU32(0xffffffff):(this.riffSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("WAVE"),this.isRf64&&(this.riffWriter.writeAscii("ds64"),this.riffWriter.writeU32(28),this.ds64RiffSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64DataSizePos=this.writer.getPos(),this.riffWriter.writeU64(0),this.ds64SampleCountPos=this.writer.getPos(),this.riffWriter.writeU64(0),this.riffWriter.writeU32(0)),this.riffWriter.writeAscii("fmt "),this.riffWriter.writeU32(16),this.riffWriter.writeU16(i),this.riffWriter.writeU16(a),this.riffWriter.writeU32(s),this.riffWriter.writeU32(s*n),this.riffWriter.writeU16(n),this.riffWriter.writeU16(8*r.sampleSize),!eU(this.output._metadataTags)){let e=this.format._options.metadataFormat??"info";"info"===e?this.writeInfoChunk(this.output._metadataTags):"id3"===e?this.writeId3Chunk(this.output._metadataTags):z(e)}if(this.riffWriter.writeAscii("data"),this.isRf64?this.riffWriter.writeU32(0xffffffff):(this.dataSizePos=this.writer.getPos(),this.riffWriter.writeU32(0)),this.format._options.onHeader){let{data:e,start:t}=this.writer.stopTrackingWrites();this.format._options.onHeader(e,t)}}writeInfoChunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii("LIST"),this.riffWriter.writeU32(0),this.riffWriter.writeAscii("INFO");let i=new Set,r=(e,t)=>{if(!f(t))return void eR._warn(`Didn't write tag '${e}' because '${t}' is not ISO 8859-1-compatible.`);let r=t.length+1,a=new Uint8Array(r);for(let e=0;e<t.length;e++)a[e]=t.charCodeAt(e);this.riffWriter.writeAscii(e),this.riffWriter.writeU32(r),this.writer.write(a),1&r&&this.writer.write(new Uint8Array(1)),i.add(e)};for(let{key:t,value:a}of ed(e))switch(t){case"title":r("INAM",a),i.add("INAM");break;case"artist":r("IART",a),i.add("IART");break;case"album":r("IPRD",a),i.add("IPRD");break;case"trackNumber":r("ITRK",void 0!==e.tracksTotal?`${a}/${e.tracksTotal}`:a.toString()),i.add("ITRK");break;case"genre":r("IGNR",a),i.add("IGNR");break;case"date":r("ICRD",a.toISOString().slice(0,10)),i.add("ICRD");break;case"comment":r("ICMT",a),i.add("ICMT");break;case"albumArtist":case"discNumber":case"tracksTotal":case"discsTotal":case"description":case"lyrics":case"images":case"raw":break;default:z(t)}if(e.raw)for(let t in e.raw){let a=e.raw[t];null==a||4!==t.length||i.has(t)||"string"==typeof a&&r(t,a)}let a=this.writer.getPos(),s=a-t-8;this.writer.seek(t+4),this.riffWriter.writeU32(s),this.writer.seek(a),1&s&&this.writer.write(new Uint8Array(1))}writeId3Chunk(e){let t=this.writer.getPos();this.riffWriter.writeAscii("ID3 "),this.riffWriter.writeU32(0);let i=new oH(this.writer).writeId3V2Tag(e),r=this.writer.getPos();this.writer.seek(t+4),this.riffWriter.writeU32(i),this.writer.seek(r),1&i&&this.writer.write(new Uint8Array(1))}async finalize(){let e=await this.mutex.acquire();if(!this.headerWritten)throw Error("Cannot finalize an empty WAVE file: no packets were added and the track specified no decoderConfig in its metadata, so there's no telling what the file should look like.");let t=this.writer.getPos();this.isRf64?(a(null!==this.ds64RiffSizePos),this.writer.seek(this.ds64RiffSizePos),this.riffWriter.writeU64(t-8),a(null!==this.ds64DataSizePos),this.writer.seek(this.ds64DataSizePos),this.riffWriter.writeU64(this.dataSize),a(null!==this.ds64SampleCountPos),this.writer.seek(this.ds64SampleCountPos),this.riffWriter.writeU64(this.sampleCount)):(a(null!==this.riffSizePos),this.writer.seek(this.riffSizePos),this.riffWriter.writeU32(t-8),a(null!==this.dataSizePos),this.writer.seek(this.dataSizePos),this.riffWriter.writeU32(this.dataSize)),e()}}class cG{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(){a(null!==this.sourceNumberOfChannels);let e=this.sourceNumberOfChannels,t=this.targetNumberOfChannels;1===e&&2===t?this.channelMixer=(t,i)=>t[i*e]:1===e&&4===t?this.channelMixer=(t,i,r)=>t[i*e]*(r<2):1===e&&6===t?this.channelMixer=(t,i,r)=>t[i*e]*(2===r):2===e&&1===t?this.channelMixer=(t,i)=>{let r=i*e;return .5*(t[r]+t[r+1])}:2===e&&4===t?this.channelMixer=(t,i,r)=>t[i*e+r]*(r<2):2===e&&6===t?this.channelMixer=(t,i,r)=>t[i*e+r]*(r<2):4===e&&1===t?this.channelMixer=(t,i)=>{let r=i*e;return .25*(t[r]+t[r+1]+t[r+2]+t[r+3])}:4===e&&2===t?this.channelMixer=(t,i,r)=>{let a=i*e;return .5*(t[a+r]+t[a+r+2])}:4===e&&6===t?this.channelMixer=(t,i,r)=>{let a=i*e;return r<2?t[a+r]:2===r||3===r?0:t[a+r-2]}:6===e&&1===t?this.channelMixer=(t,i)=>{let r=i*e;return Math.SQRT1_2*(t[r]+t[r+1])+t[r+2]+.5*(t[r+4]+t[r+5])}:6===e&&2===t?this.channelMixer=(t,i,r)=>{let a=i*e;return t[a+r]+Math.SQRT1_2*(t[a+2]+t[a+r+4])}:6===e&&4===t?this.channelMixer=(t,i,r)=>{let a=i*e;return r<2?t[a+r]+Math.SQRT1_2*t[a+2]:t[a+r+2]}:this.channelMixer=(t,i,r)=>r<e?t[i*e+r]:0}ensureTempBufferSize(e){let t=this.tempSourceBuffer.length;for(;t<e;)t*=2;if(t!==this.tempSourceBuffer.length){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()),a(null!==this.startTime);let t=e.numberOfFrames*e.numberOfChannels;this.ensureTempBufferSize(t);let i=e.allocationSize({planeIndex:0,format:"f32"}),r=new Float32Array(this.tempSourceBuffer.buffer,0,i/4);e.copyTo(r,{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 i=t-this.bufferStartFrame;a(i<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 a=0,s=0;o>=0&&o<e.numberOfFrames&&(a=this.channelMixer(r,o,t)),l>=0&&l<e.numberOfFrames&&(s=this.channelMixer(r,l,t));let n=a+c*(s-a),d=i*this.targetNumberOfChannels+t;this.outputBuffer[d]+=n}null===this.maxWrittenFrame?this.maxWrittenFrame=i:this.maxWrittenFrame=Math.max(this.maxWrittenFrame,i)}}async finalizeCurrentBuffer(){if(null===this.maxWrittenFrame)return;a(null!==this.startTime);let e=(this.maxWrittenFrame+1)*this.targetNumberOfChannels,t=new Float32Array(e);t.set(this.outputBuffer.subarray(0,e));let i=new s8({format:"f32",sampleRate:this.targetSampleRate,numberOfChannels:this.targetNumberOfChannels,timestamp:this.startTime+this.bufferStartFrame/this.targetSampleRate,data:t});await this.onSample(i),this.outputBuffer.fill(0),this.maxWrittenFrame=null}finalize(){return this.finalizeCurrentBuffer()}}var cY=function(e,t,i){if(null!=t){var r,a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");
3if(i){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!=typeof r)throw TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},cJ=(ah="function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r},function(e){function t(t){e.error=e.hasError?new ah(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var i,r=0;return function a(){for(;i=e.stack.pop();)try{if(!i.async&&1===r)return r=0,e.stack.push(i),Promise.resolve().then(a);if(i.dispose){var s=i.dispose.call(i.value);if(i.async)return r|=2,Promise.resolve(s).then(a,function(e){return t(e),a()})}else r|=1}catch(e){t(e)}if(1===r)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()});class cZ{constructor(){this._connectedTrack=null,this._closingPromise=null,this._closed=!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 c0 extends cZ{constructor(e){if(super(),this._connectedTrack=null,!e$.includes(e))throw TypeError(`Invalid video codec '${e}'. Must be one of: ${e$.join(", ")}.`);this._codec=e}}let c1=(e,t)=>{if(e.metadata.hasOnlyKeyPackets&&"key"!==t.type)throw Error("Cannot add non-key packets to a hasOnlyKeyPackets video track.")};class c2 extends c0{constructor(e){super(e)}add(e,t){if(!(e instanceof ik))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(),c1(this._connectedTrack,e),this._connectedTrack.output._muxer.addEncodedVideoPacket(this._connectedTrack,e,t)}}class c3{setError(e){this.errorSet||(this.error=e,this.errorSet=!0)}constructor(e,t){this.source=e,this.encodingConfig=t,this.ensureEncoderPromise=null,this.encoderInitialized=!1,this.encoder=null,this.muxer=null,this.lastMultipleOfKeyFrameInterval=-1,this.emittedEncoderPackets=0,this.codedWidth=null,this.co
3dedHeight=null,this.outputWidth=null,this.outputHeight=null,this.frameRateLastSample=null,this.frameRateLastTimestamp=null,this.frameRateLastEndTimestamp=null,this.preciseTimings=[],this.customEncoder=null,this.customEncoderCallSerializer=new Z,this.customEncoderQueueSize=0,this.defaultEncodeOptions={},this.alphaEncoder=null,this.splitter=null,this.splitterCreationFailed=!1,this.alphaFrameQueue=[],this.error=null,this.errorSet=!1,this.lastMuxerPromise=Promise.resolve(),this.closed=!1}async add(e,t,i){let r=e;try{this.checkForEncoderError(),this.source._ensureValidAdd();let s=this.encodingConfig,n=s.sizeChangeBehavior??"deny",o=!1;if(null!==this.codedWidth&&null!==this.codedHeight){if((e.codedWidth!==this.codedWidth||e.codedHeight!==this.codedHeight)&&(o=!0,"deny"===n))throw Error(`Video sample size must remain constant. Expected ${this.codedWidth}x${this.codedHeight}, got ${e.codedWidth}x${e.codedHeight}. To allow the sample size to change over time, set \`sizeChangeBehavior\` to a value other than 'deny' in the encoding options.`)}else this.codedWidth=e.codedWidth,this.codedHeight=e.codedHeight;if(s.transform?.width!==void 0||s.transform?.height!==void 0||s.transform?.rotate!==void 0||s.transform?.crop!==void 0||s.transform?.force===!0||o&&"passThrough"!==n){let i=s.transform?.width,r=s.transform?.height,l=s.transform?.fit??"fill";o&&"passThrough"!==n&&(a(this.outputWidth),a(this.outputHeight),a("deny"!==n),i=this.outputWidth,r=this.outputHeight,l=n);let c=await e.transform({width:i,height:r,roundDimensionsTo:2,crop:s.transform?.crop,rotate:s.transform?.rotate,fit:l,alpha:s.alpha});(null===this.outputWidth||null===this.outputHeight)&&(this.outputWidth=c.displayWidth,this.outputHeight=c.displayHeight),t&&e.close(),e=c,t=!0}else(null===this.outputWidth||null===this.outputHeight)&&(this.outputWidth=e.codedWidth,this.outputHeight=e.codedHeight);let l=s.transform?.frameRate;if(void 0!==l){let a=e.timestamp+e.duration,s=j(e.timestamp,l);if(null!==this.frameRateLastSample)if(s<=this.frameRateLastTimestamp){this.frameRateLastSample.close(),this.frameRateLastSample=e.clone(),this.frameRateLastEndTimestamp=a;return}else await this.padFrameRate(s,i);e===r&&(e=e.clone(),t=!0),e.setTimestamp(s),e.setDuration(1/l),this.frameRateLastSample?.close(),this.frameRateLastSample=e.clone(),this.frameRateLastTimestamp=s,this.frameRateLastEndTimestamp=a}await this.processAndEncode(e,i)}finally{t&&e.close()}}async processAndEncode(e,t){let i,r=this.encodingConfig;if(r.transform?.process){let t=r.transform.process(e);if(t instanceof Promise&&(t=await t),null===t)return;Array.isArray(t)||(t=[t]);let a=[];try{for(let i of t)i instanceof sW?a.push(i):"undefined"!=typeof VideoFrame&&i instanceof VideoFrame?a.push(new sW(i)):a.push(new sW(i,{timestamp:e.timestamp,duration:e.duration}))}catch(i){for(let t of a)t!==e&&t.close();for(let i of t)i instanceof sW&&i!==e?i.close():"undefined"!=typeof VideoFrame&&i instanceof VideoFrame&&i.close();throw i}i=a}else i=[e];try{for(let e of i){if(!this.encoderInitialized&&(this.ensureEncoderPromise||this.ensureEncoder(e),this.encoderInitialized||await this.ensureEncoderPromise),a(this.encoderInitialized),this.closed)break;let i=this.encodingConfig.keyFrameInterval??2,r=Math.floor(e.timestamp/i),s={...this.defaultEncodeOptions,...e.encodeOptions,...t},n={...s,keyFrame:void 0!==s.keyFrame?s.keyFrame:0===i||r!==this.lastMultipleOfKeyFrameInterval};if(this.lastMultipleOfKeyFrameInterval=r,this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t,n)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await i}else{a(this.encoder);let t=e.toVideoFrame(),i=_(this.preciseTimings,t.timestamp,e=>e.microsecondTimestamp),r=-1!==i?this.preciseTimings[i]:null;if(r&&r.microsecondTimestamp===t.timestamp?(r.timestamp!==e.timestamp&&(r.timestampIsValid=!1),r.duration!==e.duration&&(r.durationIsValid=!1)):(this.preciseTimings.splice(i+1,0,{microsecondTimestamp:t.timestamp,timestamp:e.timestamp,duration:e.duration,timestampIsValid:!0,durationIsValid:!0}),this.preciseTimings.length>128&&this.preciseTimings.shift()),this.alphaEncoder)if(t.format&&!t.format.includes("A")||this.splitterCreationFailed){this.alphaFrameQueue.push(null);try{this.encoder.encode(t,n)}finally{t.close()}}else{this.splitter||(this.splitter=new c8);let{colorFrame:e,alphaFrame:i}=await this.splitter.split(t);this.alphaFrameQueue.push(i);try{this.encoder.encode(e,n)}finally{e.close()}}else try{this.encoder.encode(t,n)}finally{t.close()}this.encoder.encodeQueueSize>=4&&await new Promise(e=>this.encoder.addEventListener("dequeue",e,{once:!0}))}await this.lastMuxerPromise}}finally{for(let t of i)t!==e&&t.close()}}async padFrameRate(e,t){let i=this.encodingConfig.transform.frameRate;a(this.frameRateLastSample);let r=Math.round((e-this.frameRateLastTimestamp)*i);for(let e=1;e<r;e++){let r={stack:[],error:void 0,hasError:!1};try{let a=cY(r,this.frameRateLastSample.clone(),!1);a.setTimestamp(this.frameRateLastTimestamp+e/i),a.setDuration(1/i),await this.processAndEncode(a,t)}catch(e){r.error=e,r.hasError=!0}finally{cJ(r)}}}ensureEncoder(e){this.ensureEncoderPromise=(async()=>{let t,i=nv(this.encodingConfig.quality,this.encodingConfig.bitrate);a(void 0!==i);let r=nn({...this.encodingConfig,quality:i,width:e.codedWidth,height:e.codedHeight,squarePixelWidth:e.squarePixelWidth,squarePixelHeight:e.squarePixelHeight,framerate:this.source._connectedTrack?.metadata.frameRate}),s=null;for(let e of r){let i=e.config;if(this.encodingConfig.onEncoderConfig?.(i),t=nN.find(e=>e.supports(this.encodingConfig.codec,i))){s=e;break}if("undefined"!=typeof VideoEncoder){if(i.alpha="discard","keep"===this.encodingConfig.alpha&&(i.latencyMode="quality"),(i.width%2==1||i.height%2==1)&&("avc"===this.encodingConfig.codec||"hevc"===this.encodingConfig.codec))throw Error(`The dimensions ${i.width}x${i.height} are not supported for codec '${this.encodingConfig.codec}'; both width and height must be even numbers. Make sure to round your dimensions to the nearest even number.`);try{if((await VideoEncoder.isConfigSupported(i)).supported){s=e;break}}catch{}}}if(!s){if("undefined"==typeof VideoEncoder)throw Error("VideoEncoder is not supported by this browser.");let e=r[0].config,t=r.map(({config:e,quantizer:t})=>null!==t?`quantizer ${t}`:`${e.bitrate} bps`);throw Error(`This specific encoder configuration (${e.codec}, ${t.join(" / ")}, ${e.width}x${e.height}, hardware acceleration: ${e.hardwareAcceleration??"no-preference"}) is not supported by this browser. Consider using another codec or changing your video parameters.`)}let n=s.config;if(null!==s.quantizer&&(this.defaultEncodeOptions=np(this.encodingConfig.codec,s.quantizer)),t)this.customEncoder=new t,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=n,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof ik))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.");c1(this.source._connectedTrack,e),this.encodingConfig.onEncodedPacket?.(e,t),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,e,t).catch(e=>{this.setError(e)})},this.customEncoder.onError=e=>{this.setError(e)},await this.customEncoder.init();else{let e=[],t=[],i=0,r=0,s=(e,t,i)=>{let r={};if(t){let e=new Uint8Array(t.byteLength);t.copyTo(e),r.alpha=e}
3let a=ik.fromEncodedChunk(e,r),s=_(this.preciseTimings,e.timestamp,e=>e.microsecondTimestamp),n=-1!==s?this.preciseTimings[s]:null,o=null;0===this.emittedEncoderPackets&&"delta"===a.type&&i?.decoderConfig&&(o=tZ(this.encodingConfig.codec,i.decoderConfig,a.data)),(n&&n.microsecondTimestamp===e.timestamp||null!==o)&&(a=a.clone({timestamp:n?.timestampIsValid?n.timestamp:void 0,duration:n?.durationIsValid?n.duration:void 0,type:o??void 0})),c1(this.source._connectedTrack,a),this.encodingConfig.onEncodedPacket?.(a,i),this.lastMuxerPromise=this.muxer.addEncodedVideoPacket(this.source._connectedTrack,a,i).catch(e=>{this.setError(e)}),this.emittedEncoderPackets++},o=Error("Encoding error").stack;if(this.encoder=new VideoEncoder({output:(n,o)=>{if(!this.alphaEncoder)return void s(n,null,o);let l=this.alphaFrameQueue.shift();a(void 0!==l),l?(this.alphaEncoder.encode(l,{...this.defaultEncodeOptions,keyFrame:"key"===n.type}),r++,l.close(),e.push({chunk:n,meta:o})):0===r?s(n,null,o):(t.push(i+r),e.push({chunk:n,meta:o}))},error:e=>{e.stack=o,this.setError(e)}}),this.encoder.configure(n),"keep"===this.encodingConfig.alpha){let o=Error("Encoding error").stack;this.alphaEncoder=new VideoEncoder({output:(n,o)=>{r--;let l=e.shift();for(a(void 0!==l),s(l.chunk,n,l.meta),i++;t.length>0&&t[0]===i;){t.shift();let i=e.shift();a(void 0!==i),s(i.chunk,null,i.meta)}},error:e=>{e.stack=o,this.setError(e)}}),this.alphaEncoder.configure(n)}}a(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}async flushAndClose(e){try{if(!e&&(this.checkForEncoderError(),this.frameRateLastSample)){let e=this.encodingConfig.transform.frameRate,t=j(this.frameRateLastEndTimestamp,e);await this.padFrameRate(t)}this.closed=!0,!e&&(this.customEncoder?this.customEncoderCallSerializer.call(()=>this.customEncoder.flush()):this.encoder&&(await this.encoder.flush(),await this.alphaEncoder?.flush(),await eE(25)))}finally{this.closed=!0,this.frameRateLastSample?.close(),this.frameRateLastSample=null,this.customEncoder?await this.customEncoderCallSerializer.call(()=>this.customEncoder.close()).catch(e=>this.setError(e)):this.encoder&&("closed"!==this.encoder.state&&this.encoder.close(),this.alphaEncoder&&"closed"!==this.alphaEncoder.state&&this.alphaEncoder.close(),this.alphaFrameQueue.forEach(e=>e?.close()),this.alphaFrameQueue.length=0,this.splitter?.close())}e||this.checkForEncoderError()}getQueueSize(){return this.customEncoder?this.customEncoderQueueSize:this.encoder?.encodeQueueSize??0}checkForEncoderError(){if(this.errorSet)throw this.error}}let c4=null;class c8{constructor(){this.worker=null,this.pendingRequests=new Map,this.nextRequestId=0}split(e){if(!this.worker){if(!c4){let e=new Blob([`(${c6.toString()})()`],{type:"application/javascript"});c4=URL.createObjectURL(e)}this.worker=new Worker(c4),this.worker.addEventListener("message",e=>{let t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(Error(t.error)):i.resolve({colorFrame:t.colorFrame,alphaFrame:t.alphaFrame}))}),this.worker.addEventListener("error",e=>{let t=Error(e.message||"Color/alpha splitter worker error.");for(let e of this.pendingRequests.values())e.reject(t);this.pendingRequests.clear()})}let t=this.nextRequestId++,i=B();return this.pendingRequests.set(t,i),this.worker.postMessage({id:t,sourceFrame:e},{transfer:[e]}),i.promise}close(){this.worker?.terminate(),this.worker=null;let e=Error("Color/alpha splitter closed.");for(let t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}let c6=()=>{let e=null,t=Promise.resolve();self.addEventListener("message",e=>{let{id:r,sourceFrame:a}=e.data;t=t.then(async()=>{try{let{colorFrame:e,alphaFrame:t}=await i(a);self.postMessage({id:r,colorFrame:e,alphaFrame:t},{transfer:[e,t]})}catch(e){self.postMessage({id:r,error:e.message})}finally{a.close()}})});let i=async t=>{let i=t.format;if(!i)throw Error("CPU color/alpha splitting requires a known VideoFrame format.");let s=t.allocationSize();if(e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e),"RGBA"===i||"BGRA"===i)return r(e,i,t);if("I420A"===i||"I420AP10"===i||"I420AP12"===i||"I422A"===i||"I422AP10"===i||"I422AP12"===i||"I444A"===i||"I444AP10"===i||"I444AP12"===i)return a(e,i,t);throw Error(`CPU color/alpha splitting does not support format '${i}'.`)},r=(e,t,i)=>
3{let r=i.visibleRect?.width??i.codedWidth,a=i.visibleRect?.height??i.codedHeight,s=r*a,n=new Uint8Array(s+Math.ceil(r/2)*Math.ceil(a/2)*2);for(let t=0,i=3;t<s;t++,i+=4)n[t]=e[i];n.fill(128,s);let o=new VideoFrame(e,{format:"RGBA"===t?"RGBX":"BGRX",codedWidth:r,codedHeight:a,timestamp:i.timestamp,duration:i.duration??void 0}),l={format:"I420",codedWidth:r,codedHeight:a,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[n.buffer]};return{colorFrame:o,alphaFrame:new VideoFrame(n,l)}},a=(e,t,i)=>{let r,a,s=i.visibleRect?.width??i.codedWidth,n=i.visibleRect?.height??i.codedHeight,o=t.includes("P10"),l=t.includes("P12"),c=o||l?2:1;t.startsWith("I420")?(r=Math.ceil(s/2),a=Math.ceil(n/2)):(r=t.startsWith("I422")?Math.ceil(s/2):s,a=n);let d=s*n,u=d*c,h=d*c+r*a*c*2,m=t.replace("A",""),f=Math.ceil(s/2)*Math.ceil(n/2),p=new Uint8Array(u+f*c*2);p.set(e.subarray(h,h+u),0);let g=o?512:l?2048:128;1===c?p.fill(g,u):new Uint16Array(p.buffer,u,2*f).fill(g);let k=new VideoFrame(e.subarray(0,h),{format:m,codedWidth:s,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0}),y={format:o?"I420P10":l?"I420P12":"I420",codedWidth:s,codedHeight:n,timestamp:i.timestamp,duration:i.duration??void 0,transfer:[p.buffer]};return{colorFrame:k,alphaFrame:new VideoFrame(p,y)}}};class c5 extends c0{constructor(e){na(e),super(e.codec),this._encoder=new c3(this,e)}add(e,t){if(!(e instanceof sW))throw TypeError("videoSample must be a VideoSample.");return this._encoder.add(e,!1,t)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class c7 extends c0{constructor(e,t){if(!("undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement)&&!("undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw TypeError("canvas must be an HTMLCanvasElement or OffscreenCanvas.");na(t),super(t.codec),this._encoder=new c3(this,t),this._canvas=e}add(e,t=0,i){if(!Number.isFinite(e)||e<0)throw TypeError("timestamp must be a non-negative number.");if(!Number.isFinite(t)||t<0)throw TypeError("duration must be a non-negative number.");let r=new sW(this._canvas,{timestamp:e,duration:t});return this._encoder.add(r,!0,i)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class c9 extends c0{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||"video"!==e.kind)throw TypeError("track must be a video MediaStreamTrack.");if(na(t),"object"!=typeof i||!i)throw TypeError("options must be an object.");if(null!=i.frameRate&&("number"!=typeof i.frameRate||i.frameRate<=0))throw TypeError("options.frameRate, when provided, must be either a positive number or null.");if(void 0!==i.timestampBase&&"synced-zero"!==i.timestampBase&&"zero"!==i.timestampBase&&"unix"!==i.timestampBase)throw TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super((t={...t,latencyMode:"realtime"}).codec),this._abortController=null,this._workerTrackId=null,this._workerListener=null,this._promiseWithResolvers=B(),this._errorPromiseAccessed=!1,this._paused=!1,this._lastVideoFrame=null,this._timerHandle=null,this._videoElement=null,this._options=i,this._encoder=new c3(this,t),this._track=e}async _start(){this._errorPromiseAccessed||eR._warn("Make sure not to ignore the `errorPromise` field on MediaStreamVideoTrackSource, so that any internal errors get bubbled up properly.");let e=void 0!==this._options.frameRate?this._options.frameRate:this._track.getSettings().frameRate??null;this._abortController=new AbortController;let t=null,i=null,r=0,s=!1,n=null,o=0,l=()=>{if(a(null!==e),!this._lastVideoFrame)return;a(null!==i),a(null!==t);let s=performance.now();for(;s-i>1e3/e;){i+=1e3/e;let a=t+r/e;d(new VideoFrame(this._videoElement??this._lastVideoFrame,{timestamp:1e6*a,duration:1e6/e}),s)}};null!==e&&(this._timerHandle=((e,t)=>{if("undefined"==typeof window)return{id:setInterval(e,t)};let i=eA++;return eP.set(i,()=>{e()}),ex().postMessage({type:"set-interval",timerId:i,delay:t}),{id:i}})(l,4));let c=t=>{if(null===e)d(t);else{let e=performance.now();this._lastVideoFrame?(l(),this._lastVideoFrame?.close()):(d(t.clone(),e),i=e),this._lastVideoFrame=t}},d=(e,i=performance.now())=>{if(s)return void e.close();r++;let a=e.timestamp/1e6;if(this._paused){null!==t&&(null!==n&&"unix"!==this._options.timestampBase&&(o-=a-n),n=a),e.close();return}if(null===t){let e;t=a;let r=this._options.timestampBase??"synced-zero";if("unix"===r)e=Date.now()/1e3;else if("zero"===r)e=0;else{let t=this._connectedTrack.output;null===t._firstMediaStreamTimestamp?(t._firstMediaStreamTimestamp=i/1e3,e=0):e=i/1e3-t._firstMediaStreamTimestamp}o=e-t}if(n=a,this._encoder.getQueueSize()>=8)return void e.close();let l=new sW(e,{timestamp:a+o});this._encoder.add(l,!0).catch(e=>{s=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),null!==this._workerTrackId&&dh({type:"stopTrack",trackId:this._workerTrackId})})};if("undefined"!=typeof MediaStreamTrackProcessor){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:c});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||this._promiseWithResolvers.reject(e)})}else if(await du())this._workerTrackId=dl++,dh({type:"videoTrack",trackId:this._workerTrackId,track:this._track}),this._workerListener=e=>{let t=e.data;"videoFrame"===t.type&&t.trackId===this._workerTrackId?c(t.videoFrame):"error"===t.type&&t.trackId===this._workerTrackId&&this._promiseWithResolvers.reject(t.error)},dc.addEventListener("message",this._workerListener);else if(null!==e){let e=document.createElement("video");
3e.style.position="fixed",e.style.left="-10000px",e.style.top="-10000px",e.style.width="1px",e.style.height="1px",e.style.opacity="0",e.style.pointerEvents="none",e.muted=!0,e.srcObject=new MediaStream([this._track]),document.body.appendChild(e),this._videoElement=e,e.addEventListener("loadeddata",()=>{if(s||!this._videoElement)return;let t=new VideoFrame(e,{timestamp:1e3*performance.now()});c(t),t.close()},{once:!0}),e.play().catch(e=>{s=!0,this._promiseWithResolvers.reject(e)})}else throw Error("When no explicit frame rate is set, MediaStreamTrackProcessor is required; but it's not supported by this browser.")}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._timerHandle&&(e=>{if("undefined"==typeof window)return clearInterval(e.id);a("number"==typeof e.id),eP.delete(e.id),ex().postMessage({type:"clear-interval",timerId:e.id})})(this._timerHandle),this._lastVideoFrame?.close(),this._videoElement&&(this._videoElement.srcObject=null,this._videoElement.remove(),this._videoElement=null),null!==this._workerTrackId&&(a(this._workerListener),dh({type:"stopTrack",trackId:this._workerTrackId}),await new Promise(e=>{let t=i=>{let r=i.data;"trackStopped"===r.type&&r.trackId===this._workerTrackId&&(a(this._workerListener),dc.removeEventListener("message",this._workerListener),dc.removeEventListener("message",t),e())};dc.addEventListener("message",t)})),await this._encoder.flushAndClose(e)}}class de extends cZ{constructor(e){if(super(),this._connectedTrack=null,!eG.includes(e))throw TypeError(`Invalid audio codec '${e}'. Must be one of: ${eG.join(", ")}.`);this._codec=e}}class dt extends de{constructor(e){super(e)}add(e,t){if(!(e instanceof ik))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(),this._connectedTrack.output._muxer.addEncodedAudioPacket(this._connectedTrack,e,t)}}class di{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 Z,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 i=this.encodingConfig;i.transform?.numberOfChannels!==void 0||i.transform?.sampleRate!==void 0?(this.resampler||(this.resampler=new cG({targetNumberOfChannels:i.transform.numberOfChannels??e.numberOfChannels,targetSampleRate:i.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 i=this.encodingConfig;if(i.transform?.sampleFormat!==void 0&&(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}})(e.format)!==i.transform.sampleFormat){let r=((e,t)=>{let i=new ArrayBuffer(e.allocationSize({format:t,planeIndex:0}));return e.copyTo(i,{format:t,planeIndex:0}),new s8({data:i,format:t,numberOfChannels:e.numberOfChannels,sampleRate:e.sampleRate,timestamp:e.timestamp,duration:e.duration})})(e,i.transform.sampleFormat);t&&e.close(),e=r,t=!0}if(i.transform?.process)try{let t=i.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 s8))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 s8&&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),a(this.encoderInitialized),this.closed)return;
3{let t=Math.round(e.timestamp*e.sampleRate),i=Math.round((e.timestamp+e.duration)*e.sampleRate);if(null===this.lastEndSampleIndex)this.lastEndSampleIndex=i;else{let i=t-this.lastEndSampleIndex;if(i>=64){let t=new s8({data:new Float32Array(i*e.numberOfChannels),format:"f32-planar",sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels,numberOfFrames:i,timestamp:this.lastEndSampleIndex/e.sampleRate});await this.encodeSample(t,!0)}this.lastEndSampleIndex+=e.numberOfFrames}}if(this.encodingConfig.onEncodedSample?.(e),this.customEncoder){this.customEncoderQueueSize++;let t=e.clone(),i=this.customEncoderCallSerializer.call(()=>this.customEncoder.encode(t)).catch(e=>this.setError(e)).finally(()=>{this.customEncoderQueueSize--,t.close()});this.customEncoderQueueSize>=4&&await i,await this.lastMuxerPromise}else if(this.isPcmEncoder)await this.doPcmEncoding(e,t);else{a(this.encoder);let i=e.toAudioData();this.encoder.encode(i),i.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){a(this.outputSampleSize),a(this.writeOutputValue);let{numberOfChannels:i,numberOfFrames:r,sampleRate:s,timestamp:n}=e,o=[];for(let t=0;t<r;t+=2048){let r=Math.min(2048,e.numberOfFrames-t),a=new DataView(new ArrayBuffer(r*i*this.outputSampleSize));o.push({frameCount:r,view:a})}let l=new Float32Array(e.allocationSize({planeIndex:0,format:"f32-planar"})/Float32Array.BYTES_PER_ELEMENT);for(let t=0;t<i;t++){e.copyTo(l,{planeIndex:t,format:"f32-planar"});for(let e=0;e<o.length;e++){let{frameCount:r,view:a}=o[e];for(let s=0;s<r;s++)this.writeOutputValue(a,(s*i+t)*this.outputSampleSize,l[2048*e+s])}}t&&e.close();let c={decoderConfig:{codec:this.encodingConfig.codec,numberOfChannels:i,sampleRate:s}};for(let e=0;e<o.length;e++){let{frameCount:t,view:i}=o[e],r=i.buffer,a=2048*e,l=new ik(new Uint8Array(r),"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:i}=e,r=nv(this.encodingConfig.quality,this.encodingConfig.bitrate),s=nc({numberOfChannels:t,sampleRate:i,...this.encodingConfig,quality:r});this.encodingConfig.onEncoderConfig?.(s);let o=nW.find(e=>e.supports(this.encodingConfig.codec,s));if(o)this.customEncoder=new o,this.customEncoder.codec=this.encodingConfig.codec,this.customEncoder.config=s,this.customEncoder.onPacket=(e,t)=>{if(!(e instanceof ik))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(eK.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(s)).supported??!1}catch{e=!1}if(!e)throw Error(`This specific encoder configuration (${s.codec}, ${s.bitrate} bps, ${s.numberOfChannels} channels, ${s.sampleRate} Hz) is not supported by this browser. Consider using another codec or changing your audio parameters.`);let t=Error("Encoding error").stack;this.encoder=new AudioEncoder({output:(e,t)=>{if("aac"===this.encodingConfig.codec&&t?.decoderConfig&&(!t.decoderConfig.description||t.decoderConfig.description.byteLength<2||0===eq(d(t.decoderConfig.description)).objectType)){let e=Number(n(s.codec.split(".")));t.decoderConfig.description=eH({objectType:e,numberOfChannels:t.decoderConfig.numberOfChannels,sampleRate:t.decoderConfig.sampleRate})}let i=ik.fromEncodedChunk(e);i=i.clone({timestamp:q(i.timestamp,s.sampleRate),duration:null!=e.duration?q(i.duration,s.sampleRate):void 0}),this.encodingConfig.onEncodedPacket?.(i,t),this.lastMuxerPromise=this.muxer.addEncodedAudioPacket(this.source._connectedTrack,i,t).catch(e=>{this.setError(e)})},error:e=>{e.stack=t,this.setError(e)}}),this.encoder.configure(s)}a(this.source._connectedTrack),this.muxer=this.source._connectedTrack.output._muxer,this.encoderInitialized=!0})()}initPcmEncoder(){this.isPcmEncoder=!0;let{dataType:e,sampleSize:t,littleEndian:i}=tr(this.encodingConfig.codec);switch(this.outputSampleSize=t,t){case 1:"unsigned"===e?this.writeOutputValue=(e,t,i)=>e.setUint8(t,W((i+1)*127.5,0,255)):"signed"===e?this.writeOutputValue=(e,t,i)=>{e.setInt8(t,W(Math.round(128*i),-128,127))}:"ulaw"===e?this.writeOutputValue=(e,t,i)=>{let r=W(Math.floor(32767*i),-32768,32767);e.setUint8(t,(e=>{let t=e,i=4096,r=0,a=12,s=0;for(t<0&&(t=-t,r=128),(t+=33)>8191&&(t=8191);(t&i)!==i&&a>=5;)i>>=1,a--;return s=t>>a-4&15,255&~(r|a-5<<4|s)})(r))}:"alaw"===e?this.writeOutputValue=(e,t,i)=>{let r=W(Math.floor(32767*i),-32768,32767);e.setUint8(t,(e=>{let t=2048,i=0,r=11,a=0,s=e;for(s<0&&(s=-s,i=128),s>4095&&(s=4095);(s&t)!==t&&r>=5;)t>>=1,r--;return a=s>>(4===r?1:r-4)&15,(i|r-4<<4|a)^85})(r))}:a(!1);break;case 2:"unsigned"===e?this.writeOutputValue=(e,t,r)=>e.setUint16(t,W((r+1)*32767.5,0,65535),i):"signed"===e?this.writeOutputValue=(e,t,r)=>e.setInt16(t,W(Math.round(32767*r),-32768,32767),i):a(!1);break;case 3:"unsigned"===e?this.writeOutputValue=(e,t,r)=>U(e,t,W((r+1)*8388607.5,0,0xffffff),i):"signed"===e?this.writeOutputValue=(e,t,r)=>{var a;return a=W(Math.round(8388607*r),-8388608,8388607),void((a=W(a,-8388608,8388607))<0&&(a=a+0x1000000&0xffffff),U(e,t,a,i))}:a(!1);break;case 4:"unsigned"===e?this.writeOutputValue=(e,t,r)=>e.setUint32(t,W((r+1)*2147483647.5,0,0xffffffff),i):"signed"===e?this.writeOutputValue=(e,t,r)=>e.setInt32(t,W(Math.round(0x7fffffff*r),-0x80000000,0x7fffffff),i):"float"===e?this.writeOutputValue=(e,t,r)=>e.setFloat32(t,r,i):a(!1);break;case 8:"float"===e?this.writeOutputValue=(e,t,r)=>e.setFloat64(t,r,i):a(!1);break;default:z(t),a(!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 dr extends de{constructor(e){no(e),super(e.codec),this._encoder=new di(this,e)}add(e){if(!(e instanceof s8))throw TypeError("audioSample must be an AudioSample.");return this._encoder.add(e,!1)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class da extends de{constructor(e){no(e),super(e.codec),this._accumulatedTime=0,this._encoder=new di(this,e)}async add(e){if(!(e instanceof AudioBuffer))throw TypeError("audioBuffer must be an AudioBuffer.");let t=s8._fromAudioBuffer(e,this._accumulatedTime);for(let i of(this._accumulatedTime+=e.duration,t))await this._encoder.add(i,
3!0)}_flushAndClose(e){return this._encoder.flushAndClose(e)}}class ds extends de{get errorPromise(){return this._errorPromiseAccessed=!0,this._promiseWithResolvers.promise}get paused(){return this._paused}constructor(e,t,i={}){if(!(e instanceof MediaStreamTrack)||"audio"!==e.kind)throw TypeError("track must be an audio MediaStreamTrack.");if(no(t),"object"!=typeof i||!i)throw TypeError("options must be an object.");if(void 0!==i.timestampBase&&"synced-zero"!==i.timestampBase&&"zero"!==i.timestampBase&&"unix"!==i.timestampBase)throw TypeError("options.timestampBase, when provided, must be one of 'synced-zero', 'zero', or 'unix'.");super(t.codec),this._abortController=null,this._audioContext=null,this._scriptProcessorNode=null,this._promiseWithResolvers=B(),this._errorPromiseAccessed=!1,this._paused=!1,this._options=i,this._encoder=new di(this,t),this._track=e}async _start(){this._errorPromiseAccessed||eR._warn("Make sure not to ignore the `errorPromise` field on MediaStreamAudioTrackSource, so that any internal errors get bubbled up properly."),this._abortController=new AbortController;let e=null,t=!1,i=null,r=0,a=a=>{if(t)return void a.close();let s=a.timestamp;if(this._paused){null!==e&&(null!==i&&"unix"!==this._options.timestampBase&&(r-=s-i),i=s),a.close();return}if(null===e){let t;e=a.timestamp;let i=this._options.timestampBase??"synced-zero";if("unix"===i)t=Date.now()/1e3;else if("zero"===i)t=0;else{let e=this._connectedTrack.output;null===e._firstMediaStreamTimestamp?(e._firstMediaStreamTimestamp=performance.now()/1e3,t=0):t=performance.now()/1e3-e._firstMediaStreamTimestamp}r=t-e}if(i=s,this._encoder.getQueueSize()>=8)return void a.close();a.setTimestamp(s+r),this._encoder.add(a,!0).catch(e=>{t=!0,this._abortController?.abort(),this._promiseWithResolvers.reject(e),this._audioContext?.suspend()})};if("undefined"!=typeof MediaStreamTrackProcessor){let e=new MediaStreamTrackProcessor({track:this._track}),t=new WritableStream({write:e=>a(new s8(e))});e.readable.pipeTo(t,{signal:this._abortController.signal}).catch(e=>{e instanceof DOMException&&"AbortError"===e.name||this._promiseWithResolvers.reject(e)})}else{let e=window.AudioContext||window.webkitAudioContext;this._audioContext=new e({sampleRate:this._track.getSettings().sampleRate});let t=this._audioContext.createMediaStreamSource(new MediaStream([this._track]));this._scriptProcessorNode=this._audioContext.createScriptProcessor(4096),"suspended"===this._audioContext.state&&await this._audioContext.resume(),t.connect(this._scriptProcessorNode),this._scriptProcessorNode.connect(this._audioContext.destination);let i=0;this._scriptProcessorNode.onaudioprocess=e=>{let t=s8._fromAudioBuffer(e.inputBuffer,i);for(let r of(i+=e.inputBuffer.duration,t))a(r)}}}pause(){this._paused=!0}resume(){this._paused=!1}async _flushAndClose(e){this._abortController&&(this._abortController.abort(),this._abortController=null),this._audioContext&&(a(this._scriptProcessorNode),this._scriptProcessorNode.disconnect(),await this._audioContext.suspend()),await this._encoder.flushAndClose(e)}}let dn=()=>{let e=(e,t)=>{t?self.postMessage(e,{transfer:t}):self.postMessage(e)};e({type:"support",supported:"undefined"!=typeof MediaStreamTrackProcessor});let t=new Map,i=new Map;self.addEventListener("message",r=>{let a=r.data;switch(a.type){case"videoTrack":{i.set(a.trackId,a.track);let r=new MediaStreamTrackProcessor({track:a.track}),s=new WritableStream({write:t=>{if(!i.has(a.trackId))return void t.close();e({type:"videoFrame",trackId:a.trackId,videoFrame:t},[t])}}),n=new AbortController;t.set(a.trackId,n),r.readable.pipeTo(s,{signal:n.signal}).catch(t=>{t instanceof DOMException&&"AbortError"===t.name||e({type:"error",trackId:a.trackId,error:t})})}break;case"stopTrack":{let r=t.get(a.trackId);r&&(r.abort(),t.delete(a.trackId));let s=i.get(a.trackId);s?.stop(),i.delete(a.trackId),e({type:"trackStopped",trackId:a.trackId})}break;default:z(a)}})},dl=0,dc=null,dd=null,du=async()=>null!==dd?dd:(dc||(()=>{let e=new Blob([`(${dn.toString()})()`],{type:"application/javascript"});dc=new Worker(URL.createObjectURL(e))})(),new Promise(e=>{a(dc);let t=i=>{let r=i.data;
3"support"===r.type&&(dd=r.supported,dc.removeEventListener("message",t),e(r.supported))};dc.addEventListener("message",t)})),dh=(e,t)=>{a(dc),t?dc.postMessage(e,t):dc.postMessage(e)};class dm extends cZ{constructor(e){if(super(),this._connectedTrack=null,!eY.includes(e))throw TypeError(`Invalid subtitle codec '${e}'. Must be one of: ${eY.join(", ")}.`);this._codec=e}}class df extends dm{constructor(e){super(e),this._error=null,this._errorSet=!1,this._lastMuxerPromise=Promise.resolve(),this._parser=new oJ({codec:e,output:(e,t)=>{this._lastMuxerPromise=this._connectedTrack.output._muxer.addSubtitleCue(this._connectedTrack,e,t).catch(e=>{this._setError(e)})}})}add(e){if("string"!=typeof e)throw TypeError("text must be a string.");return this._checkForError(),this._ensureValidAdd(),this._parser.parse(e),this._lastMuxerPromise}_setError(e){this._errorSet||(this._error=e,this._errorSet=!0)}_checkForError(){if(this._errorSet)throw this._error}async _flushAndClose(e){e||this._checkForError()}}class dp extends oj{constructor(e,t){if(!(e._target instanceof cI))throw TypeError("HLS outputs require `OutputOptions.target` to be a PathedTarget.");super(e),this.trackDatas=[],this.isRelativeToUnixEpoch=!1,this.numWrittenMasterPlaylists=0,this.playlists=[],this.playlistDeclarations=[],this.format=t,this.targetSegmentDuration=t._options.targetDuration??2,this.singleFilePerPlaylist=t._options.singleFilePerPlaylist??!1,this.isLive=t._options.live??!1,this.maxLiveSegmentCount=t._options.maxLiveSegmentCount??1/0,this.globalTargetDuration=this.targetSegmentDuration,this.getPlaylistPath=t._options.getPlaylistPath??(({n:e})=>`playlist-${e}.m3u8`),this.getSegmentPath=t._options.getSegmentPath??(e=>e.isSingleFile?`segments-${e.playlist.n}${e.format.fileExtension}`:`segment-${e.playlist.n}-${e.n}${e.format.fileExtension}`),this.getInitPath=t._options.getInitPath??(e=>`init-${e.n}${e.segmentFormat.fileExtension}`)}async start(){let e=await this.mutex.acquire(),t=this.output.tracks.some(e=>e.metadata.isRelativeToUnixEpoch),i=this.output.tracks.some(e=>!e.metadata.isRelativeToUnixEpoch);if(t&&i)throw Error("All tracks must agree on `relativeToUnixEpoch`: some tracks are relative to the Unix epoch and some are not.");this.isRelativeToUnixEpoch=t;let r=new Map,s=[],n=!1,o=!1,l=!1;for(let e of this.output.tracks){"video"===e.type&&(n=!0);let t=new Map;for(let i of this.output.tracks){if(e===i||!e.canBePairedWith(i))continue;if(e.type===i.type){o||(eR._warn(`Illegal pairing of two ${e.type} tracks detected, which is not possible in HLS; treating them as unpaired.`),o=!0);continue}if(e.isVideoTrack()&&e.metadata.hasOnlyKeyPackets||i.isVideoTrack()&&i.metadata.hasOnlyKeyPackets){l||(eR._warn("A key-packets-only video track is pairable with another track, which is not possible in HLS; treating them as unpaired."),l=!0);continue}let r=t.get(i.source._codec);r||t.set(i.source._codec,r=[]),r.push(i)}for(let[,i]of t){let t=i.map(e=>e.id).join("-");s.find(e=>e.key===t)||s.push({name:i[0].type+"-"+(s.length+1),key:t,tracks:i,needsEmit:!1,firstNoUri:!1});let a=r.get(e);a||r.set(e,a=[]),a.push(t)}}let c=n?"video":"audio",d=[],u=[],h=[];for(let e of this.output.tracks){let t=r.get(e);if(t){if(a(t.length>0),e.type!==c)continue;for(let i of t){let n=s.find(e=>e.key===i);if(a(n),1===t.length&&1===n.tracks.length){let t=r.get(n.tracks[0]);if(a(void 0!==t),1===t.length){let i=s.find(e=>e.key===t[0]);if(1===i.tracks.length){a(i.tracks[0]===e),d.push({tracks:[e,n.tracks[0]],linkedGroup:null});continue}}}d.push({tracks:[e],linkedGroup:n}),n.needsEmit=!0}}else"video"===e.type?u.push(e):"audio"===e.type&&h.push(e)}let m=({metadata:e})=>{let t="";return t+`${e.languageCode??"und"}-${e.name??""}-${e.disposition?.default??!0}-${e.disposition?.primary??!1}-${e.disposition?.forced??!1}-`};if(u.length>0)if(new Set(u.map(m)).size>1){let e={key:u.map(e=>e.id).join("-"),name:"video-"+(s.length+1),tracks:u,needsEmit:!0,firstNoUri:!0};s.push(e),d.push({tracks:[u[0]],linkedGroup:e})}else for(let e of u)d.push({tracks:[e],linkedGroup:null});if(h.length>0)if(new Set(h.map(m)).size>1){let e={key:h.map(e=>e.id).join("-"),name:"audio-"+(s.length+1),tracks:h,needsEmit:!0,firstNoUri:!0};s.push(e),d.push({tracks:[h[0]],linkedGroup:e})}else for(let e of h)d.push({tracks:[e],linkedGroup:null});let f=e=>{let t=[],i=0,r=0,s=!1,n=null,o=-1/0;for(let a of e)a.isVideoTrack()?(i++,s||=(a.metadata.rotation??0)!==0):a.isAudioTrack()&&r++,t.push(a.source._codec);for(let e of e_(this.format._options.segmentFormat)){let a=e.getSupp
3ortedCodecs(),l=e.getSupportedTrackCounts();if(t.some(e=>!a.includes(e))||i<l.video.min||i>l.video.max||r<l.audio.min||r>l.audio.max)continue;let c=0;s&&e.supportsVideoRotationMetadata&&c++,c>o&&(n=e,o=c)}return a(n),n},p=async e=>{if(e.some(e=>this.playlists.some(t=>t.tracks.includes(e))))throw Error("Internal error: track is already registered in a playlist.");let t=f(e),i=this.playlists.length+1,r=await this.getPlaylistPath({n:i,tracks:e,segmentFormat:t});dg(r);let a={id:this.playlists.length+1,path:r,tracks:e,segmentFormat:t,currentSegmentStartTimestamp:null,currentSegmentStartTimestampIsFixed:!1,nextSegmentId:1,initSegment:null,writtenSegments:[],peakBitrate:null,averageBitrate:null,mediaSequence:0,done:!1,singleFile:null,mutex:new v};return this.playlists.push(a),a};for(let e of s)if(e.needsEmit)for(let t=0;t<e.tracks.length;t++){let i=e.tracks[t],r=this.playlists.find(e=>e.tracks[0].id===i.id);r??=await p([i]),this.playlistDeclarations.push({playlist:r,groupId:e.name,noUri:e.firstNoUri&&0===t,references:[]})}for(let e of d){let t=this.playlists.find(t=>t.tracks[0].id===e.tracks[0].id);t??=await p(e.tracks),this.playlistDeclarations.push({playlist:t,groupId:null,noUri:!1,references:e.linkedGroup?this.playlistDeclarations.filter(t=>t.groupId===e.linkedGroup.name):[]})}for(let e of 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()}async getMimeType(){return r2}allTracksAreKnown(e){for(let t of e.tracks)if(!t.source._closed&&!this.trackDatas.some(e=>e.track===t))return!1;return!0}async onTrackClose(e){let t=this.trackDatas.find(t=>t.track===e);t&&(t.closed=!0);let i=this.playlists.find(t=>t.tracks.includes(e));a(i);let r=await i.mutex.acquire();try{await this.advancePlaylist(i)}finally{r()}}getVideoTrackData(e,t,i){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;td(i,e.source._codec),a(i),a(i?.decoderConfig);let s=this.playlists.filter(t=>t.tracks.includes(e));return a(1===s.length),r={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"video",decoderConfig:i.decoderConfig,primingPacket:t}},this.trackDatas.push(r),r}getAudioTrackData(e,t,i){let r=this.trackDatas.find(t=>t.track===e);if(r)return r;th(i,e.source._codec),a(i),a(i?.decoderConfig);let s=this.playlists.filter(t=>t.tracks.includes(e));return a(1===s.length),r={track:e,packets:[],playlist:s[0],closed:!1,info:{type:"audio",decoderConfig:i.decoderConfig,primingPacket:t}},this.trackDatas.push(r),r}async addEncodedVideoPacket(e,t,i){let r=this.getVideoTrackData(e,t,i),a=r.playlist,s=await a.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,"key"===t.type),r.packets.push(t),null===a.currentSegmentStartTimestamp?a.currentSegmentStartTimestamp=t.timestamp:a.currentSegmentStartTimestampIsFixed||(a.currentSegmentStartTimestamp=Math.min(a.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(a)}finally{s()}}async addEncodedAudioPacket(e,t,i){let r=this.getAudioTrackData(e,t,i),a=r.playlist,s=await a.mutex.acquire();try{this.validateTimestamp(e,t.timestamp,"key"===t.type),r.packets.push(t),null===a.currentSegmentStartTimestamp?a.currentSegmentStartTimestamp=t.timestamp:a.currentSegmentStartTimestampIsFixed||(a.currentSegmentStartTimestamp=Math.min(a.currentSegmentStartTimestamp,t.timestamp)),await this.advancePlaylist(a)}finally{s()}}async addSubtitleCue(e,t,i){throw Error("Unreachable.")}async advancePlaylist(e){if(a(!e.done),!this.allTracksAreKnown(e))return;let t=this.trackDatas.filter(t=>e.tracks.includes(t.track));if(null===e.currentSegmentStartTimestamp){t.every(e=>e.closed)&&await this.onPlaylistDone(e);return}let i=t.find(e=>"video"===e.info.type),r=t.find(e=>"audio"===e.info.type);for(;;){let s,n,o=e.currentSegmentStartTimestamp+this.targetSegmentDuration,l=0,c=0;if(i&&(!i.closed||i.packets.length>0)){let e=i.packets.every(e=>e.timestamp<o),t=null,s=null;if(e){if(!i.closed)return}else for(let e=0;e<i.packets.length;e++){let r=i.packets[e];if(null!==t&&r.timestamp>o)break;e>0&&"key"===r.type&&(t=r,s=e)}if(null!==s){if(l=s,r){let e=r.packets.findIndex(e=>e.timestamp>=t.timestamp);if(-1!==e)c=e;else{if(!r.closed)return;c=r.packets.length}}}else{if(!i.closed)return;l=i.packets.length;let e=eb(i.packets,e=>e.timestamp),t=i.packets[e];if(a(t),r)if(t.timestamp<o){let e=r.packets.findIndex(e=>e.timestamp>=o);if(-1!==e)c=e;else{if(!r.closed)return;c=r.packets.length}}else{let e=r.packets.findIndex(e=>e.timestamp>t.timestamp);if(-1!==e)c=e;else{if(!r.closed)return;c=r.packets.length}}}}else if(r&&(!r.closed||r.packets.length>0))if(r.packets.every(e=>e.timestamp<o))if(!r.closed)return;else c=r.packets.length;else c=Math.max(R(r.packets,e=>e.timestamp<=o),1);if(0===l&&0===c){t.every(e=>e.closed)&&await this.onPlaylistDone(e);return}let d=null;a(this.output._target instanceof cI);let u=this.output._target;if(this.singleFilePerPlaylist)if(null===e.singleFile){let t={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!0,playlist:dw(e)};
vendor: 1,205 bytes, line 3
3dk(s=await this.getSegmentPath(t)),n=ek(ek(u.rootPath,e.path),s);let a=await this.output._getTarget({path:n,isRoot:!1,mimeType:e.segmentFormat.mimeType}),o=null;if(e.segmentFormat._isFragmentedIsobmff()){o={output:new dV({format:e.segmentFormat,target:a}),videoSource:null,audioSource:null,firstMoofPosition:null,currentFileSize:0},a.on("write",({end:e})=>{o.currentFileSize=Math.max(o.currentFileSize,e)});let t=o.output._muxer;t.minimumFragmentDuration=1/0;let s=t.formatOptions.onMoof;t.formatOptions.onMoof=(e,i,r)=>{o.firstMoofPosition=i,s?.(e,i,r),t.formatOptions.onMoof=s},i&&(o.videoSource=new c2(i.track.source._codec),o.output.addVideoTrack(o.videoSource,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),r&&(o.audioSource=new dt(r.track.source._codec),o.output.addAudioTrack(o.audioSource,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0})),await o.output.start()}else a._start();e.singleFile={target:a,path:s,nextOffset:0,info:t,fragmentedIsobmffOutput:o}}else s=e.singleFile.path,n=ek(ek(u.rootPath,e.path),s);else d={n:e.nextSegmentId,format:e.segmentFormat,isSingleFile:!1,playlist:dw(e)}
3,dk(s=await this.getSegmentPath(d)),n=ek(ek(u.rootPath,e.path),s),e.nextSegmentId++;let h=0,m=null,f=-1/0,p=null,g=null,k=null;try{if(e.singleFile?.fragmentedIsobmffOutput?(p=e.singleFile.fragmentedIsobmffOutput.output,g=e.singleFile.fragmentedIsobmffOutput.videoSource,k=e.singleFile.fragmentedIsobmffOutput.audioSource):(p=new dV({format:e.segmentFormat,target:new cI(n,async t=>{let i={...t,isRoot:!1};if(t.isRoot)if(e.singleFile){let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on("write",({end:e})=>h=Math.max(h,e)),t}else{let e=await this.output._getTarget(i);return m=e,e.on("write",({end:e})=>h=Math.max(h,e)),e}return this.output._getTarget(i)}),initTarget:async()=>{if(e.initSegment)return new cE;if(e.singleFile){e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:0,byteOffset:0,info:null};let t=e.singleFile.target.slice(e.singleFile.nextOffset);return t.on("write",({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),t.on("finalized",()=>{e.singleFile.nextOffset=e.initSegment.byteSize}),t}{let t=dw(e),i=await this.getInitPath(t);dy(i),e.initSegment={path:i,duration:0,timestamp:0,byteSize:0,byteOffset:null,info:null};let r=ek(ek(u.rootPath,e.path),i),a=await this.output._getTarget({path:r,isRoot:!1,mimeType:e.segmentFormat.mimeType});return a.on("write",({end:t})=>{e.initSegment.byteSize=Math.max(e.initSegment.byteSize,t)}),a.on("finalized",()=>{this.format._options.onInit?.(a,t)}),a}}}),i&&(g=new c2(i.track.source._codec),p.addVideoTrack(g,{...i.track.metadata,decoderConfig:i.info.decoderConfig,primingPacket:i.info.primingPacket??void 0})),r&&(k=new dt(r.track.source._codec),p.addAudioTrack(k,{...r.track.metadata,decoderConfig:r.info.decoderConfig,primingPacket:r.info.primingPacket??void 0})),await p.start()),i){a(g);let e={decoderConfig:i.info.decoderConfig};for(let t=0;t<l;t++){let r=i.packets[t];await g.add(r,e),f=Math.max(f,r.timestamp+r.duration)}}if(r){a(k);let e={decoderConfig:r.info.decoderConfig};for(let t=0;t<c;t++){let i=r.packets[t];await k.add(i,e),f=Math.max(f,i.timestamp+i.duration)}}if(e.singleFile?.fragmentedIsobmffOutput){let t=e.singleFile.fragmentedIsobmffOutput.output._muxer;await t.forceFragmentFinalization(),null===e.singleFile.fragmentedIsobmffOutput.firstMoofPosition||e.initSegment||(e.initSegment={path:e.singleFile.path,duration:0,timestamp:0,byteSize:e.singleFile.fragmentedIsobmffOutput.firstMoofPosition,byteOffset:0,info:null},e.singleFile.nextOffset=e.singleFile.fragmentedIsobmffOutput.firstMoofPosition),h=e.singleFile.fragmentedIsobmffOutput.currentFileSize-e.singleFile.nextOffset}else await p.finalize()}catch(e){throw await p?.cancel(),e}d&&(a(m),this.format._options.onSegment?.(m,d)),l>0&&(a(i),i.packets.splice(0,l)),c>0&&(a(r),r.packets.splice(0,c));let y=1/0;i&&i.packets.length>0&&(y=i.packets[0].timestamp),r&&r.packets.length>0&&(y=Math.min(y,r.packets[0].timestamp));let w=y<1/0?y:f;a(Number.isFinite(w));let b=w-e.currentSegmentStartTimestamp;if(a(b>=0),e.writtenSegments.push({path:s,duration:b,timestamp:e.currentSegmentStartTimestamp,byteSize:h,byteOffset:e.singleFile?e.singleFile.nextOffset:null,info:d??null}),this.globalTargetDuration=Math.max(this.globalTargetDuration,b),e.currentSegmentStartTimestamp=w,e.currentSegmentStartTimestampIsFixed=!0,e.singleFile&&(e.singleFile.nextOffset+=h),this.isLive){for(;e.writtenSegments.length>this.maxLiveSegmentCount;){let t=e.writtenSegments.shift();e.mediaSequence++,this.singleFilePerPlaylist||(a(t.info),this.format._options.onSegmentPopped?.(t.path,t.info))}await this.writePlaylist(e),await this.tryWriteMasterPlaylist()}}}async onPlaylistDone(e){a(!e.done),e.done=!0,e.singleFile&&(e.singleFile.fragmentedIsobmffOutput?await e.singleFile.fragmentedIsobmffOutput.output.finalize():(await e.singleFile.target._flush(),await e.singleFile.target._finalize()),this.format._options.onSegment?.(e.singleFile.target,e.singleFile.info)),await this.writePlaylist(e),this.isLive&&0===e.writtenSegments.length&&await this.tryWriteMasterPlaylist()}updatePlaylistBitrates(e){let t=e.writtenSegments,i=0,r=0,a=0;for(let e=0;e<t.length;e++){a+=t[e].duration;let r=0,s=0;for(let a=e;a<t.length&&(r+=t[a].byteSize,(s+=t[a].duration)>=.5*this.globalTargetDuration&&s<=1.5*this.globalTargetDuration&&(i=Math.max(i,8*r/s)),!(s>1.5*this.globalTargetDuration));a++);}if(0===i)for(let e of t){let t=e.duration||1;i=Math.max(i,8*e.byteSize/t)}for(let e of t)r+=8*e.byteSize;e.peakBitrate=i,e.averageBitrate=r/(a||1)}async writePlaylist(e){a(this.output._target instanceof cI);let t=this.output._target;this.updatePlaylistBitrates(e);let i=!1;for(let t of e.writtenSegments)i||=null!==t.byteOffset;let r=e.tracks[0].isVideoTrack()&&e.tracks[0].metadata.hasOnlyKeyPackets,s=3;(r||i)&&(s=4),e.initSegment&&(s=5),e.initSegment&&!r&&(s=6);let n=this.isLive?this.targetSegmentDuration:this.globalTargetDuration,o=ek(t.rootPath,e.path),l=`#EXTM3U
4#EXT-X-VERSION:${s}
5`+(this.isLive?"":"#EXT-X-PLAYLIST-TYPE:VOD\n")+`#EXT-X-TARGETDURATION:${Math.ceil(n)}
6`+(Number.isFinite(this.maxLiveSegmentCount)?`#EXT-X-MEDIA-SEQUENCE:${e.mediaSequence}
7`:"")+"#EXT-X-INDEPENDENT-SEGMENTS\n"+(r?"#EXT-X-I-FRAMES-ONLY\n":"")+(e.initSegment?`#EXT-X-MAP:URI="${e.initSegment.path}
7"`+(null!==e.initSegment.byteOffset?`,BYTERANGE="${e.initSegment.byteSize}@${e.initSegment.byteOffset}"`:"")+"\n":"")+"\n"+e.writtenSegments.map(e=>`#EXTINF:${+e.duration.toFixed(12)},
8`+(this.isRelativeToUnixEpoch?`#EXT-X-PROGRAM-DATE-TIME:${new Date(1e3*e.timestamp).toISOString()}
9`:"")+(null!==e.byteOffset?`#EXT-X-BYTERANGE:${e.byteSize}@${e.byteOffset}
10`:"")+`${e.path}
11`).join("")+(e.done?(e.writtenSegments.length>0?"\n":"")+"#EXT-X-ENDLIST\n":"");this.format._options.onPlaylist?.(l,dw(e));let c=new cT(await this.output._getTarget({path:o,isRoot:!1,mimeType:r2}),!0);c.start(),c.write(m.encode(l)),await c.flush(),await c.finalize()}async writeMasterPlaylist(){a(this.output._target instanceof cI);let e=this.output._target,t="#EXTM3U\n",i=!1,r=null,s=0,n=!1;for(let e of this.playlistDeclarations)if(null===e.groupId){let r=e.playlist.tracks[0].isVideoTrack()&&e.playlist.tracks[0].metadata.hasOnlyKeyPackets,s=[];for(let t of e.playlist.tracks){let e=this.trackDatas.find(e=>e.track===t),i=e?.info.decoderConfig.codec??t.source._codec;s.push(i)}let n=0,o=0;if(e.references.length>0){let t=e.references[0].playlist.tracks[0],i=this.trackDatas.find(e=>e.track===t),r=i?.info.decoderConfig.codec??t.source._codec;for(let t of(s.push(r),e.references))a(null!==t.playlist.peakBitrate),n=Math.max(n,t.playlist.peakBitrate),o=Math.max(o,t.playlist.averageBitrate??0)}a(null!==e.playlist.peakBitrate);let l=e.playlist.peakBitrate+n,c=(e.playlist.averageBitrate??0)+o;i||(t+="\n",i=!0),r?t+="#EXT-X-I-FRAME-STREAM-INF:":t+="#EXT-X-STREAM-INF:",t+=`BANDWIDTH=${Math.ceil(l)}`,c>0&&(t+=`,AVERAGE-BANDWIDTH=${Math.ceil(c)}`),t+=`,CODECS="${s.join(",")}"`;let d=e.playlist.tracks.find(e=>e.isVideoTrack());if(d?.isVideoTrack()){let e=this.trackDatas.find(e=>e.track===d),i=e?.info.decoderConfig;if(i){let e=i.displayAspectWidth??i.codedWidth,r=i.displayAspectHeight??i.codedHeight;void 0!==e&&void 0!==r&&(void 0!==d.metadata.rotation&&d.metadata.rotation%180==90&&([e,r]=[r,e]),t+=`,RESOLUTION=${e}x${r}`)}r||void 0===d.metadata.frameRate||(t+=`,FRAME-RATE=${+d.metadata.frameRate.toFixed(3)}`)}if(!r){let i=new Map;for(let t of e.references){a(null!==t.groupId);let e=t.playlist.tracks[0].type;i.set(e,t.groupId)}for(let[e,r]of i)t+=`,${e.toUpperCase()}="${r}"`}r?t+=`,URI="${e.playlist.path}"
12`:t+=`
13${e.playlist.path}
14`}else{a(1===e.playlist.tracks.length);let i=e.playlist.tracks[0],o=i.type,l=i.metadata.name??null,c=i.metadata.languageCode,d=i.metadata.disposition;(null===r||e.groupId!==r)&&(s=0,t+="\n",n=!1),r=e.groupId,s++,t+=`#EXT-X-MEDIA:TYPE=${o.toUpperCase()},GROUP-ID="${e.groupId}"`,null!==l&&/[\n\r"]/.test(l)&&(eR._warn("Dropping track name since it includes a line feed, carriage return, or double quote character, which are not allowed in HLS playlist attributes."),l=null),l??=`${c??e.groupId}-${s}`,t+=`,NAME="${l}"`,void 0!==c&&(t+=`,LANGUAGE="${c}"`);let u=d?.primary??!1,h=d?.default??!0;if(u&&!n&&(t+=",DEFAULT=YES",n=!0),(u||h)&&(t+=",AUTOSELECT=YES"),d?.forced&&(t+=",FORCED=YES"),"audio"===o){let e=this.trackDatas.find(e=>e.track===i),r=e?.info.decoderConfig;r&&(t+=`,CHANNELS="${r.numberOfChannels}"`)}e.noUri||(t+=`,URI="${e.playlist.path}"`),t+="\n"}this.format._options.onMaster?.(t);let o=await this.mutex.acquire();try{let i;if(0===this.numWrittenMasterPlaylists)i=await this.output._getRootWriter(!0);else{let t=await this.output._getTarget({path:e.rootPath,isRoot:!0,mimeType:r2});(i=new cT(t,!0)).start()}i.write(m.encode(t)),await i.flush(),await i.finalize(),this.numWrittenMasterPlaylists++}finally{o()}}async tryWriteMasterPlaylist(){for(let e of(a(this.isLive),this.playlists))if(0===e.writtenSegments.length&&!e.done)return;await this.writeMasterPlaylist()}async finalize(){for(let e of((await Promise.all(this.playlists.map(e=>e.mutex.acquire()))).forEach(e=>e()),this.trackDatas))e.closed=!0;await Promise.all(this.playlists.map(e=>e.done?Promise.resolve():this.advancePlaylist(e))),this.isLive||await this.writeMasterPlaylist()}}let dg=e=>{if("string"!=typeof e)throw TypeError("options.getPlaylistPath must return or resolve to a string");if(/[\n\r"]/.test(e))throw TypeError("Playlist paths cannot contain line feed, carriage return, or double quote characters.")},dk=e=>{if("string"!=typeof e)throw TypeError("options.getSegmentPath must return or resolve to a string");if(/[\n\r"]/.test(e))throw TypeError("Segment paths cannot contain line feed or carriage return characters.")},dy=e=>{if("string"!=typeof e)throw TypeError("options.getInitPath must return or resolve to a string");if(/[\n\r"]/.test(e))throw TypeError("Init paths cannot contain line feed, carriage return, or double quote characters.")},dw=e=>({n:e.id,tracks:e.tracks,segmentFormat:e.segmentFormat});
14class db{getSupportedVideoCodecs(){return this.getSupportedCodecs().filter(e=>e$.includes(e))}getSupportedAudioCodecs(){return this.getSupportedCodecs().filter(e=>eG.includes(e))}getSupportedSubtitleCodecs(){return this.getSupportedCodecs().filter(e=>eY.includes(e))}_codecUnsupportedHint(e){return""}_isFragmentedIsobmff(){return!1}}class dT extends db{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 cR(e,this)}_isFragmentedIsobmff(){return"fragmented"===this._options.fastStart}}class dS extends dT{constructor(e){super(e)}get _name(){return"MP4"}get fileExtension(){return".mp4"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...e$,...eX,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...eY]}_codecUnsupportedHint(e){return new dv().getSupportedCodecs().includes(e)?" Switching to MOV will grant support for this codec.":""}}class dA extends dT{constructor(e){super(e)}get _name(){return"CMAF"}get fileExtension(){return".m4s"}get mimeType(){return"video/mp4"}getSupportedCodecs(){return[...e$,...eX,"pcm-s16","pcm-s16be","pcm-s24","pcm-s24be","pcm-s32","pcm-s32be","pcm-f32","pcm-f32be","pcm-f64","pcm-f64be",...eY]}}class dv extends dT{constructor(e){super(e)}get _name(){return"MOV"}get fileExtension(){return".mov"}get mimeType(){return"video/quicktime"}getSupportedCodecs(){return[...e$,...eG]}_codecUnsupportedHint(e){return new dS().getSupportedCodecs().includes(e)?" Switching to MP4 will grant support for this codec.":""}}class dP extends db{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.appendOnly&&"boolean"!=typeof e.appendOnly)throw TypeError("options.appendOnly, when provided, must be a boolean.");if(void 0!==e.minimumClusterDuration&&(!Number.isFinite(e.minimumClusterDuration)||e.minimumClusterDuration<0))throw TypeError("options.minimumClusterDuration, when provided, must be a non-negative number.");if(void 0!==e.onEbmlHeader&&"function"!=typeof e.onEbmlHeader)throw TypeError("options.onEbmlHeader, when provided, must be a function.");if(void 0!==e.onSegmentHeader&&"function"!=typeof e.onSegmentHeader)throw TypeError("options.onHeader, when provided, must be a function.");if(void 0!==e.onCluster&&"function"!=typeof e.onCluster)throw TypeError("options.onCluster, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cO(e,this)}get _name(){return"Matroska"}getSupportedTrackCounts(){return{video:{min:0,max:127},audio:{min:0,max:127},subtitle:{min:0,max:127},total:{min:0,max:127}}}get fileExtension(){return".mkv"}get mimeType(){return"video/x-matroska"}getSupportedCodecs(){return[...e$,...eX,...eK.filter(e=>!["pcm-s8","pcm-f32be","pcm-f64be","ulaw","alaw"].includes(e)),...eY]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class dC extends dP{constructor(e){super(e)}getSupportedCodecs(){return[...e$.filter(e=>["vp8","vp9","av1"].includes(e)),...eG.filter(e=>["opus","vorbis"].includes(e)),...eY]}get _name(){return"WebM"}get fileExtension(){return".webm"}get mimeType(){return"video/webm"}_codecUnsupportedHint(e){return new dP().getSupportedCodecs().includes(e)?" Switching to MKV will grant support for this codec.":""}}class dx extends db{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.xingHeader&&"boolean"!=typeof e.xingHeader)throw TypeError("options.xingHeader, when provided, must be a boolean.");if(void 0!==e.onXingFrame&&"function"!=typeof e.onXingFrame)throw TypeError("options.onXingFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cN(e,this)}get _name(){return"MP3"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".mp3"}get mimeType(){return"audio/mpeg"}getSupportedCodecs(){return["mp3"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class dE extends db{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.large&&"boolean"!=typeof e.large)throw TypeError("options.large, when provided, must be a boolean.");if(void 0!==e.metadataFormat&&!["info","id3"].includes(e.metadataFormat))throw TypeError("options.metadataFormat, when provided, must be either 'info' or 'id3'.");if(void 0!==e.onHeader&&"function"!=typeof e.onHeader)throw TypeError("options.onHeader, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cX(e,this)}get _name(){return"WAVE"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".wav"}get mimeType(){return"audio/wav"}getSupportedCodecs(){return[...eK.filter(e=>["pcm-s16","pcm-s24","pcm-s32","pcm-f32","pcm-f64","pcm-u8","ulaw","alaw"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class d_ extends db{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.maximumPageDuration&&(!Number.isFinite(e.maximumPageDuration)||e.maximumPageDuration<=0))throw TypeError("options.maximumPageDuration, when provided, must be a positive number.");if(void 0!==e.onPage&&"function"!=typeof e.onPage)throw TypeError("options.onPage, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cW(e,this)}get _name(){return"Ogg"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:0,max:0x100000000},subtitle:{min:0,max:0},total:{min:0,max:0x100000000}}}get fileExtension(){return".ogg"}get mimeType(){return"application/ogg"}getSupportedCodecs(){return[...eG.filter(e=>["vorbis","opus"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class dI extends db{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.onFrame&&"function"!=typeof e.onFrame)throw TypeError("options.onFrame, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new oQ(e,this)}get _name(){return"ADTS"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".aac"}get mimeType(){return"audio/aac"}getSupportedCodecs(){return["aac"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class dB extends db{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.appendOnly&&"boolean"!=typeof e.appendOnly)throw TypeError("options.appendOnly, when provided, must be a boolean.");super(),this._options=e}_createMuxer(e){return new oK(e,this)}get _name(){return"FLAC"}getSupportedTrackCounts(){return{video:{min:0,max:0},audio:{min:1,max:1},subtitle:{min:0,max:0},total:{min:1,max:1}}}get fileExtension(){return".flac"}get mimeType(){return"audio/flac"}getSupportedCodecs(){return["flac"]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!1}}class dF extends db{constructor(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.onPacket&&"function"!=typeof e.onPacket)throw TypeError("options.onPacket, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new cq(e,this)}get _name(){return"MPEG-TS"}getSupportedTrackCounts(){return{video:{min:0,max:16},audio:{min:0,max:32},subtitle:{min:0,max:0},total:{min:0,max:48}}}get fileExtension(){return".ts"}get mimeType(){return"video/MP2T"}getSupportedCodecs(){return[...e$.filter(e=>["avc","hevc"].includes(e)),...eG.filter(e=>["aac","mp3","ac3","eac3","dts"].includes(e))]}get supportsVideoRotationMetadata(){return!1}get supportsTimestampedMediaData(){return!0}}class dM extends db{constructor(e){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!(e.segmentFormat instanceof db)&&(!Array.isArray(e.segmentFormat)||0===e.segmentFormat.length||!e.segmentFormat.every(e=>e instanceof db)))throw TypeError("options.segmentFormat must be an OutputFormat or a non-empty array of OutputFormat instances.");if(void 0!==e.targetDuration&&("number"!=typeof e.targetDuration||e.targetDuration<=0))throw TypeError("options.targetDuration, when provided, must be a positive number.");if(void 0!==e.singleFilePerPlaylist&&"boolean"!=typeof e.singleFilePerPlaylist)throw TypeError("options.singleFilePerPlaylist, when provided, must be a boolean.");if(void 0!==e.live&&"boolean"!=typeof e.live)throw TypeError("options.live, when provided, must be a boolean.");if(void 0!==e.maxLiveSegmentCount&&("number"!=typeof e.maxLiveSegmentCount||e.maxLiveSegmentCount<1||Number.isFinite(e.maxLiveSegmentCount)&&!Number.isInteger(e.maxLiveSegmentCount)))throw TypeError("options.maxLiveSegmentCount, when provided, must be a positive integer or Infinity.");if(void 0!==e.getPlaylistPath&&"function"!=typeof e.getPlaylistPath)throw TypeError("options.getPlaylistPath, when provided, must be a function.");
14if(void 0!==e.getSegmentPath&&"function"!=typeof e.getSegmentPath)throw TypeError("options.getSegmentPath, when provided, must be a function.");if(void 0!==e.getInitPath&&"function"!=typeof e.getInitPath)throw TypeError("options.getInitPath, when provided, must be a function.");if(void 0!==e.onMaster&&"function"!=typeof e.onMaster)throw TypeError("options.onMaster, when provided, must be a function.");if(void 0!==e.onPlaylist&&"function"!=typeof e.onPlaylist)throw TypeError("options.onPlaylist, when provided, must be a function.");if(void 0!==e.onSegment&&"function"!=typeof e.onSegment)throw TypeError("options.onSegment, when provided, must be a function.");if(void 0!==e.onInit&&"function"!=typeof e.onInit)throw TypeError("options.onInit, when provided, must be a function.");if(void 0!==e.onSegmentPopped&&"function"!=typeof e.onSegmentPopped)throw TypeError("options.onSegmentPopped, when provided, must be a function.");super(),this._options=e}_createMuxer(e){return new dp(e,this)}get _name(){return"HTTP Live Streaming (HLS)"}get fileExtension(){return".m3u8"}get mimeType(){return r2}getSupportedCodecs(){return[...new Set(e_(this._options.segmentFormat).flatMap(e=>e.getSupportedCodecs()))]}getSupportedTrackCounts(){let e=!1,t=!1,i=!1;for(let r of e_(this._options.segmentFormat)){let a=r.getSupportedTrackCounts();e||=a.video.max>0,t||=a.audio.max>0,i||=a.subtitle.max>0}return{video:{min:0,max:e?1/0:0},audio:{min:0,max:t?1/0:0},subtitle:{min:0,max:0},total:{min:0,max:1/0}}}get supportsVideoRotationMetadata(){return e_(this._options.segmentFormat).some(e=>e.supportsVideoRotationMetadata)}get supportsTimestampedMediaData(){return!0}_codecUnsupportedHint(e){return" Using different segment formats may grant support for this codec."}}let dR=["video","audio","subtitle"];class dD{constructor(e,t,i,r,a){this.id=e,this.output=t,this.type=i,this.source=r,this.metadata=a}isVideoTrack(){return"video"===this.type}isAudioTrack(){return"audio"===this.type}isSubtitleTrack(){return"subtitle"===this.type}canBePairedWith(e){if(!(e instanceof dD))throw TypeError("other must be an OutputTrack.");if(this===e)return!1;let t=e_(this.metadata.group),i=e_(e.metadata.group);for(let r of t)if(this.type!==e.type&&i.some(e=>r===e)||i.some(e=>r._pairedGroups.has(e)))return!0;return!1}}class dz extends dD{constructor(e,t,i,r){super(e,t,"video",i,r)}}class dO extends dD{constructor(e,t,i,r){super(e,t,"audio",i,r)}}class dU extends dD{constructor(e,t,i,r){super(e,t,"subtitle",i,r)}}class dN{constructor(){this._pairedGroups=new Set}pairWith(e){if(!(e instanceof dN))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 dW=e=>{if(!e||"object"!=typeof e)throw TypeError("metadata must be an object.");if(void 0!==e.languageCode&&!K(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&&(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.")})(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 dN)&&(!Array.isArray(e.group)||e.group.some(e=>!(e instanceof dN))))throw TypeError("metadata.group, when provided, must be an OutputTrackGroup instance or an array of OutputTrackGroup instances.")};class dV extends eI{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 dN,this.tracks=[],this._onFinalize=null,this._unfinalizedTargets=new Set,this._rootWriterPromise=null,this._startPromise=null,this._cancelPromise=null,this._finalizePromise=null,this._mutex=new v,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 db))throw TypeError("options.format must be an OutputFormat.");if(!(e.target instanceof cA||e.target instanceof cI))throw TypeError("options.target must be a Target or a PathedTarget.");if(e.target instanceof cA&&this._rememberTarget(e.target),void 0!==e.initTarget&&!(e.initTarget instanceof cA)&&"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 cA&&this._rememberTarget(this._initTarget),this._muxer=e.format._createMuxer(this)}_getTargetValidated(e){a(this._target instanceof cI);let t=this._target.getTarget(e),i=e=>{if(!(e instanceof cA))throw TypeError("getTarget must return a Target.");return e};return t instanceof Promise?t.then(i):i(t)}async _getTarget(e){a(this._target instanceof cI);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})}
14async _getInitTarget(){if(a(null!==this._initTarget),this._initTarget instanceof cA)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 cA)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),i=t=>("canceled"===this.state?t._close():this._rememberTarget(t),this._emit("target",{target:t,request:e,isRoot:!0}),this._rootTarget=t,t);return t instanceof Promise?this._rootTargetPromise=t.then(i):i(t)}_getRootWriter(e){return this._rootWriterPromise??=(async()=>{let t=await this._getRootTarget(),i=new cT(t,"boolean"==typeof e?e:e(t));return i.start(),i})()}addVideoTrack(e,t={}){if(!(e instanceof c0))throw TypeError("source must be a VideoSource.");if(dW(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&&td({decoderConfig:t.decoderConfig},e._codec),void 0!==t.primingPacket){if(!(t.primingPacket instanceof ik))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 i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new dz(this.tracks.length+1,this,e,i))}addAudioTrack(e,t={}){if(!(e instanceof de))throw TypeError("source must be an AudioSource.");if(dW(t),void 0!==t.decoderConfig&&th({decoderConfig:t.decoderConfig},e._codec),void 0!==t.primingPacket){if(!(t.primingPacket instanceof ik))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 i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new dO(this.tracks.length+1,this,e,i))}addSubtitleTrack(e,t={}){if(!(e instanceof dm))throw TypeError("source must be a SubtitleSource.");dW(t);let i={...t};return i.group??=this.defaultTrackGroup,this._addTrack(new dU(this.tracks.length+1,this,e,i))}setMetadataTags(e){if(eO(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.");if(e.source._connectedTrack)throw Error("Source is already used for a track.");let t=this.format.getSupportedTrackCounts(),i=this.tracks.reduce((t,i)=>t+ +(i.type===e.type),0),r=t[e.type].max;if(i===r)throw Error(0===r?`${this.format._name} does not support ${e.type} tracks.`:`${this.format._name} does not support more than ${r} ${e.type} track${1===r?"":"s"}.`);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))}
14else 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 dR)if(this.tracks.reduce((e,i)=>e+ +(i.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 dR){let i=this.tracks.reduce((e,i)=>e+ +(i.type===t),0),r=e[t].min;if(i<r)throw Error(r===e[t].max?`${this.format._name} requires exactly ${r} ${t} track${1===r?"":"s"}.`:`${this.format._name} requires at least ${r} ${t} track${1===r?"":"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?(eR._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 eR._warn("Output has already been canceled."),this._cancelPromise;if("finalizing"===this.state||"finalized"===this.state){"finalized"===this.state&&eR._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?(eR._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()}})()}}var dL=function(e,t,i){if(null!=t){var r,a;if("object"!=typeof t&&"function"!=typeof t)throw TypeError("Object expected.");if(i){if(!Symbol.asyncDispose)throw TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!=typeof r)throw TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},dq=(am="function"==typeof SuppressedError?SuppressedError:function(e,t,i){var r=Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r},function(e){function t(t){e.error=e.hasError?new am(t,e.error,"An error was suppressed during disposal."):t,e.hasError=!0}var i,r=0;return function a(){for(;i=e.stack.pop();)try{if(!i.async&&1===r)return r=0,e.stack.push(i),Promise.resolve().then(a);if(i.dispose){var s=i.dispose.call(i.value);if(i.async)return r|=2,Promise.resolve(s).then(a,function(e){return t(e),a()})}else r|=1}catch(e){t(e)}
14if(1===r)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}()});let dH=e=>{if(!e||"object"!=typeof e)throw TypeError("options.video, when provided, must be an object.");if(e?.discard!==void 0&&"boolean"!=typeof e.discard)throw TypeError("options.video.discard, when provided, must be a boolean.");if(e?.forceTranscode!==void 0&&"boolean"!=typeof e.forceTranscode)throw TypeError("options.video.forceTranscode, when provided, must be a boolean.");if(e?.codec!==void 0&&!e$.includes(e.codec))throw TypeError(`options.video.codec, when provided, must be one of: ${e$.join(", ")}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof nd))throw TypeError("options.video.quality, when provided, must be a Quality.");if(e?.quality!==void 0&&void 0!==t)throw TypeError("options.video.quality and options.video.bitrate cannot both be provided.");if(void 0!==t&&!(t instanceof nd)&&(!Number.isInteger(t)||t<=0))throw TypeError("options.video.bitrate, when provided, must be a positive integer or a quality.");if(e?.width!==void 0&&(!Number.isInteger(e.width)||e.width<=0))throw TypeError("options.video.width, when provided, must be a positive integer.");if(e?.height!==void 0&&(!Number.isInteger(e.height)||e.height<=0))throw TypeError("options.video.height, when provided, must be a positive integer.");if(e?.fit!==void 0&&!["fill","contain","cover"].includes(e.fit))throw TypeError("options.video.fit, when provided, must be one of 'fill', 'contain', or 'cover'.");if(e?.width!==void 0&&void 0!==e.height&&void 0===e.fit)throw TypeError("When both options.video.width and options.video.height are provided, options.video.fit must also be provided.");if(e?.rotate!==void 0&&![0,90,180,270].includes(e.rotate))throw TypeError("options.video.rotate, when provided, must be 0, 90, 180 or 270.");if(e?.allowRotationMetadata!==void 0&&"boolean"!=typeof e.allowRotationMetadata)throw TypeError("options.video.allowRotationMetadata, when provided, must be a boolean.");if(e?.crop!==void 0&&sX(e.crop,"options.video."),e?.frameRate!==void 0&&(!Number.isFinite(e.frameRate)||e.frameRate<=0))throw TypeError("options.video.frameRate, when provided, must be a finite positive number.");if(e?.alpha!==void 0&&!["discard","keep"].includes(e.alpha))throw TypeError("options.video.alpha, when provided, must be either 'discard' or 'keep'.");if(e?.keyFrameInterval!==void 0&&(!Number.isFinite(e.keyFrameInterval)||e.keyFrameInterval<0))throw TypeError("options.video.keyFrameInterval, when provided, must be a non-negative number.");if(e?.process!==void 0&&"function"!=typeof e.process)throw TypeError("options.video.process, when provided, must be a function.");if(e?.processedWidth!==void 0&&(!Number.isInteger(e.processedWidth)||e.processedWidth<=0))throw TypeError("options.video.processedWidth, when provided, must be a positive integer.");if(e?.processedHeight!==void 0&&(!Number.isInteger(e.processedHeight)||e.processedHeight<=0))throw TypeError("options.video.processedHeight, when provided, must be a positive integer.");if(e?.hardwareAcceleration!==void 0&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw TypeError("options.video.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(e?.group!==void 0&&!(e.group instanceof dN||Array.isArray(e.group)&&e.group.every(e=>e instanceof dN)))throw TypeError("options.video.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")},dj=e=>{if(!e||"object"!=typeof e)throw TypeError("options.audio, when provided, must be an object.");if(e?.discard!==void 0&&"boolean"!=typeof e.discard)throw TypeError("options.audio.discard, when provided, must be a boolean.");if(e?.forceTranscode!==void 0&&"boolean"!=typeof e.forceTranscode)throw TypeError("options.audio.forceTranscode, when provided, must be a boolean.");if(e?.codec!==void 0&&!eG.includes(e.codec))throw TypeError(`options.audio.codec, when provided, must be one of: ${eG.join(", ")}.`);let t=e?.bitrate;if(e?.quality!==void 0&&!(e.quality instanceof nd))throw TypeError("options.audio.quality, when provided, must be a Quality.");if(e?.quality!==void 0&&void 0!==t)throw TypeError("options.audio.quality and options.audio.bitrate c
14annot both be provided.");if(void 0!==t&&!(t instanceof nd)&&(!Number.isInteger(t)||t<=0))throw TypeError("options.audio.bitrate, when provided, must be a positive integer or a quality.");if(e?.numberOfChannels!==void 0&&(!Number.isInteger(e.numberOfChannels)||e.numberOfChannels<=0))throw TypeError("options.audio.numberOfChannels, when provided, must be a positive integer.");if(e?.sampleRate!==void 0&&(!Number.isInteger(e.sampleRate)||e.sampleRate<=0))throw TypeError("options.audio.sampleRate, when provided, must be a positive integer.");if(e?.sampleFormat!==void 0&&!["u8","s16","s32","f32"].includes(e.sampleFormat))throw TypeError("options.audio.sampleFormat, when provided, must be one of: u8, s16, s32, f32.");if(e?.process!==void 0&&"function"!=typeof e.process)throw TypeError("options.audio.process, when provided, must be a function.");if(e?.processedNumberOfChannels!==void 0&&(!Number.isInteger(e.processedNumberOfChannels)||e.processedNumberOfChannels<=0))throw TypeError("options.audio.processedNumberOfChannels, when provided, must be a positive integer.");if(e?.processedSampleRate!==void 0&&(!Number.isInteger(e.processedSampleRate)||e.processedSampleRate<=0))throw TypeError("options.audio.processedSampleRate, when provided, must be a positive integer.");if(e?.group!==void 0&&!(e.group instanceof dN||Array.isArray(e.group)&&e.group.every(e=>e instanceof dN)))throw TypeError("options.audio.group, when provided, must be an OutputTrackGroup or an array of OutputTrackGroups.")};class dQ{static async init(e){let t=new dQ(e);return await t._init(),t}constructor(e){if(this.state="idle",this._nextOutputTrackId=0,this._outputTrackIds=[],this._outputOwnTrackGroups=[],this._trackPumps=[],this._composable=!1,this._executed=!1,this._executionUntil=1/0,this._pauseRequested=!1,this._synchronizer=new dK(this),this._totalDuration=null,this._maxTimestamps=new Map,this.onProgress=void 0,this._computeProgress=!1,this._lastProgress=0,this.isValid=!1,this.utilizedTracks=[],this.discardedTracks=[],!e||"object"!=typeof e)throw TypeError("options must be an object.");if(!(e.input instanceof oh))throw TypeError("options.input must be an Input.");if(!(e.output instanceof dV))throw TypeError("options.output must be an Output.");if(void 0!==e.tracks&&"all"!==e.tracks&&"primary"!==e.tracks)throw TypeError("options.tracks, when provided, must be either 'all' or 'primary'.");if(void 0!==e.composable&&"boolean"!=typeof e.composable)throw TypeError("options.composable, when provided, must be a boolean.");let t=e.composable??!1;if(t){if(void 0!==e.tags)throw TypeError("options.tags cannot be set by a composable conversion; set metadata directly on the output instead.");if("pending"!==e.output.state)throw TypeError("options.output must not have been started yet.")}else if(e.output.tracks.length>0||Object.keys(e.output._metadataTags).length>0||"pending"!==e.output.state)throw TypeError("options.output must be fresh: no tracks or metadata tags added and not started.");if(void 0!==e.video&&"function"!=typeof e.video)if(Array.isArray(e.video))for(let t of e.video)dH(t);else dH(e.video);if(void 0!==e.audio&&"function"!=typeof e.audio)if(Array.isArray(e.audio))for(let t of e.audio)dj(t);else dj(e.audio);if(void 0!==e.trim&&(!e.trim||"object"!=typeof e.trim))throw TypeError("options.trim, when provided, must be an object.");if(e.trim?.start!==void 0&&!Number.isFinite(e.trim.start))throw TypeError("options.trim.start, when provided, must be a finite number.");if(e.trim?.end!==void 0&&!Number.isFinite(e.trim.end))throw TypeError("options.trim.end, when provided, must be a finite number.");if(e.trim?.start!==void 0&&void 0!==e.trim.end&&e.trim.start>=e.trim.end)throw TypeError("options.trim.start must be less than options.trim.end.");if(void 0!==e.tags&&("object"!=typeof e.tags||!e.tags)&&"function"!=typeof e.tags)throw TypeError("options.tags, when provided, must be an object or a function.");if("object"==typeof e.tags&&eO(e.tags),void 0!==e.showWarnings&&"boolean"!=typeof e.showWarnings)throw TypeError("options.showWarnings, when provided, must be a boolean.");this._options=e,this._composable=t,this.input=e.input,this.output=e.output}async _init(){let e,t=await this.input.getFormat(),i=this._options.tracks;(void 0===i&&(i=t.name.includes("(HLS)")?"primary":"all"),"all"===i)?e=await this.input.getTracks():"primary"===i?e=[await this.input.getPrimaryVideoTrack(),await this.input.getPrimaryAudioTrack()].filter(e=>null!==e):(z(i),a(!1));
14let r=this.output.format.getSupportedTrackCounts(),s=1,n=1,o=[],l=[];for(let t of e){let e;if(t.isVideoTrack())if(this._options.video)if("function"==typeof this._options.video){let i=await this._options.video(t,s)??{};if(Array.isArray(i))for(let e of i)dH(e);else dH(i);e=Array.isArray(i)?i:[i],s++}else e=Array.isArray(this._options.video)?this._options.video:[this._options.video];else e=[{}];else if(t.isAudioTrack())if(this._options.audio)if("function"==typeof this._options.audio){let i=await this._options.audio(t,n)??{};if(Array.isArray(i))for(let e of i)dj(e);else dj(i);e=Array.isArray(i)?i:[i],n++}else e=Array.isArray(this._options.audio)?this._options.audio:[this._options.audio];else e=[{}];else a(!1);let i=e.filter(e=>e.discard);for(let e of i)this.discardedTracks.push({track:t,reason:"discarded_by_user",trackOptions:e});if(e.length===i.length){0===e.length&&this.discardedTracks.push({track:t,reason:"discarded_by_user",trackOptions:{}});continue}let r=e.filter(e=>!e.discard);o.push(t),l.push(r)}this._options.trim?.start!==void 0?this._startTimestamp=this._options.trim.start:this._startTimestamp=Math.max(await this.input.getFirstTimestamp(o),0),this._endTimestamp=Math.max(this._options.trim?.end??1/0,this._startTimestamp);for(let e=0;e<o.length;e++){let t=o[e];for(let i of l[e]){if(this.output.tracks.length===r.total.max){this.discardedTracks.push({track:t,reason:"max_track_count_reached",trackOptions:i});continue}if(this.output.tracks.reduce((e,i)=>e+ +(i.type===t.type),0)===r[t.type].max){this.discardedTracks.push({track:t,reason:"max_track_count_of_type_reached",trackOptions:i});continue}let e=this._nextOutputTrackId++;t.isVideoTrack()?await this._processVideoTrack(t,i,e):t.isAudioTrack()?await this._processAudioTrack(t,i,e):a(!1)}}for(let e=0;e<this.utilizedTracks.length-1;e++)for(let t=e+1;t<this.utilizedTracks.length;t++){let i=this.utilizedTracks[e],r=this.utilizedTracks[t],s=this._outputOwnTrackGroups[e],n=this._outputOwnTrackGroups[t];a(void 0!==s),a(void 0!==n),s&&n&&i.canBePairedWith(r)&&s.pairWith(n)}if(!this._composable){let e,i=await this.input.getMetadataTags();if(this._options.tags){let t="function"==typeof this._options.tags?await this._options.tags(i):this._options.tags;eO(t),e=t}else e=i;let r=t.mimeType===this.output.format.mimeType,a=i.raw===e.raw;i.raw&&a&&!r&&delete e.raw,this.output.setMetadataTags(e)}if(this._composable?this.isValid=!0:this.isValid=this.output.hasEnoughTracks()&&this.output.tracks.length>0,this._options.showWarnings??!0){let e=[],t=this.discardedTracks.filter(e=>"discarded_by_user"!==e.reason);t.length>0&&e.push("Some tracks had to be discarded from the conversion:",t),this.isValid||(e.length>0&&e.push("\n\n"),e.push(this._getInvalidityExplanation().join(""))),e.length>0&&eR._warn(...e)}}_getInvalidityExplanation(){let e=[];
14if(0===this.discardedTracks.length)e.push("Due to missing tracks, this conversion cannot be executed.");else{let t=this.discardedTracks.every(e=>"discarded_by_user"===e.reason||"no_encodable_target_codec"===e.reason)&&this.discardedTracks.some(e=>"no_encodable_target_codec"===e.reason);if(e.push("Due to discarded tracks, this conversion cannot be executed."),t){let t=[...new Set(this.discardedTracks.flatMap(e=>"discarded_by_user"===e.reason?[]:("video"===e.track.type?this.output.format.getSupportedVideoCodecs():"audio"===e.track.type?this.output.format.getSupportedAudioCodecs():this.output.format.getSupportedSubtitleCodecs()).filter(t=>!e.trackOptions.codec||t===e.trackOptions.codec)))];1===t.length?e.push(`
15Tracks were discarded because your environment is not able to encode '${t[0]}' with the provided parameters.`):e.push(`
16Tracks were discarded because your environment is not able to encode any of the codecs ${t.map(e=>`'${e}'`).join(", ")} with the provided parameters.`),t.includes("mp3")&&e.push(`
17The @mediabunny/mp3-encoder extension package provides support for encoding MP3.`),t.includes("aac")&&e.push("\nThe @mediabunny/aac-encoder extension package provides support for encoding AAC."),(t.includes("ac3")||t.includes("eac3"))&&e.push("\nThe @mediabunny/ac3 extension package provides support for encoding and decoding AC-3/E-AC-3."),t.includes("flac")&&e.push("\nThe @mediabunny/flac-encoder extension package provides support for encoding FLAC.")}else e.push("\nCheck the discardedTracks field for more info.")}return e}async execute(e={}){if(!e||"object"!=typeof e)throw TypeError("options must be an object.");if(void 0!==e.until&&("number"!=typeof e.until||Number.isNaN(e.until)))throw TypeError("options.until, when provided, must be a number.");if(void 0!==e.pauseSignal&&!(e.pauseSignal instanceof AbortSignal))throw TypeError("options.pauseSignal, when provided, must be an AbortSignal.");if(!this.isValid)throw Error("Cannot execute this conversion because its output configuration is invalid. Make sure to always check the isValid field before executing a conversion.\n"+this._getInvalidityExplanation().join(""));if("executing"===this.state)throw Error("Cannot call execute() while a previous call to execute() is still running.");if("canceled"===this.state)throw new d$;if("done"===this.state)return;if(this._composable&&"pending"===this.output.state)throw Error("A composable conversion requires the output to be started. Call start() on the output before executing the conversion.");this.state="executing",this._executionUntil=e.until??1/0,this._pauseRequested=e.pauseSignal?.aborted??!1;let t=()=>{"executing"===this.state&&(this._pauseRequested=!0,this._synchronizer.resolveAll())};for(let i of(e.pauseSignal?.addEventListener("abort",t),this._trackPumps))i.done||(i.resolvers=B());if(this._executed)for(let e of this._trackPumps)e.wake?.();else{for(let e of(this._executed=!0,this._outputTrackIds))this._synchronizer.declareTrack(e);if(this.onProgress){let e=[...new Set(this.utilizedTracks)].map(async e=>await e.isLive()?1/0:await e.getDurationFromMetadata()??await e.computeDuration()),t=Math.max(0,...await Promise.all(e));for(let e of(this._computeProgress=!0,this._totalDuration=Math.min(t-this._startTimestamp,this._endTimestamp-this._startTimestamp),this._outputTrackIds))this._maxTimestamps.set(e,0);this.onProgress?.(0,0)}for(let e of(this._composable||await this.output.start(),this._trackPumps))e.start()}try{await Promise.all(this._trackPumps.map(e=>e.resolvers.promise))}catch(e){throw"canceled"!==this.state&&this.cancel(),e}finally{e.pauseSignal?.removeEventListener("abort",t)}if("canceled"===this.state)throw new d$;let i=this._trackPumps.every(e=>e.done);if(this.state=i?"done":"idle",i&&(this._composable||await this.output.finalize(),this._computeProgress)){let e=Math.min(...this._maxTimestamps.values());this.onProgress?.(1,e)}}async cancel(){if("done"!==this.state){if("canceled"===this.state)return void eR._warn("Conversion already canceled.");for(let e of(this.state="canceled",this._trackPumps))e.wake?.();this._synchronizer.resolveAll(),this._composable||await this.output.cancel()}}async _processVideoTrack(e,t,i){let r,n=await e.getCodec();if(!n)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});let o=await e.getRotation(),l=s(o+(t.rotate??0)),c=l,d=this.output.format.supportsVideoRotationMetadata&&(t.allowRotationMetadata??
17!0),u=await e.getSquarePixelWidth(),h=await e.getSquarePixelHeight(),[m,f]=l%180==0?[u,h]:[h,u],p=t.crop;p&&(p=sK(p,m,f));let[g,k]=p?[p.width,p.height]:[m,f],y=g,w=k,b=y/w;void 0!==t.width&&void 0===t.height?(y=eB(t.width),w=eB(Math.round(y/b))):void 0===t.width&&void 0!==t.height?(w=eB(t.height),y=eB(Math.round(w*b))):void 0!==t.width&&void 0!==t.height&&(y=eB(t.width),w=eB(t.height));let T=await e.getFirstTimestamp(),S=this.output.format.getSupportedVideoCodecs(),A=!!t.forceTranscode||T<this._startTimestamp||!!t.frameRate||void 0!==t.keyFrameInterval||void 0!==t.process||void 0!==t.quality||void 0!==t.bitrate||!S.includes(n)||t.codec&&t.codec!==n||y!==g||w!==k||0!==l&&!d||!!p,v=t.alpha??"discard";if(A){if(!await e.canDecode())return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});t.codec&&(S=S.filter(e=>e===t.codec));let n=nv(t.quality,t.bitrate)??new nd("high"),m=await nI(S,{width:t.process&&t.processedWidth?t.processedWidth:y,height:t.process&&t.processedHeight?t.processedHeight:w,quality:n});if(!m)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});let f={codec:m,quality:n,keyFrameInterval:t.keyFrameInterval,sizeChangeBehavior:t.fit??"passThrough",alpha:v,hardwareAcceleration:t.hardwareAcceleration,transform:{}};a(f.transform);let b=y!==g||w!==k||0!==l&&(!d||void 0!==t.process)||!!p||u!==await e.getCodedWidth()||h!==await e.getCodedHeight();if(!b){let t={stack:[],error:void 0,hasError:!1};try{let i=new dV({format:new dS,target:new cE}),r=new c5(f);i.addVideoTrack(r),await i.start();let a=new n1(e),s=dL(t,await a.getSample(T),!1);if(s)try{await r.add(s),s.close(),await i.finalize()}catch(e){eR._warn("An error occurred when probing encoder support. Falling back to rerender path.",e),i.cancel(),b=!0,f.transform.force=!0}else await i.cancel()}catch(e){t.error=e,t.hasError=!0}finally{dq(t)}}t.frameRate&&(f.transform.frameRate=t.frameRate),t.process&&(f.transform.process=t.process),b&&(c=0,f.transform.width=y,f.transform.height=w,f.transform.fit=t.fit??"fill",f.transform.rotate=s(l-o),f.transform.crop=p,f.transform.alpha=v);let A=null;f.onEncodedSample=e=>{A=e.timestamp};let P=new c5(f);r=P,this._registerTrackPump(async t=>{for await(let r of new n1(e).samples(this._startTimestamp,this._endTimestamp)){let e={stack:[],error:void 0,hasError:!1};try{let a=dL(e,r,!1);if("canceled"===this.state)break;let s=Math.max(a.timestamp-this._startTimestamp,0);a.setTimestamp(s),this._reportProgress(i,a.timestamp+a.duration),await P.add(a),a.close(),null!==A&&(this._synchronizer.shouldWait(i,A)&&await this._synchronizer.wait(A),await this._checkpoint(t,A))}catch(t){e.error=t,e.hasError=!0}finally{dq(e)}}P.close(),this._synchronizer.closeTrack(i)})}else{let t=new c2(n);r=t,this._registerTrackPump(async r=>{let s=new nQ(e),n={decoderConfig:await e.getDecoderConfig()??void 0};for await(let e of s.packets(void 0,void 0,{verifyKeyPackets:!0})){if("canceled"===this.state||e.timestamp>=this._endTimestamp)break;let s=e.clone({timestamp:e.timestamp-this._startTimestamp,sideData:"discard"===v?{}:e.sideData});a(s.timestamp>=0),this._reportProgress(i,s.timestamp+s.duration),await t.add(s,n),this._synchronizer.shouldWait(i,s.timestamp)&&await this._synchronizer.wait(s.timestamp),await this._checkpoint(r,s.timestamp)}t.close(),this._synchronizer.closeTrack(i)})}let P=null;t.group||this._composable||(P=new dN);let C=await e.getLanguageCode();this.output.addVideoTrack(r,{frameRate:t.frameRate,languageCode:K(C)?C:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),rotation:c,group:P??t.group}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(P)}async _processAudioTrack(e,t,i){let r,s=await e.getCodec();if(!s)return void this.discardedTracks.push({track:e,reason:"unknown_source_codec",trackOptions:t});let n=await e.getNumberOfChannels(),o=await e.getSampleRate(),l=await e.getFirstTimestamp(),c=t.numberOfChannels??n,d=t.sampleRate??o,u=l<this._startTimestamp,h=l>this._startTimestamp&&!this.output.format.supportsTimestampedMediaData,m=this.output.format.getSupp
17ortedAudioCodecs();if(!(!t.forceTranscode&&!t.quality&&!t.bitrate&&c===n&&d===o&&!u&&!h&&m.includes(s))||t.codec&&t.codec!==s||t.process||void 0!==t.sampleFormat){if(!await e.canDecode())return void this.discardedTracks.push({track:e,reason:"undecodable_source_codec",trackOptions:t});let s=null;t.codec&&(m=m.filter(e=>e===t.codec));let u=nv(t.quality,t.bitrate)??new nd("high"),f=await nE(m,{numberOfChannels:t.process&&t.processedNumberOfChannels?t.processedNumberOfChannels:c,sampleRate:t.process&&t.processedSampleRate?t.processedSampleRate:d,quality:u});if(!f.some(e=>eX.includes(e))&&m.some(e=>eX.includes(e))&&(2!==c||48e3!==d)){let e=(await nE(m,{numberOfChannels:2,sampleRate:48e3,quality:u})).find(e=>eX.includes(e));e&&(s=e,c=2,d=48e3)}else s=f[0]??null;if(null===s)return void this.discardedTracks.push({track:e,reason:"no_encodable_target_codec",trackOptions:t});let p={codec:s,quality:u,transform:{sampleFormat:t.sampleFormat,process:t.process}};a(p.transform),c!==n&&(p.transform.numberOfChannels=c),d!==o&&(p.transform.sampleRate=d);let g=null;p.onEncodedSample=e=>{g=e.timestamp};let k=new dr(p);r=k,this._registerTrackPump(async t=>{for await(let r of new n8(e).samples(this._startTimestamp,this._endTimestamp)){let e={stack:[],error:void 0,hasError:!1};try{let a,s=dL(e,r,!1);if("canceled"===this.state)break;if(h){let e={stack:[],error:void 0,hasError:!1};try{let r=l-this._startTimestamp,a=Math.round(r*o),c=s6(s.format),d=new Uint8Array(c*a*n);("u8"===s.format||"u8-planar"===s.format)&&d.fill(128);let u=dL(e,new s8({data:d,format:s.format,numberOfChannels:n,sampleRate:o,timestamp:0}),!1);await this._registerAudioSample(t,u,k,i,()=>g),h=!1}catch(t){e.error=t,e.hasError=!0}finally{dq(e)}}let c=0,d=s.numberOfFrames;if(s.timestamp<this._startTimestamp&&(c=Math.round((this._startTimestamp-s.timestamp)*s.sampleRate)),s.timestamp+s.duration>this._endTimestamp&&(d=Math.round((this._endTimestamp-s.timestamp)*s.sampleRate)),c>0||d<s.numberOfFrames){let e=s.trim(c,d);if(s.close(),a=e,0===e.numberOfFrames){e.close();continue}}else a=s;let u=dL(e,a,!1);u.setTimestamp(u.timestamp-this._startTimestamp),await this._registerAudioSample(t,u,k,i,()=>g)}catch(t){e.error=t,e.hasError=!0}finally{dq(e)}}k.close(),this._synchronizer.closeTrack(i)})}else{let t=new dt(s);r=t,this._registerTrackPump(async r=>{let s=new nQ(e),n={decoderConfig:await e.getDecoderConfig()??void 0};for await(let e of s.packets()){if("canceled"===this.state||e.timestamp>=this._endTimestamp)break;let s=e.clone({timestamp:e.timestamp-this._startTimestamp});a(s.timestamp>=0),this._reportProgress(i,s.timestamp+s.duration),await t.add(s,n),this._synchronizer.shouldWait(i,s.timestamp)&&await this._synchronizer.wait(s.timestamp),await this._checkpoint(r,s.timestamp)}t.close(),this._synchronizer.closeTrack(i)})}let f=null;t.group||this._composable||(f=new dN);let p=await e.getLanguageCode();this.output.addAudioTrack(r,{languageCode:K(p)?p:void 0,name:await e.getName()??void 0,disposition:await e.getDisposition(),group:f??t.group}),this.utilizedTracks.push(e),this._outputTrackIds.push(i),this._outputOwnTrackGroups.push(f)}async _registerAudioSample(e,t,i,r,a){this._reportProgress(r,t.timestamp+t.duration),await i.add(t),t.close();let s=a();null!==s&&(this._synchronizer.shouldWait(r,s)&&await this._synchronizer.wait(s),await this._checkpoint(e,s))}_registerTrackPump(e){let t={done:!1,resolvers:B(),wake:null,start:()=>{e(t).then(()=>{t.done=!0,t.resolvers.resolve()},e=>{t.resolvers.reject(e)})}};this._trackPumps.push(t)}async _checkpoint(e,t){for(;"canceled"!==this.state&&(t>=this._executionUntil||this._pauseRequested);){e.resolvers.resolve();let{promise:t,resolve:i}=B();e.wake=i,await t}}_reportProgress(e,t){if(!this._computeProgress)return;a(null!==this._totalDuration),this._maxTimestamps.set(e,Math.max(t,this._maxTimestamps.get(e)));let i=Math.min(...this._maxTimestamps.values()),r=W(i/this._totalDuration,0,1);r!==this._lastProgress&&(this._lastProgress=r,this.onProgress?.(r,i))}}class d$ extends Error{constructor(e="Conversion has been canceled."){super(e),this.name="ConversionCanceledError"}}class dK{constructor(e){this.maxTimestamps=new Map,this.resolvers=[],this.conversion=e}declareTrack(e){this.maxTimestamps.set(e,0)}shouldWait(e,t){let i=this.maxTimestamps.get(e);a(void 0!==i),this.maxTimestamps.set(e,Math.max(t,i));let r=this.computeMinAndMaybeResolve();return"canceled"!==this.conversion.state&&!this.conversion._pauseRequested&&!(t>=this.conversion._executionUntil)&&t-r>1}wait(e){let{promise:t,resolve:i}=B();return this.resolvers.push({timestamp:e,resolve:i}),t}closeTrack(e){this.maxTimestamps.delete(e),this.computeMinAndMaybeResolve()}resolveAll(){for(let e of this.resolvers)e.resolve();this.resolvers.length=0}computeMinAndMaybeResolve(){let e=1/0;for(let[,t]of this.maxTimestamps)e=Math.min(e,t);for(let t=0;t<this.resolvers.length;t++){let i=this.resolvers[t];i.timestamp-e<1&&(i.resolve(),this.resolvers.splice(t,1),t--)}return e}}let dX=Symbol.for("mediabunny loaded");globalThis[dX]&&eR._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[dX]=!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.