Files
ArtPlayer/docs/compiled/artplayer-proxy-mediabunny.js
T

8 lines
419 KiB
JavaScript

/*!
* artplayer-proxy-mediabunny.js v1.2.0
* Github: https://github.com/zhw2590582/ArtPlayer
* (c) 2017-2026 Harvey Zhao
* Released under the MIT License.
*/
!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,a,s,n,o,c,l,u,d,h,f,m,p,g,k,y,b,w=e=>{throw TypeError(e)},T=(e,t,i)=>t.has(e)||w("Cannot "+i),S=(e,t,i)=>(T(e,t,"read from private field"),i?i.call(e):t.get(e)),v=(e,t,i)=>t.has(e)?w("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),P=(e,t,i,r)=>(T(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),I=(e,t,i)=>(T(e,t,"access private method"),i),x=(e,t,i,r)=>({set _(r){P(e,t,r,i)},get _(){return S(e,t,r)}});function C(e,t){const i=new Map;return e.filter(e=>{const r=e[t];return void 0===r||!i.has(r)&&i.set(r,1)})}class B{constructor(){v(this,e,!1),this.listeners=new Map}addEventListener(t,i){S(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t)?.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){if(S(this,e))return;const r=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{S(this,e)||t(r)})}destroy(){P(this,e,!0),this.listeners.clear()}}function E(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const _=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},R=e=>e&&e[e.length-1],F=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<<t)-1+e.readBits(t)},A=(e,t)=>{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-2**r)},D=e=>{const t=F(e);return 0===(1&t)?-(t>>1):t+1>>1},M=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),N=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),O=new TextDecoder,z=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),L={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},U=z(L),q={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},W=z(q),H={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},V=z(H),j=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,K={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},X=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class ${constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const G=/^[0-9a-fA-F]+$/,Q=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),Y=e=>(e=(e=(e=(e=(e=e>>1&1431655765|(1431655765&e)<<1)>>2&858993459|(858993459&e)<<2)>>4&252645135|(252645135&e)<<4)>>8&16711935|(16711935&e)<<8)>>16&65535|(65535&e)<<16)>>>0,J=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o<t?r=n+1:a=n-1}return s},Z=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},ee=(e,t,i)=>{const r=Z(e,i(t),i);e.splice(r+1,0,t)},te=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},ie=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},re=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},ae=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},se=e=>{throw new Error(`Unexpected value: ${e}`)},ne=(e,t,i)=>{const r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},oe=(e,t,i,r)=>{i>>>=0,i&=16777215,e.setUint8(t,i>>>16&255),e.setUint8(t+1,i>>>8&255),e.setUint8(t+2,255&i)},ce=(e,t)=>({async next(){const i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),le=(e,t,i)=>Math.max(t,Math.min(i,e)),ue="und",de=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},he=(e,t)=>Math.round(e/t)*t,fe=(e,t)=>Math.round(e*t)/t,me=(e,t)=>Math.floor(e/t)*t,pe=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},ge=/^[a-z]{3}$/,ke=e=>ge.test(e),ye=1e6*(1+Number.EPSILON),be=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?we(e.headers):{},a=t.headers?we(t.headers):{},s={...r};Object.entries(a).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},we=e=>{if(e instanceof Headers){const t={};return e.forEach((e,i)=>{t[i]=e}),t}if(Array.isArray(e)){const t={};return e.forEach(([e,i])=>{t[e]=i}),t}return e},Te=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(n){if(a())throw n;s++;const e=r(s,n,t);if(null===e)throw n;if(Ke._error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await We(1e3*e),a())throw n}};class Se{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ve=null;const Pe=()=>null!==ve?ve:ve=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let Ie=null;const xe=()=>null!==Ie?Ie:Ie="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let Ce=null;const Be=()=>null!==Ce?Ce:Ce=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),Ee=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,_e=(async()=>{})().constructor,Re=e=>e instanceof _e||e instanceof Promise||"function"===typeof e?.then,Fe=(e,t)=>-1!==e?e:t,Ae=(e,t,i,r)=>e<=r&&i<=t,De=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r<t.length;r++)i[r]=t.charCodeAt(r);return i},Me=()=>{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Ne=e=>"number"===typeof e&&!Number.isNaN(e),Oe=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const a=e.indexOf("/",r+3);i=-1===a?e+t:e.slice(0,a)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const a=i.indexOf("://");if(-1!==a){const e=i.indexOf("/",a+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),n=[];for(const o of s)".."===o?n.pop():"."!==o&&n.push(o);return r+n.join("/")},ze=(e,t)=>{let i=0;for(let r=0;r<e.length;r++)t(e[r])&&i++;return i},Le=(e,t)=>{let i=-1,r=1/0;for(let a=0;a<e.length;a++){const s=t(e[a]);s<r&&(r=s,i=a)}return i},Ue=e=>{E(Number.isInteger(e.num)),E(Number.isInteger(e.den)),E(0!==e.den);let t=Math.abs(e.num),i=Math.abs(e.den);for(;0!==i;){const e=t%i;t=i,i=e}const r=t||1;return{num:e.num/r,den:e.den/r}},qe=(e,t)=>{if("object"!==typeof e||!e)throw new TypeError(`${t} must be an object.`);if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(`${t}.left must be a non-negative integer.`);if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(`${t}.top must be a non-negative integer.`);if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(`${t}.width must be a non-negative integer.`);if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(`${t}.height must be a non-negative integer.`)},We=e=>new Promise(t=>setTimeout(t,e));class He{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const r={fn:t,once:i?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(a){console.error(a)}s.once&&r.delete(s)}}}var Ve,je;(je=Ve||(Ve={}))[je.Silent=0]="Silent",je[je.Errors=1]="Errors",je[je.Warnings=2]="Warnings",je[je.Info=3]="Info";class Ke{constructor(){}static get level(){return Ke._level}static set level(e){if(e!==Ve.Silent&&e!==Ve.Errors&&e!==Ve.Warnings&&e!==Ve.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Ke._level=e}static get _emitter(){return Ke._emitterInstance??(Ke._emitterInstance=new He)}static on(e,t,i){return Ke._emitter.on(e,t,i)}static _error(...e){Ke._emitter._emit("error",e),Ke._level>=Ve.Errors&&console.error(...e)}static _warn(...e){Ke._emitter._emit("warn",e),Ke._level>=Ve.Warnings&&console.warn(...e)}static _info(...e){Ke._emitter._emit("info",e),Ke._level>=Ve.Info&&console.info(...e)}}Ke._level=Ve.Info,Ke._emitterInstance=null;class Xe{constructor(e,t){if(this.data=e,this.mimeType=t,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("string"!==typeof t)throw new TypeError("mimeType must be a string.")}}class $e{constructor(e,t,i,r){if(this.data=e,this.mimeType=t,this.name=i,this.description=r,!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if(void 0!==t&&"string"!==typeof t)throw new TypeError("mimeType, when provided, must be a string.");if(void 0!==i&&"string"!==typeof i)throw new TypeError("name, when provided, must be a string.");if(void 0!==r&&"string"!==typeof r)throw new TypeError("description, when provided, must be a string.")}}const Ge={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Qe{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(7&this.pos),r=(t&1<<i)>>i;return this.pos++,r}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i<e;i++)t<<=1,t|=this.readBit();return t}writeBits(e,t){const i=this.pos+e;for(let r=this.pos;r<i;r++){const e=Math.floor(r/8);let a=this.bytes[e];const s=7-(7&r);a&=~(1<<s),a|=(t&1<<i-r-1)>>i-r-1<<s,this.bytes[e]=a}this.pos=i}copyBits(e,t){let i=0;for(;i<e-7;i+=8)this.writeBits(8,t.readBits(8));const r=e-i;r>0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new Qe(this.bytes);return e.pos=this.pos,e}}const Ye=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Je=[-1,1,2,3,4,5,6,8],Ze=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Qe(e),i=et(t),{frequencyIndex:r,sampleRate:a}=tt(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=Je[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=tt(t).sampleRate,o=et(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===et(t)&&t.readBits(1)&&(l=tt(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(c=!!t.readBits(1)));break}t.pos=e+1}return null!==n&&n>1&&(c=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:c&&1===n?2:n}},et=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},tt=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t<Ye.length?Ye[t]:null}},it=[48e3,44100,32e3],rt=[24e3,22050,16e3];var at,st,nt,ot;(st=at||(at={}))[st.NON_IDR_SLICE=1]="NON_IDR_SLICE",st[st.SLICE_DPA=2]="SLICE_DPA",st[st.SLICE_DPB=3]="SLICE_DPB",st[st.SLICE_DPC=4]="SLICE_DPC",st[st.IDR=5]="IDR",st[st.SEI=6]="SEI",st[st.SPS=7]="SPS",st[st.PPS=8]="PPS",st[st.AUD=9]="AUD",st[st.SPS_EXT=13]="SPS_EXT",(ot=nt||(nt={}))[ot.RASL_N=8]="RASL_N",ot[ot.RASL_R=9]="RASL_R",ot[ot.BLA_W_LP=16]="BLA_W_LP",ot[ot.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",ot[ot.VPS_NUT=32]="VPS_NUT",ot[ot.SPS_NUT=33]="SPS_NUT",ot[ot.PPS_NUT=34]="PPS_NUT",ot[ot.AUD_NUT=35]="AUD_NUT",ot[ot.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",ot[ot.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const ct=function*(e){let t=0,i=-1;for(;t<e.length-2;){const r=e.indexOf(0,t);if(-1===r||r>=e.length-2)break;t=r;let a=0;t+3<e.length&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]?a=4:0===e[t+1]&&1===e[t+2]&&(a=3),0!==a?(-1!==i&&t>i&&(yield{offset:i,length:t-i}),i=t+a,t=i):t++}-1!==i&&i<e.length&&(yield{offset:i,length:e.length-i})},lt=function*(e,t){let i=0;const 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=ne(r,i,!1):(E(4===t),e=r.getUint32(i,!1)),i+=t,yield{offset:i,length:e},i+=e}},ut=(e,t)=>{if(t.description){const i=3&M(t.description)[4];return lt(e,i+1)}return ct(e)},dt=e=>31&e,ht=e=>{const t=[],i=e.length;for(let r=0;r<i;r++)r+2<i&&0===e[r]&&0===e[r+1]&&3===e[r+2]?(t.push(0,0),r+=2):t.push(e[r]);return new Uint8Array(t)},ft=new Uint8Array([0,0,0,1]),mt=e=>{const t=e.reduce((e,t)=>e+ft.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(ft,r),r+=ft.byteLength,i.set(a,r),r+=a.byteLength;return i},pt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let a=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(a,s.byteLength);break;case 2:e.setUint16(a,s.byteLength,!1);break;case 3:oe(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},gt=e=>{try{const t=[],i=[],r=[];for(const o of ct(e)){const a=e.subarray(o.offset,o.offset+o.length),s=dt(a[0]);s===at.SPS?t.push(a):s===at.PPS?i.push(a):s===at.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=wt(a);E(null!==s);const n=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:n?s.chromaFormatIdc:null,bitDepthLumaMinus8:n?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:n?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:n?r:null}}catch(t){return Ke._error("Error building AVC Decoder Configuration Record:",t),null}},kt=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}t.push(e.pictureParameterSets.length);for(const i of e.pictureParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}if((100===e.avcProfileIndication||110===e.avcProfileIndication||122===e.avcProfileIndication||144===e.avcProfileIndication)&&null!==e.chromaFormat){E(null!==e.bitDepthLumaMinus8),E(null!==e.bitDepthChromaMinus8),E(null!==e.sequenceParameterSetExt),t.push(252|3&e.chromaFormat),t.push(248|7&e.bitDepthLumaMinus8),t.push(248|7&e.bitDepthChromaMinus8),t.push(e.sequenceParameterSetExt.length);for(const i of e.sequenceParameterSetExt){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r<e;r++)t.push(i[r])}}return new Uint8Array(t)},yt=e=>{try{const t=N(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint8(i++),n=t.getUint8(i++),o=3&t.getUint8(i++),c=31&t.getUint8(i++),l=[];for(let f=0;f<c;f++){const r=t.getUint16(i,!1);i+=2,l.push(e.subarray(i,i+r)),i+=r}const u=t.getUint8(i++),d=[];for(let f=0;f<u;f++){const r=t.getUint16(i,!1);i+=2,d.push(e.subarray(i,i+r)),i+=r}const h={configurationVersion:r,avcProfileIndication:a,profileCompatibility:s,avcLevelIndication:n,lengthSizeMinusOne:o,sequenceParameterSets:l,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===a||110===a||122===a||144===a)&&i+4<=e.length){const r=3&t.getUint8(i++),a=7&t.getUint8(i++),s=7&t.getUint8(i++),n=t.getUint8(i++);h.chromaFormat=r,h.bitDepthLumaMinus8=a,h.bitDepthChromaMinus8=s;const o=[];for(let c=0;c<n;c++){const r=t.getUint16(i,!1);i+=2,o.push(e.subarray(i,i+r)),i+=r}h.sequenceParameterSetExt=o}return h}catch(t){return Ke._error("Error deserializing AVC Decoder Configuration Record:",t),null}},bt={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}},wt=e=>{try{const t=ht(e),i=new Qe(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();F(i);let n=1,o=0,c=0,l=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=F(i),3===n&&(l=i.readBits(1)),o=F(i),c=F(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==n?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,a=8;for(let e=0;e<t;e++){if(0!==a){a=(r+D(i)+256)%256}r=0===a?r:a}}}}F(i);const u=F(i);if(0===u)F(i);else if(1===u){i.skipBits(1),D(i),D(i);const e=F(i);for(let t=0;t<e;t++)D(i)}F(i),i.skipBits(1);const d=F(i),h=F(i),f=16*(d+1),m=16*(h+1);let p=f,g=m;const k=i.readBits(1);k||i.skipBits(1),i.skipBits(1);if(i.readBits(1)){const e=F(i),t=F(i),r=F(i),a=F(i);let s,o;if(0===(0===l?n:0))s=1,o=2-k;else{s=3===n?1:2,o=(1===n?2:1)*(2-k)}p-=s*(e+t),g-=o*(r+a)}let y=2,b=2,w=2,T=0,S={num:1,den:1},v=null,P=null,I=null,x=null;const C=i.pos;if(i.readBits(1)){if(i.readBits(1)){const e=i.readBits(8);if(255===e)S={num:i.readBits(16),den:i.readBits(16)};else{const t=bt[e];t&&(S=t)}}i.readBits(1)&&i.skipBits(1);if(i.readBits(1)){i.skipBits(3),T=i.readBits(1);i.readBits(1)&&(y=i.readBits(8),b=i.readBits(8),w=i.readBits(8))}i.readBits(1)&&(F(i),F(i));i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.skipBits(1));const e=i.readBits(1);e&&Tt(i);const t=i.readBits(1);t&&Tt(i),(e||t)&&i.skipBits(1),i.skipBits(1),I=i.pos,x=i.readBits(1),x&&(i.skipBits(1),F(i),F(i),F(i),F(i),v=F(i),P=F(i))}if(null===v){E(null===P);if(44!==r&&86!==r&&100!==r&&110!==r&&122!==r&&244!==r||!(16&a)){const e=d+1,t=(2-k)*(h+1),i=ki.find(e=>e.level>=s)??R(ki),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);v=r,P=r}else v=0,P=0}return E(null!==P),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:S,colourPrimaries:y,matrixCoefficients:w,transferCharacteristics:b,fullRangeFlag:T,numReorderFrames:v,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:C,bitstreamRestrictionFlagBitOffset:I,bitstreamRestrictionFlag:x}}catch(t){return Ke._error("Error parsing AVC SPS:",t),null}},Tt=e=>{const t=F(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)F(e),F(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},St=e=>{E(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Qe(e.emulationUnpreventedBytes),r=new Qe(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(E(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),A(r,2),A(r,1),A(r,16),A(r,16),A(r,e.numReorderFrames),A(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return E(Number.isInteger(a)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,a))},vt=(e,t)=>{if(t.description){const i=3&M(t.description)[21];return lt(e,i+1)}return ct(e)},Pt=e=>e>>1&63,It=e=>{try{const t=new Qe(ht(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Ct(t,i);F(t);const u=F(t);let d=0;3===u&&(d=t.readBits(1));const h=F(t),f=F(t);let m=h,p=f;if(t.readBits(1)){const e=F(t),i=F(t),r=F(t),a=F(t);let s=1,n=1;const o=0===d?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),m-=(e+i)*s,p-=(r+a)*n}const g=F(t),k=F(t);F(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)F(t),b=F(t),F(t);F(t),F(t),F(t),F(t),F(t),F(t),t.readBits(1)&&t.readBits(1)&&Bt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),F(t),F(t),t.skipBits(1));const w=F(t);if(Et(t,w),t.readBits(1)){const e=F(t);for(let i=0;i<e;i++)F(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let T=2,S=2,v=2,P=0,I=0,x={num:1,den:1};if(t.readBits(1)){const e=Rt(t,i);x=e.pixelAspectRatio,T=e.colourPrimaries,S=e.transferCharacteristics,v=e.matrixCoefficients,P=e.fullRangeFlag,I=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:p,pixelAspectRatio:x,colourPrimaries:T,transferCharacteristics:S,matrixCoefficients:v,fullRangeFlag:P,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:a,generalTierFlag:s,generalProfileIdc:n,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:c,generalLevelIdc:l,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:k,minSpatialSegmentationIdc:I}}catch(t){return Ke._error("Error parsing HEVC SPS:",t),null}},xt=e=>{try{const t=[],i=[],r=[],a=[];for(const c of ct(e)){const s=e.subarray(c.offset,c.offset+c.length),n=Pt(s[0]);n===nt.VPS_NUT?t.push(s):n===nt.SPS_NUT?i.push(s):n===nt.PPS_NUT?r.push(s):n!==nt.PREFIX_SEI_NUT&&n!==nt.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=It(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new Qe(ht(e));t.skipBits(16),F(t),F(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),F(t),F(t),D(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&F(t),D(t),D(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType:nt.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:nt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:nt.PPS_NUT,nalUnits:r}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Pt(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:n,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return Ke._error("Error building HEVC Decoder Configuration Record:",t),null}},Ct=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let u=0;u<6;u++)n[u]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let u=0;u<t;u++)c.push(e.readBits(1)),l.push(e.readBits(1));if(t>0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u<t;u++)c[u]&&e.skipBits(88),l[u]&&e.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:a,general_profile_compatibility_flags:s,general_constraint_indicator_flags:n,general_level_idc:o}},Bt=e=>{for(let t=0;t<4;t++)for(let i=0;i<(3===t?2:6);i++){if(e.readBits(1)){const i=Math.min(64,1<<4+(t<<1));t>1&&D(e);for(let t=0;t<i;t++)D(e)}else F(e)}},Et=(e,t)=>{const i=[];for(let r=0;r<t;r++)i[r]=_t(e,r,t,i)},_t=(e,t,i,r)=>{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){if(t===i){n=t-(F(e)+1)}else n=t-1;e.readBits(1),F(e);const s=r[n]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=r[n]}else{const t=F(e),i=F(e);for(let r=0;r<t;r++)F(e),e.readBits(1);for(let r=0;r<i;r++)F(e),e.readBits(1);a=t+i}return a},Rt=(e,t)=>{let i=2,r=2,a=2,s=0,n=0,o={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{const e=bt[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)&&(F(e),F(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(F(e),F(e),F(e),F(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&F(e),e.readBits(1)&&Ft(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=F(e),F(e),F(e),F(e),F(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},Ft=(e,t,i)=>{let r=!1,a=!1,s=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?F(e):i=1===e.readBits(1);let n=1;if(!i){n=F(e)+1}r&&At(e,n,s),a&&At(e,n,s)}},At=(e,t,i)=>{for(let r=0;r<t;r++)F(e),F(e),i&&(F(e),F(e)),e.readBits(1)};var Dt,Mt;(Mt=Dt||(Dt={}))[Mt.audAllowed=0]="audAllowed",Mt[Mt.beforeFirstVcl=1]="beforeFirstVcl",Mt[Mt.afterFirstVcl=2]="afterFirstVcl",Mt[Mt.eoBitstreamAllowed=3]="eoBitstreamAllowed",Mt[Mt.noMoreDataAllowed=4]="noMoreDataAllowed";const Nt=(e,t)=>{const i=new Set;let r=Dt.audAllowed;for(const s of vt(e,t)){if(r===Dt.noMoreDataAllowed){i.add(s.offset);continue}const t=Pt(e[s.offset]);if(r===Dt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>Dt.audAllowed?a=!0:r=Dt.beforeFirstVcl:t<=31?r>Dt.afterFirstVcl?a=!0:r=Dt.afterFirstVcl:36===t?r!==Dt.afterFirstVcl?a=!0:r=Dt.eoBitstreamAllowed:37===t?r<Dt.afterFirstVcl?a=!0:r=Dt.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?r>Dt.beforeFirstVcl?a=!0:r=Dt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r<Dt.afterFirstVcl&&(a=!0),a&&i.add(s.offset)}if(0===i.size)return null;const a=[];for(const s of vt(e,t))i.has(s.offset)||a.push(e.subarray(s.offset,s.offset+s.length));return((e,t)=>{if(t.description){const i=3&M(t.description)[21];return pt(e,i+1)}return mt(e)})(a,t)},Ot={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},zt=e=>{const t=new Qe(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(r>=2){a=t.readBits(1)?12:10}const s=t.readBits(3);let n=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);n=e||i?e&&!i?2:1:3,t.skipBits(1)}else n=1}else n=3,o=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let l=R(yi).level;for(const d of yi)if(c<=d.maxPictureSize){l=d.level;break}const u=Ot[s];return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:u?.colourPrimaries??2,transferCharacteristics:u?.transferCharacteristics??2,matrixCoefficients:u?.matrixCoefficients??2}},Lt=function*(e){const t=new Qe(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*2**(7*i),!(128&r))break;if(7===i&&128&r)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),a=t.readBits(1),s=t.readBits(1);let n;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;n=e}else n=Math.floor(t.getBitsLeft()/8);E(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},Ut=e=>{for(const{type:t,data:i}of Lt(e)){if(1!==t)continue;const e=new Qe(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const d=l+1;e.skipBits(d);let h=0;if(h=a?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},qt=e=>{if(e.length<36)return null;const t=N(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},Wt=[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],Ht=e=>{if(e.length<7)throw new Error("Setup header is too short.");if(5!==e[0])throw new Error("Wrong packet type in Setup header.");if("vorbis"!==String.fromCharCode(...e.slice(1,7)))throw new Error("Invalid packet signature in Setup header.");const t=e.length,i=new Uint8Array(t);for(let u=0;u<t;u++)i[u]=e[t-1-u];const r=new Qe(i);let a=0;for(;r.getBitsLeft()>97;)if(1===r.readBits(1)){a=r.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;r.getBitsLeft()>=97;){const e=r.pos,t=r.readBits(8),i=r.readBits(16),a=r.readBits(16);if(t>63||0!==i||0!==a){r.pos=e;break}if(r.skipBits(1),s++,s>64)break;r.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;r.pos=0,r.skipBits(a);const l=Array(c).fill(0);for(let u=c-1;u>=0;u--)r.skipBits(40),l[u]=r.readBits(1);return{modeBlockflags:l}},Vt=(e,t,i)=>{switch(e){case"avc":for(const e of ut(i,t)){const t=i[e.offset],r=dt(t);if(r>=at.NON_IDR_SLICE&&r<=at.SLICE_DPC)return"delta";if(r===at.IDR)return"key";if(r===at.SEI&&!Be()){const t=i.subarray(e.offset,e.offset+e.length),r=ht(t);let a=1;do{let e=0;for(;;){const t=r[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new Qe(r);e.pos=8*a;const t=F(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a<r.length-1)}}return"delta";case"hevc":for(const e of vt(i,t)){const t=Pt(i[e.offset]);if(t<nt.BLA_W_LP)return"delta";if(t<=nt.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 0===(1&i[0])?"key":"delta";case"vp9":{const e=new Qe(i);if(2!==e.readBits(2))return null;const t=e.readBits(1);3===(e.readBits(1)<<1)+t&&e.skipBits(1);if(e.readBits(1))return null;return 0===e.readBits(1)?"key":"delta"}case"av1":{let e=!1;for(const{type:t,data:r}of Lt(i))if(1===t){const t=new Qe(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new Qe(r);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}case"prores":return"key";default:se(e),E(!1)}};var jt,Kt;(Kt=jt||(jt={}))[Kt.STREAMINFO=0]="STREAMINFO",Kt[Kt.VORBIS_COMMENT=4]="VORBIS_COMMENT",Kt[Kt.PICTURE=6]="PICTURE";const Xt=(e,t)=>{var i,r;const a=N(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=O.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(i=t.raw).vendor??(i.vendor=o));const c=a.getUint32(s,!0);s+=4;for(let l=0;l<c;l++){const i=a.getUint32(s,!0);s+=4;const n=O.decode(e.subarray(s,s+i));s+=i;const o=n.indexOf("=");if(-1===o)continue;const c=n.slice(0,o).toUpperCase(),l=n.slice(o+1);switch(t.raw??(t.raw={}),Array.isArray(t.raw[c])?t.raw[c]=[...t.raw[c],l]:"string"===typeof t.raw[c]?t.raw[c]=[t.raw[c],l]:(r=t.raw)[c]??(r[c]=l),c){case"TITLE":t.title??(t.title=l);break;case"DESCRIPTION":t.description??(t.description=l);break;case"ARTIST":t.artist??(t.artist=l);break;case"ALBUM":t.album??(t.album=l);break;case"ALBUMARTIST":t.albumArtist??(t.albumArtist=l);break;case"COMMENT":t.comment??(t.comment=l);break;case"LYRICS":t.lyrics??(t.lyrics=l);break;case"TRACKNUMBER":{const e=l.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=l.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.discNumber??(t.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??(t.discsTotal=r))}break;case"DISCTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(l);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=l);break;case"METADATA_BLOCK_PICTURE":{const e=De(l),i=N(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=O.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),u=e.subarray(a+n+32,a+n+32+c);t.images??(t.images=[]),t.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},$t=[2,1,2,3,3,4,4,5],Gt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Qe(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),a=t.readBits(5);if(a>8)return null;const s=t.readBits(3),n=t.readBits(3);0!==(1&n)&&1!==n&&t.skipBits(2),0!==(4&n)&&t.skipBits(2),2===n&&t.skipBits(2);return{fscod:i,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Qt=[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],Yt=[1,2,3,6],Jt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Qe(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),a=t.readBits(2);let s,n=0;3===a?(n=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;const u=Yt[s];let d;d=a<3?it[a]/1e3:rt[n]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},Zt=e=>{const t=e.substreams[0];return E(t),t.fscod<3?it[t.fscod]:null!==t.fscod2&&t.fscod2<3?rt[t.fscod2]:null},ei=e=>{const t=e.substreams[0];E(t);let i=$t[t.acmod]+t.lfeon;if(t.numDepSub>0){const 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},ti=[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],ri=[16,16,20,20,0,24,24,0],ai=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],si=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],ni=[32e3,44100,48e3,0],oi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],ci=[512,1024,2048,4096],li=e=>{const t=di(e),i=N(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=hi(e.subarray(r));if(!t)break;a??(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;const{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}},ui=e=>{const t=li(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},di=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new Qe(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const a=t.readBits(14)+1;if(a<96)return null;const s=t.readBits(6);if(s>=ai.length)return null;const n=ti[t.readBits(4)];if(0===n)return null;const o=ii[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const c=t.readBits(2);if(3===c)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const l=ri[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:ai[s]+(u?1:0),sampleCount:32*r,channelLayout:si[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},hi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new Qe(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),a=8+4*r,s=16+4*r;t.skipBits(a);const n=t.readBits(s)+1,o={frameSize:n,asset:null};if(!t.readBits(1))return o;const c=ni[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;k<u;k++)h.push(t.readBits(i+1));for(const k of h)t.skipBits(8*pe(k));if(t.readBits(1)){t.skipBits(2);const e=t.readBits(2)+1<<2,i=t.readBits(2)+1;t.skipBits(i*e)}for(let k=0;k<d;k++)t.skipBits(s);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));const f=t.readBits(5)+1,m=oi[t.readBits(4)],p=t.readBits(8)+1;let g=0;if(t.readBits(1)&&(p>2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===c||t.getBitsLeft()<0?o:{frameSize:n,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:f}}},fi=e=>pe(e)+pe(44646&e),mi=["avc","hevc","vp9","av1","vp8","prores"],pi=["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"],gi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...pi],ki=[{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}],yi=[{maxPictureSize:36864,maxBitrate:2e5,level:10},{maxPictureSize:73728,maxBitrate:8e5,level:11},{maxPictureSize:122880,maxBitrate:18e5,level:20},{maxPictureSize:245760,maxBitrate:36e5,level:21},{maxPictureSize:552960,maxBitrate:72e5,level:30},{maxPictureSize:983040,maxBitrate:12e6,level:31},{maxPictureSize:2228224,maxBitrate:18e6,level:40},{maxPictureSize:2228224,maxBitrate:3e7,level:41},{maxPictureSize:8912896,maxBitrate:6e7,level:50},{maxPictureSize:8912896,maxBitrate:12e7,level:51},{maxPictureSize:8912896,maxBitrate:18e7,level:52},{maxPictureSize:35651584,maxBitrate:18e7,level:60},{maxPictureSize:35651584,maxBitrate:24e7,level:61},{maxPictureSize:35651584,maxBitrate:48e7,level:62}],bi=".01.01.01.01.00",wi=".0.110.01.01.01.0",Ti=["ap4x","ap4h","apch","apcn","apcs","apco"],Si=["dtsc","dtsh","dtsl","dtse"],vi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o,proresFormat:c}=e;if("avc"===t){if(E(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${Q(t)}`}if(!i||i.byteLength<4)throw new TypeError("AVC decoder description is not provided or is not at least 4 bytes long.");return`avc${e.avcType}.${Q(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=Y(s.generalProfileCompatibilityFlags),a=s.generalTierFlag,n=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=N(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=Y(s.getUint32(2)),a=c>>5&1,n=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=r.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=n;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!n){const t=e.width*e.height;let i=R(yi).level;for(const e of yi)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${n.profile.toString().padStart(2,"0")}.${n.level.toString().padStart(2,"0")}.${n.bitDepth.toString().padStart(2,"0")}.${n.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${n.colourPrimaries.toString().padStart(2,"0")}.${n.transferCharacteristics.toString().padStart(2,"0")}.${n.matrixCoefficients.toString().padStart(2,"0")}.${n.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(bi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=R(yi).level;for(const e of yi)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),a=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),n=o.monochrome?"1":"0",c=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),l=r?.primaries?L[r.primaries]:1,u=r?.transfer?q[r.transfer]:1,d=r?.matrix?H[r.matrix]:1,h=r?.fullRange?1:0;let f=`av01.${t}.${i}${a}.${s}`;return f+=`.${n}.${c.toString().padStart(3,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,f+=`.${h}`,f.endsWith(wi)&&(f=f.slice(0,-17)),f}if("prores"===t)return c??"apch";throw null!==t&&se(t),new TypeError(`Unhandled codec '${t}'.`)},Pi=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=yt(e.codecDescription)?.sequenceParameterSets[0]),t){const e=wt(t);if(e)return{primaries:U[e.colourPrimaries],transfer:W[e.transferCharacteristics],matrix:V[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===nt.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=N(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,w=k>>2&1,T=3&k,S=t.getUint8(i++),v=[];for(let P=0;P<S;P++){const r=t.getUint8(i++),a=r>>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;c<n;c++){const r=t.getUint16(i,!1);i+=2,o.push(e.subarray(i,i+r)),i+=r}v.push({arrayCompleteness:a,nalUnitType:s,nalUnits:o})}return{configurationVersion:r,generalProfileSpace:s,generalTierFlag:n,generalProfileIdc:o,generalProfileCompatibilityFlags:c,generalConstraintIndicatorFlags:l,generalLevelIdc:u,minSpatialSegmentationIdc:d,parallelismType:h,chromaFormatIdc:f,bitDepthLumaMinus8:m,bitDepthChromaMinus8:p,avgFrameRate:g,constantFrameRate:y,numTemporalLayers:b,temporalIdNested:w,lengthSizeMinusOne:T,arrays:v}}catch(t){return Ke._error("Error deserializing HEVC Decoder Configuration Record:",t),null}})(e.codecDescription)?.arrays.find(e=>e.nalUnitType===nt.SPS_NUT)?.nalUnits[0]),t){const e=It(t);if(e)return{primaries:U[e.colourPrimaries],transfer:W[e.transferCharacteristics],matrix:V[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:U[e.vp9CodecInfo.colourPrimaries],transfer:W[e.vp9CodecInfo.transferCharacteristics],matrix:V[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:U[e.av1CodecInfo.colourPrimaries],transfer:W[e.av1CodecInfo.transferCharacteristics],matrix:V[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:U[e.proresCodecInfo.colourPrimaries],transfer:W[e.proresCodecInfo.transferCharacteristics],matrix:V[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},Ii=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=Ze(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return a??"dtsc";if(t&&pi.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},xi=48e3,Ci=/^pcm-([usf])(\d+)(be)?$/,Bi=e=>{if(E(pi.includes(e)),"ulaw"===e)return{dataType:"ulaw",sampleSize:1,littleEndian:!0,silentValue:255};if("alaw"===e)return{dataType:"alaw",sampleSize:1,littleEndian:!0,silentValue:213};const t=Ci.exec(e);let i;E(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},Ei=e=>e.startsWith("avc1")||e.startsWith("avc3")?"avc":e.startsWith("hev1")||e.startsWith("hvc1")?"hevc":"vp8"===e?"vp8":e.startsWith("vp09")?"vp9":e.startsWith("av01")?"av1":Ti.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":Si.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ci.test(e)?e:"webvtt"===e?"webvtt":null,_i=[44100,48e3,32e3],Ri=[-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],Fi=1483304551,Ai=1231971951,Di=(e,t)=>3===e?3===t?21:36:3===t?13:21,Mi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Ri[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=_i[u]>>n+o,b=((e,t,i,r,a)=>0===t?0:1===t?Math.floor(144*i/(r<<e))+a:2===t?Math.floor(144*i/r)+a:4*(Math.floor(12*i/r)+a))(n,l,k,y,a>>1&1);if(null!==t&&t<b)return{header:null,bytesAdvanced:1};let w;return w=3===c?3===l?384:1152:3===l?384:2===l?1152:576,{header:{totalSize:b,mpegVersionId:c,lowSamplingFrequency:n,layer:l,bitrate:k,frequencyIndex:u,sampleRate:y,channel:d,modeExtension:h,copyright:f,original:m,emphasis:p,audioSamplesInFrame:w},bytesAdvanced:1}},Ni=e=>{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Oi,zi;(zi=Oi||(Oi={}))[zi.FrameCount=1]="FrameCount",zi[zi.FileSize=2]="FileSize",zi[zi.Toc=4]="Toc";const Li=e=>3===e?1:2;class Ui{constructor(e){this.input=e}dispose(){}}const qi=new Uint8Array(0);class Wi{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===qi&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!==typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===qi}get microsecondTimestamp(){return Math.trunc(ye*this.timestamp)}get microsecondDuration(){return Math.trunc(ye*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new Wi(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 new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new Wi(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)}}const Hi=e=>{const t=N(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=Q(e.subarray(i,i+16));i+=16;let s=null;if(r>0){const r=t.getUint32(i);if(i+=4,r>0){s=[];for(let t=0;t<r;t++)s.push(Q(e.subarray(i,i+16))),i+=16}}const n=t.getUint32(i);return i+=4,{systemId:a,keyIds:s,data:e.slice(i,i+n)}},Vi=(e,t)=>e.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i<e.length;i++)if(e[i]!==t[i])return!1;return!0})(e.data,t.data),ji=e=>{let t=$o(e);const i=rc(e,4);let r=8;1===t&&(t=Jo(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},Ki=e=>Qo(e)/65536,Xi=e=>Qo(e)/1073741824,$i=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=Wo(e);if(t|=127&i,0===(128&i))break}return t},Gi=e=>{let t=Vo(e);return e.skip(2),t=Math.min(t,e.remainingLength),O.decode(qo(e,t))},Qi=e=>{const t=ji(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=$o(e);e.skip(4);const r=qo(e,t.contentSize-8);switch(i){case 1:return O.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new Xe(r,"image/jpeg");case 14:return new Xe(r,"image/png");case 27:return new Xe(r,"image/bmp");default:return r}},Yi=16,Ji=new Uint32Array(256),Zi=new Uint32Array(256),er=new Uint32Array(256),tr=new Uint32Array(256),ir=new Uint32Array(256),rr=new Uint32Array(256),ar=new Uint32Array(10);let sr=!1;class nr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Yi/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Yi),this.out=new Uint8Array(Yi),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){E(16===e.byteLength),E(16===t.byteLength),sr||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,n=1;s<256;s++)i[s]=n,t[n]=s,n=n^n<<1^(128&n?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let a=r^r<<1^r<<2^r<<3^r<<4;a=a>>>8^255&a^99,e[s]=a}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);Ji[s]=t<<24|t<<16|t<<8|t,rr[s]=i<<24|i<<16|i<<8|i;const a=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);Zi[s]=a,er[s]=a>>>8|a<<24,tr[s]=a>>>16|a<<16,ir[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)ar[s]=a<<24,a=a<<1^(128&a?283:0);sr=!0})();const 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 a=4;a<44;a+=4){const e=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^4278190080&Ji[e>>>16&255]^16711680&Ji[e>>>8&255]^65280&Ji[e>>>0&255]^255&Ji[e>>>24&255]^ar[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a<s;a+=4,s-=4)for(let e=0;e<4;e++){const t=this.roundkey[a+e];this.roundkey[a+e]=this.roundkey[s+e],this.roundkey[s+e]=t}for(let a=4;a<40;a+=4)for(let e=0;e<4;e++){const t=this.roundkey[a+e];this.roundkey[a+e]=Zi[255&Ji[t>>>24&255]]^er[255&Ji[t>>>16&255]]^tr[255&Ji[t>>>8&255]]^ir[255&Ji[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,d;for(let g=1;g<10;g++){const a=4*g;c=Zi[e>>>24]^er[r>>>16&255]^tr[i>>>8&255]^ir[255&t]^this.roundkey[a],l=Zi[t>>>24]^er[e>>>16&255]^tr[r>>>8&255]^ir[255&i]^this.roundkey[a+1],u=Zi[i>>>24]^er[t>>>16&255]^tr[e>>>8&255]^ir[255&r]^this.roundkey[a+2],d=Zi[r>>>24]^er[i>>>16&255]^tr[t>>>8&255]^ir[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=d}const h=4278190080&rr[e>>>24&255]^16711680&rr[r>>>16&255]^65280&rr[i>>>8&255]^255&rr[t>>>0&255]^this.roundkey[40],f=4278190080&rr[t>>>24&255]^16711680&rr[e>>>16&255]^65280&rr[r>>>8&255]^255&rr[i>>>0&255]^this.roundkey[41],m=4278190080&rr[i>>>24&255]^16711680&rr[t>>>16&255]^65280&rr[e>>>8&255]^255&rr[r>>>0&255]^this.roundkey[42],p=4278190080&rr[r>>>24&255]^16711680&rr[i>>>16&255]^65280&rr[t>>>8&255]^255&rr[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,h^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class or extends Ui{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Re(r)&&(r=await r),!r)break;const a=e,s=ji(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=rc(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Re(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>a+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');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){E(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Re(e)&&(e=await e),E(e);const t=$o(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Re(e)&&(e=await e),e){const t=ji(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Re(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==or)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const i of t.tracks){const e={id:i.id,demuxer:this,trackBacking:null,disposition:i.disposition,timescale:i.timescale,durationInMediaTimescale:i.durationInMediaTimescale,durationInMovieTimescale:i.durationInMovieTimescale,rotation:i.rotation,internalCodecId:i.internalCodecId,name:i.name,languageCode:i.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:i.editListPreviousSegmentDurations,editListOffset:i.editListOffset,encryptionInfo:i.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:i.info};if(i.trackBacking)if(E(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new lr(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new ur(t),this.tracks.push(e)}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,null===e.sampleTableByteOffset)return t;E(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(i),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&pi.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){E("audio"===e.info?.type);const i=Bi(e.info.codec),r=[],a=[];for(let s=0;s<t.sampleToChunk.length;s++){const n=t.sampleToChunk[s],o=t.sampleToChunk[s+1],c=(o?o.startChunkIndex:t.chunkOffsets.length)-n.startChunkIndex;for(let s=0;s<c;s++){const o=n.startSampleIndex+s*n.samplesPerChunk,c=o+n.samplesPerChunk,l=Z(t.sampleTimingEntries,o,e=>e.startIndex),u=t.sampleTimingEntries[l],d=Z(t.sampleTimingEntries,c,e=>e.startIndex),h=t.sampleTimingEntries[d],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=h.startDecodeTimestamp+(c-h.startIndex)*h.delta-f,p=R(r);p&&p.delta===m?p.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:f,count:1,delta:m});const g=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(g)}n.startSampleIndex=n.startChunkIndex,n.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let i=0;i<e.count;i++)t.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+i*e.delta,sampleIndex:e.startIndex+i});for(const e of t.sampleCompositionTimeOffsets)for(let i=0;i<e.count;i++){const r=e.startIndex+i,a=t.presentationTimestamps[r];a&&(a.presentationTimestamp+=e.offset)}t.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;e<t.presentationTimestamps.length;e++)t.presentationTimestampIndexMap[t.presentationTimestamps[e].sampleIndex]=e}return t}async readFragment(e){if(this.lastReadFragment?.moofOffset===e)return this.lastReadFragment;let t=this.reader.requestSliceRange(e,8,16);Re(t)&&(t=await t),E(t);const i=ji(t);E("moof"===i?.name);let r=this.reader.requestSlice(e,i.totalSize);Re(r)&&(r=await r),E(r),this.traverseBox(r);const a=this.lastReadFragment;E(a&&a.moofOffset===e);for(const[,s]of a.trackData){const e=s.track,{fragmentPositionCache:t}=e;if(!s.startTimestampIsFinal){const i=e.fragmentLookupTable.find(e=>e.moofOffset===a.moofOffset);if(i)pr(s,i.timestamp);else{const e=Z(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];pr(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=Z(t,s.startTimestamp,e=>e.startTimestamp);if(-1!==i&&t[i].moofOffset===a.moofOffset||t.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:s.startTimestamp,endTimestamp:s.endTimestamp}),s.encryptionAuxInfo&&e.encryptionInfo){const t=await br(this.reader,e.encryptionInfo,s.encryptionAuxInfo);for(let e=0;e<Math.min(s.samples.length,t.length);e++){const i=t[e];s.samples[e].encryption=i}}}return a}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){if(!this.traverseBox(e))break}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,i=ji(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=t+i.totalSize}}traverseBox(e){var t,i,r,a,s,n,o,c,l,u,d,h,f,m,p,g,k,y,b,w,T,S,v,P,I,x,C,B,F,A,D,M,z;const L=e.filePos,q=ji(e);if(!q)return!1;const H=e.filePos,j=L+q.totalSize;switch(q.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":case"wave":this.readContiguousBoxes(e.slice(H,q.contentSize));break;case"mvhd":{const t=Wo(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=$o(e),this.movieDurationInTimescale=Jo(e)):(e.skip(8),this.movieTimescale=$o(e),this.movieDurationInTimescale=$o(e))}break;case"trak":{const t={id:-1,demuxer:this,trackBacking:null,disposition:{...Ge,primary:!1},info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:ue,sampleTableByteOffset:-1,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:0,editListOffset:0,encryptionInfo:null,encryptionAuxInfo:null,frmaCodecString:null};if(this.currentTrack=t,this.readContiguousBoxes(e.slice(H,q.contentSize)),-1!==t.id&&-1!==t.timescale&&null!==t.info)if("video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new lr(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new ur(e),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const i=Wo(e),r=!!(1&jo(e));if(t.disposition.default=r,0===i)e.skip(8),t.id=$o(e),e.skip(4),t.durationInMovieTimescale=$o(e);else{if(1!==i)throw new Error(`Incorrect track header version ${i}.`);e.skip(16),t.id=$o(e),e.skip(4),t.durationInMovieTimescale=Jo(e)}e.skip(16);const a=[Ki(e),Ki(e),Xi(e),Ki(e),Ki(e),Xi(e),Ki(e),Ki(e),Xi(e)],s=_(he(gr(a),90));E(0===s||90===s||180===s||270===s),t.rotation=s}break;case"elst":{const t=this.currentTrack;if(!t)break;const i=Wo(e);e.skip(3);let r=!1,a=0;const s=$o(e);for(let n=0;n<s;n++){const s=1===i?Jo(e):$o(e),n=1===i?Zo(e):Qo(e),o=Ki(e);if(r){Ke._warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==n){if(1!==o){Ke._warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=a,t.editListOffset=n,r=!0}else a+=s}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const i=Wo(e);e.skip(3),0===i?(e.skip(8),t.timescale=$o(e),t.durationInMediaTimescale=$o(e)):1===i&&(e.skip(16),t.timescale=$o(e),t.durationInMediaTimescale=Jo(e));let r=Vo(e);if(r>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;ke(t.languageCode)||(t.languageCode=ue)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=rc(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...K},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo: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":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=L,this.readContiguousBoxes(e.slice(H,q.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=Wo(e);e.skip(3);const r=$o(e);for(let a=0;a<r;a++){const r=e.filePos,a=ji(e);if(!a)break;t.internalCodecId=a.name;const s=a.name.toLowerCase();if("video"===t.info.type){e.skip(24),t.info.width=Vo(e),t.info.height=Vo(e),t.info.squarePixelWidth=t.info.width,t.info.squarePixelHeight=t.info.height,e.skip(50),t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const i="encv"===s?t.frmaCodecString:s;t.frmaCodecString=null,"avc1"===i||"avc3"===i?(t.info.codec="avc",t.info.avcType="avc1"===i?1:3):"hvc1"===i||"hev1"===i?t.info.codec="hevc":"vp08"===i?t.info.codec="vp8":"vp09"===i?t.info.codec="vp9":"av01"===i?t.info.codec="av1":Ti.includes(s)?(t.info.codec="prores",t.info.proresFormat=s):null===i?Ke._warn("Unknown encrypted video codec due to missing frma box."):Ke._warn(`Unsupported video codec (sample entry type '${a.name}').`)}else{e.skip(8);const n=Vo(e);e.skip(6);let o=Vo(e),c=Vo(e);e.skip(4);let l=$o(e)/65536,u=null;0===i&&n>0&&(1===n?(e.skip(4),c=8*$o(e),e.skip(8)):2===n&&(e.skip(4),l=ic(e),o=$o(e),e.skip(4),c=$o(e),u=$o(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const d="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===d);else if("opus"===d)t.info.codec="opus",t.info.sampleRate=xi;else if("flac"===d)t.info.codec="flac";else if("ulaw"===d)t.info.codec="ulaw";else if("alaw"===d)t.info.codec="alaw";else if("ac-3"===d)t.info.codec="ac3";else if("ec-3"===d)t.info.codec="eac3";else if(Si.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Ke._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(Ke._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?16===e?t.info.codec="pcm-s16":24===e?t.info.codec="pcm-s24":32===e?t.info.codec="pcm-s32":(Ke._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":(Ke._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===d){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(Ke._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(Ke._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<<e-1?1===e?t.info.codec="pcm-s8":2===e?t.info.codec=r?"pcm-s16be":"pcm-s16":3===e?t.info.codec=r?"pcm-s24be":"pcm-s24":4===e&&(t.info.codec=r?"pcm-s32be":"pcm-s32"):1===e&&(t.info.codec="pcm-u8")),null===t.info.codec&&Ke._warn("Unsupported PCM format.")}else null===d?Ke._warn("Unknown encrypted audio codec due to missing frma box."):Ke._warn(`Unsupported audio codec (sample entry type '${a.name}').`)}e.filePos=r+a.totalSize}}break;case"frma":{const t=this.currentTrack;if(!t)break;const i=rc(e,4).toLowerCase();t.frmaCodecString=i}break;case"schm":{const t=this.currentTrack;if(!t)break;e.skip(4);const i=rc(e,4);"cenc"===i||"cens"===i||"cbcs"===i?t.encryptionInfo={scheme:i,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:Ke._warn(`Unsupported encryption scheme '${i}'.`)}break;case"tenc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Wo(e);e.skip(3),e.skip(1);const r=Wo(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!==Wo(e),t.encryptionInfo.defaultPerSampleIvSize=Wo(e),t.encryptionInfo.defaultKid=Q(qo(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=Wo(e),r=new Uint8Array(16);r.set(qo(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(E(t.info),0===q.contentSize)break;t.info.codecDescription=qo(e,q.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(E(t.info),0===q.contentSize)break;t.info.codecDescription=qo(e,q.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;E("video"===t.info?.type),e.skip(4);const i=Wo(e),r=Wo(e),a=Wo(e),s=a>>4,n=a>>1&7,o=1&a,c=Wo(e),l=Wo(e),u=Wo(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case"av1C":{const t=this.currentTrack;if(!t)break;E("video"===t.info?.type),e.skip(1);const i=Wo(e),r=i>>5,a=31&i,s=Wo(e),n=s>>7,o=s>>6&1,c=s>>4&1,l=s>>3&1,u=s>>2&1,d=3&s,h=2===r&&o?s>>5&1?12:10:o?10:8;e.skip(1);const f=qo(e,q.contentSize-4),m=Ut(f);t.info.av1CodecInfo={profile:r,level:a,tier:n,bitDepth:h,monochrome:c,chromaSubsamplingX:l,chromaSubsamplingY:u,chromaSamplePosition:d,videoFullRangeFlag:m?.videoFullRangeFlag??0,colourPrimaries:m?.colourPrimaries??2,transferCharacteristics:m?.transferCharacteristics??2,matrixCoefficients:m?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;E("video"===t.info?.type);const i=rc(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Vo(e),a=Vo(e),s=Vo(e);let n;"nclx"===i&&(n=Boolean(128&Wo(e))),t.info.colorSpace={primaries:U[r],transfer:W[a],matrix:V[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;E("video"===t.info?.type);const i=$o(e),r=$o(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":{const t=this.currentTrack;if(!t||"audio"!==t.info?.type)break;e.skip(4);E(3===Wo(e)),$i(e),e.skip(2);const i=Wo(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=Wo(e);e.skip(t)}a&&e.skip(2);E(4===Wo(e));const s=$i(e),n=e.filePos,o=Wo(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":Ke._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-n){E(5===Wo(e));const i=$i(e);if(t.info.codecDescription=qo(e,i),"aac"===t.info.codec){const e=Ze(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;E("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&Vo(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;E("audio"===t.info?.type),e.skip(4);const i=Wo(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=Wo(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;E("audio"===t.info?.type),e.skip(1);const i=Wo(e),r=Vo(e),a=$o(e),s=Ko(e),n=Wo(e);let o;o=0!==n?qo(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,i),l.setUint16(10,r,!0),l.setUint32(12,a,!0),l.setInt16(16,s,!0),l.setUint8(18,n),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;E("audio"===t.info?.type),e.skip(4);const i=127,r=128,a=e.filePos;for(;e.filePos<j;){const a=Wo(e),s=jo(e);if((a&i)===jt.STREAMINFO){e.skip(10);const i=$o(e),r=i>>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(a&r)break}const s=e.filePos;e.filePos=a;const n=qo(e,s-a),o=new Uint8Array(4+n.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(n,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;E("audio"===t.info?.type);const i=qo(e,3),r=new Qe(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=it[a]),t.info.numberOfChannels=$t[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;E("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new Qe(e),i=t.readBits(13),r=t.readBits(3),a=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),n=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let c=0;o>0?c=t.readBits(9):t.skipBits(1),a.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:n,numDepSub:o,chanLoc:c})}return 0===a.length?null:{dataRate:i,substreams:a}})(qo(e,q.contentSize));if(!i){Ke._warn("Invalid dec3 box contents, ignoring.");break}const r=Zt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=ei(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;E("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=N(e),i=t.getUint32(0);if(0===i)return null;const r=new Qe(e);r.seekToByte(13);const a=r.readBits(2);r.skipBits(5);const s=r.readBits(1),n=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return 0!==o?c=fi(o):n<ai.length&&(c=ai[n]+s),{sampleRate:i,maxBitrate:t.getUint32(4),avgBitrate:t.getUint32(8),pcmSampleDepth:e[12],sampleCount:ci[a],channelLayout:o,numberOfChannels:c}})(qo(e,Math.min(q.contentSize,20)));if(!i){Ke._warn("Invalid ddts box contents, ignoring.");break}t.info.sampleRate=i.sampleRate,null!==i.numberOfChannels&&(t.info.numberOfChannels=i.numberOfChannels)}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=$o(e);let r=0,a=0;for(let s=0;s<i;s++){const i=$o(e),s=$o(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:a,count:i,delta:s}),r+=i,a+=i*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=$o(e);let r=0;for(let a=0;a<i;a++){const i=$o(e),a=Qo(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:i,offset:a}),r+=i}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=$o(e),r=$o(e);if(0===i)for(let a=0;a<r;a++){const i=$o(e);t.sampleTable.sampleSizes.push(i)}else t.sampleTable.sampleSizes.push(i)}break;case"stz2":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),e.skip(3);const i=Wo(e),r=$o(e),a=qo(e,Math.ceil(r*i/8)),s=new Qe(a);for(let e=0;e<r;e++){const e=s.readBits(i);t.sampleTable.sampleSizes.push(e)}}break;case"stss":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4),t.sampleTable.keySampleIndices=[];const i=$o(e);for(let r=0;r<i;r++){const i=$o(e)-1;t.sampleTable.keySampleIndices.push(i)}0!==t.sampleTable.keySampleIndices[0]&&t.sampleTable.keySampleIndices.unshift(0)}break;case"stsc":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=$o(e);for(let a=0;a<i;a++){const i=$o(e)-1,r=$o(e),a=$o(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++)if(t.sampleTable.sampleToChunk[e].startSampleIndex=r,e<t.sampleTable.sampleToChunk.length-1){r+=(t.sampleTable.sampleToChunk[e+1].startChunkIndex-t.sampleTable.sampleToChunk[e].startChunkIndex)*t.sampleTable.sampleToChunk[e].samplesPerChunk}}break;case"stco":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=$o(e);for(let r=0;r<i;r++){const i=$o(e);t.sampleTable.chunkOffsets.push(i)}}break;case"co64":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=$o(e);for(let r=0;r<i;r++){const i=Jo(e);t.sampleTable.chunkOffsets.push(i)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(H,q.contentSize));break;case"mehd":{const t=Wo(e);e.skip(3);const i=1===t?Jo(e):$o(e);this.movieDurationInTimescale=i}break;case"trex":{e.skip(4);const t=$o(e),i=$o(e),r=$o(e),a=$o(e),s=$o(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:i,defaultSampleDuration:r,defaultSampleSize:a,defaultSampleFlags:s})}break;case"tfra":{const t=Wo(e);e.skip(3);const i=$o(e),r=this.tracks.find(e=>e.id===i);if(!r)break;const a=$o(e),s=(12&a)>>2,n=3&a,o=[Wo,Vo,jo,$o],c=o[(48&a)>>4],l=o[s],u=o[n],d=$o(e);for(let h=0;h<d;h++){const i=1===t?Jo(e):$o(e),a=1===t?Jo(e):$o(e);c(e),l(e),u(e),r.fragmentLookupTable.push({timestamp:i,moofOffset:a})}r.fragmentLookupTable.sort((e,t)=>e.timestamp-t.timestamp);for(let e=0;e<r.fragmentLookupTable.length-1;e++){const t=r.fragmentLookupTable[e],i=r.fragmentLookupTable[e+1];t.timestamp===i.timestamp&&(r.fragmentLookupTable.splice(e+1,1),e--)}}break;case"moof":this.currentFragment={moofOffset:L,moofSize:q.totalSize,implicitBaseDataOffset:L,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(H,q.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(E(this.currentFragment),this.readContiguousBoxes(e.slice(H,q.contentSize)),this.currentTrack){const 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 a=0;a<e.presentationTimestamps.length;a++){const t=e.presentationTimestamps[a],i=e.samples[t.sampleIndex];if(null===e.firstKeyFrameTimestamp&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.presentationTimestamp),a<e.presentationTimestamps.length-1){const r=e.presentationTimestamps[a+1].presentationTimestamp-t.presentationTimestamp;i.duration=r}}const t=e.samples[e.presentationTimestamps[0].sampleIndex],i=e.samples[R(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=i.presentationTimestamp+i.duration;const{currentFragmentState:r}=this.currentTrack;E(r),null!==r.startTimestamp&&(pr(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;const t=Hi(qo(e,q.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case"tfhd":{E(this.currentFragment),e.skip(1);const t=jo(e),i=Boolean(1&t),r=Boolean(2&t),a=Boolean(8&t),s=Boolean(16&t),n=Boolean(32&t),o=Boolean(65536&t),c=Boolean(131072&t),l=$o(e),u=this.tracks.find(e=>e.id===l);if(!u)break;const d=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:d?.defaultSampleDescriptionIndex??null,defaultSampleDuration:d?.defaultSampleDuration??null,defaultSampleSize:d?.defaultSampleSize??null,defaultSampleFlags:d?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Jo(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=$o(e)),a&&(u.currentFragmentState.defaultSampleDuration=$o(e)),s&&(u.currentFragmentState.defaultSampleSize=$o(e)),n&&(u.currentFragmentState.defaultSampleFlags=$o(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;E(t.currentFragmentState);const i=Wo(e);e.skip(3);const r=0===i?$o(e):Jo(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;E(this.currentFragment),E(t.currentFragmentState);const i=Wo(e),r=jo(e),a=Boolean(1&r),s=Boolean(4&r),n=Boolean(256&r),o=Boolean(512&r),c=Boolean(1024&r),l=Boolean(2048&r),u=$o(e);let d=null;a&&(d=Qo(e));let h,f=null;s&&(f=$o(e)),this.currentFragment.trackData.has(t.id)?(h=this.currentFragment.trackData.get(t.id),null!==d&&(h.currentOffset=t.currentFragmentState.baseDataOffset+d)):(h={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(d??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,h));for(let m=0;m<u;m++){let r,a,s;n?r=$o(e):(E(null!==t.currentFragmentState.defaultSampleDuration),r=t.currentFragmentState.defaultSampleDuration),o?a=$o(e):(E(null!==t.currentFragmentState.defaultSampleSize),a=t.currentFragmentState.defaultSampleSize),c?s=$o(e):(E(null!==t.currentFragmentState.defaultSampleFlags),s=t.currentFragmentState.defaultSampleFlags),0===m&&null!==f&&(s=f);let u=0;l&&(u=0===i?$o(e):Qo(e));const d=!(65536&s);h.samples.push({presentationTimestamp:h.currentTimestamp+u,duration:r,byteOffset:h.currentOffset,byteSize:a,isKeyFrame:d,encryption:null}),h.currentOffset+=a,h.currentTimestamp+=r}this.currentFragment.implicitBaseDataOffset=h.currentOffset}break;case"saiz":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;e.skip(1);if(1&jo(e)){const i=rc(e,4),r=$o(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const i=Wo(e),r=$o(e);let a=null;0===i&&r>0&&(a=qo(e,r));const s=yr(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Wo(e);if(1&jo(e)){const i=rc(e,4),r=$o(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=$o(e);if(0===r)break;r>1&&Ke._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?$o(e):Number(Jo(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);yr(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;E(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=jo(e),a=Boolean(2&r),s=$o(e),n=t.encryptionInfo.defaultPerSampleIvSize;E(null!==n);for(let o=0;o<Math.min(s,i.samples.length);o++){const r=new Uint8Array(16);n>0?r.set(qo(e,n),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=Vo(e);s=[];for(let i=0;i<t;i++){const t=Vo(e),i=$o(e);s.push({clearLen:t,protectedLen:i})}}i.samples[o].encryption={iv:r,subsamples:s}}}break;case"udta":{const p=this.iterateContiguousBoxes(e.slice(H,q.contentSize));for(const{boxInfo:e,slice:g}of p){if("meta"!==e.name&&!this.currentTrack){const n=g.filePos;(t=this.metadataTags).raw??(t.raw={}),"\xa9"===e.name[0]?(i=this.metadataTags.raw)[r=e.name]??(i[r]=Gi(g)):(a=this.metadataTags.raw)[s=e.name]??(a[s]=qo(g,e.contentSize)),g.filePos=n}switch(e.name){case"meta":g.skip(-e.headerSize),this.traverseBox(g);break;case"\xa9nam":case"name":this.currentTrack?this.currentTrack.name=O.decode(qo(g,e.contentSize)):(n=this.metadataTags).title??(n.title=Gi(g));break;case"\xa9des":this.currentTrack||((o=this.metadataTags).description??(o.description=Gi(g)));break;case"\xa9ART":this.currentTrack||((c=this.metadataTags).artist??(c.artist=Gi(g)));break;case"\xa9alb":this.currentTrack||((l=this.metadataTags).album??(l.album=Gi(g)));break;case"albr":this.currentTrack||((u=this.metadataTags).albumArtist??(u.albumArtist=Gi(g)));break;case"\xa9gen":this.currentTrack||((d=this.metadataTags).genre??(d.genre=Gi(g)));break;case"\xa9day":if(!this.currentTrack){const e=new Date(Gi(g));Number.isNaN(e.getTime())||((h=this.metadataTags).date??(h.date=e))}break;case"\xa9cmt":this.currentTrack||((f=this.metadataTags).comment??(f.comment=Gi(g)));break;case"\xa9lyr":this.currentTrack||((m=this.metadataTags).lyrics??(m.lyrics=Gi(g)))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==$o(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(H,q.contentSize)):this.readContiguousBoxes(e.slice(H+4,q.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=$o(e);for(let i=0;i<t;i++){const t=$o(e);e.skip(4);const r=O.decode(qo(e,t-8));this.currentMetadataKeys.set(i+1,r)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(H,q.contentSize));for(const{boxInfo:e,slice:i}of t){let t=e.name;const r=(t.charCodeAt(0)<<24)+(t.charCodeAt(1)<<16)+(t.charCodeAt(2)<<8)+t.charCodeAt(3);this.currentMetadataKeys.has(r)&&(t=this.currentMetadataKeys.get(r));const a=Qi(i);switch((p=this.metadataTags).raw??(p.raw={}),(g=this.metadataTags.raw)[t]??(g[t]=a),t){case"\xa9nam":case"titl":case"com.apple.quicktime.title":case"title":"string"===typeof a&&((k=this.metadataTags).title??(k.title=a));break;case"\xa9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"===typeof a&&((y=this.metadataTags).description??(y.description=a));break;case"\xa9ART":case"com.apple.quicktime.artist":case"artist":"string"===typeof a&&((b=this.metadataTags).artist??(b.artist=a));break;case"\xa9alb":case"albm":case"com.apple.quicktime.album":case"album":"string"===typeof a&&((w=this.metadataTags).album??(w.album=a));break;case"aART":case"album_artist":"string"===typeof a&&((T=this.metadataTags).albumArtist??(T.albumArtist=a));break;case"\xa9cmt":case"com.apple.quicktime.comment":case"comment":"string"===typeof a&&((S=this.metadataTags).comment??(S.comment=a));break;case"\xa9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"===typeof a&&((v=this.metadataTags).genre??(v.genre=a));break;case"\xa9lyr":case"lyrics":"string"===typeof a&&((P=this.metadataTags).lyrics??(P.lyrics=a));break;case"\xa9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"===typeof a){const e=new Date(a);Number.isNaN(e.getTime())||((I=this.metadataTags).date??(I.date=e))}break;case"covr":case"com.apple.quicktime.artwork":a instanceof Xe?((x=this.metadataTags).images??(x.images=[]),this.metadataTags.images.push({data:a.data,kind:"coverFront",mimeType:a.mimeType})):a instanceof Uint8Array&&((C=this.metadataTags).images??(C.images=[]),this.metadataTags.images.push({data:a,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"===typeof a){const e=a.split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&((B=this.metadataTags).trackNumber??(B.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((F=this.metadataTags).tracksTotal??(F.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=N(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((A=this.metadataTags).trackNumber??(A.trackNumber=t)),i>0&&((D=this.metadataTags).tracksTotal??(D.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=N(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((M=this.metadataTags).discNumber??(M.discNumber=t)),i>0&&((z=this.metadataTags).discsTotal??(z.discsTotal=i))}}}}}return e.filePos=j,!0}}class cr{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;E(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return(t?.timestamp??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return de(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=dr(r,i),s=await this.fetchPacketForSampleIndex(a,t);return kr(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=Z(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<t.endTimestamp}},i,i,t):s}async getNextPacket(e,t){const i=this.packetToSampleIndex.get(e);if(void 0!==i)return this.fetchPacketForSampleIndex(i+1,t);const r=this.packetToFragmentLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1<t.samples.length)return{sampleIndex:r.sampleIndex+1,correctSampleFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{sampleIndex:0,correctSampleFound:!0}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=hr(r,i),s=await this.fetchPacketForSampleIndex(a,t);return kr(r)&&this.internalTrack.demuxer.isFragmented?this.performFragmentedLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=ae(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i<t.endTimestamp}},i,i,t):s}async getNextKeyPacket(e,t){const i=this.packetToSampleIndex.get(e);if(void 0!==i){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=mr(e,i);return this.fetchPacketForSampleIndex(r,t)}const r=this.packetToFragmentLocation.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");return this.performFragmentedLookup(r.fragment,e=>{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id).samples.findIndex((e,t)=>e.isKeyFrame&&t>r.sampleIndex);if(-1!==t)return{sampleIndex:t,correctSampleFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.samples.findIndex(e=>e.isKeyFrame);return E(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=fr(i,e);if(!r)return null;let a;if(t.metadataOnly)a=qi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Re(t)&&(t=await t),!t)return null;if(a=qo(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await br(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<i.length&&(t=i[e])}t??(t=wr(this.internalTrack.encryptionInfo)),t&&(a=await Tr(this.internalTrack,t,a,null))}}const s=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=r.duration/this.internalTrack.timescale,o=new Wi(a,r.isKeyFrame?"key":"delta",s,n,e,r.sampleSize);return this.packetToSampleIndex.set(o,e),o}async fetchPacketInFragment(e,t,i){if(-1===t)return null;const r=e.trackData.get(this.internalTrack.id).samples[t];let a;if(E(r),i.metadataOnly)a=qi;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(Re(t)&&(t=await t),!t)return null;if(a=qo(t,r.byteSize),this.internalTrack.encryptionInfo){const t=r.encryption??wr(this.internalTrack.encryptionInfo);t&&(a=await Tr(this.internalTrack,t,a,e))}}const s=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,n=r.duration/this.internalTrack.timescale,o=new Wi(a,r.isKeyFrame?"key":"delta",s,n,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(o,{fragment:e,sampleIndex:t}),o}async performFragmentedLookup(e,t,i,r,a){const s=this.internalTrack.demuxer;let n=null,o=null,c=-1;if(e){const{sampleIndex:i,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,i,a);-1!==i&&(o=e,c=i)}const l=Z(this.internalTrack.fragmentLookupTable,i,e=>e.timestamp),u=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,d=Z(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),h=-1!==d?this.internalTrack.fragmentPositionCache[d]:null,f=Math.max(u?.moofOffset??0,h?.moofOffset??0)||null;let m;for(e?null===f||e.moofOffset>=f?(m=e.moofOffset+e.moofSize,n=e):m=f:m=f??0;;){if(n){const e=n.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(m,8,16);if(Re(e)&&(e=await e),!e)break;const i=m,l=ji(e);if(!l)break;if("moof"===l.name){n=await s.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(n);if(r)return this.fetchPacketInFragment(n,e,a);-1!==e&&(o=n,c=e)}m=i+l.totalSize}if(u&&(!o||o.moofOffset<u.moofOffset)){const e=this.internalTrack.fragmentLookupTable[l-1];E(!e||e.timestamp<u.timestamp);const i=e?.timestamp??-1/0;return this.performFragmentedLookup(null,t,i,r,a)}return o?this.fetchPacketInFragment(o,c,a):null}}class lr extends cr{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(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async 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??(this.decoderConfigPromise=(async()=>{var e,t,i,r,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&qt(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&Ut(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&zt(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else{const e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&xt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&gt(e.data)}if(!j(this.internalTrack.info.colorSpace)){const a=Pi(this.internalTrack.info);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const s={codec:vi(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};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(s.displayAspectWidth=this.internalTrack.info.squarePixelWidth,s.displayAspectHeight=this.internalTrack.info.squarePixelHeight),s})()):null}}class ur extends cr{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??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&ui(e.data)}return{codec:Ii(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const dr=(e,t)=>{if(e.presentationTimestamps){const i=Z(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=Z(e.sampleTimingEntries,t,e=>e.startDecodeTimestamp);if(-1===i)return-1;const r=e.sampleTimingEntries[i];return r.startIndex+Math.min(Math.floor((t-r.startDecodeTimestamp)/r.delta),r.count-1)}},hr=(e,t)=>{if(!e.keySampleIndices)return dr(e,t);if(e.presentationTimestamps){const i=Z(e.presentationTimestamps,t,e=>e.presentationTimestamp);if(-1===i)return-1;for(let t=i;t>=0;t--){const i=e.presentationTimestamps[t].sampleIndex;if(-1!==J(e.keySampleIndices,i,e=>e))return i}return-1}{const i=dr(e,t),r=Z(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},fr=(e,t)=>{const i=Z(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=Z(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),n=e.sampleCompositionTimeOffsets[s];n&&t-n.startIndex<n.count&&(a+=n.offset);const o=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],c=Z(e.sampleToChunk,t,e=>e.startSampleIndex),l=e.sampleToChunk[c];E(l);const u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),d=e.chunkOffsets[u],h=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk;let f=0,m=d;if(1===e.sampleSizes.length)m+=o*(t-h),f+=o*l.samplesPerChunk;else for(let g=h;g<h+l.samplesPerChunk;g++){const i=e.sampleSizes[g];g<t&&(m+=i),f+=i}let p=r.delta;if(e.presentationTimestamps){const i=e.presentationTimestampIndexMap[t];if(E(void 0!==i),i<e.presentationTimestamps.length-1){p=e.presentationTimestamps[i+1].presentationTimestamp-a}}return{presentationTimestamp:a,duration:p,sampleOffset:m,sampleSize:o,chunkOffset:d,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==J(e.keySampleIndices,t,e=>e)}},mr=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=Z(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},pr=(e,t)=>{e.startTimestamp+=t,e.endTimestamp+=t;for(const i of e.samples)i.presentationTimestamp+=t;for(const i of e.presentationTimestamps)i.presentationTimestamp+=t},gr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},kr=e=>0===e.sampleSizes.length,yr=e=>{var t;return e.currentFragmentState?(t=e.currentFragmentState).encryptionAuxInfo??(t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):e.encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},br=async(e,t,i)=>{if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{E(i.sampleSizes);for(let e=0;e<i.sampleCount;e++)r+=i.sampleSizes[e]}let a=e.requestSlice(i.offset,r);if(Re(a)&&(a=await a),!a)throw new Error("Failed to read auxiliary encryption info.");const s=t.defaultPerSampleIvSize;E(null!==s);const n=[];for(let o=0;o<i.sampleCount;o++){const e=i.defaultSampleInfoSize>0?i.defaultSampleInfoSize:i.sampleSizes[o],r=new Uint8Array(16);s>0?r.set(qo(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=Vo(a);c=[];for(let t=0;t<e;t++){const e=Vo(a),t=$o(a);c.push({clearLen:e,protectedLen:t})}}n.push({iv:r,subsamples:c})}return i.resolved=n,n},wr=e=>e.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Tr=async(e,t,i,r)=>{E(e.encryptionInfo);const a=e.encryptionInfo;E(null!==a.defaultKid);const s=a.defaultKid;let n;const o=e.demuxer.decryptionKeyCache.get(s);if(o)n=await o;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(s));for(let e=0;e<t.length-1;e++)for(let i=e+1;i<t.length;i++)Vi(t[e],t[i])&&(t.splice(i,1),i--)}const i=await e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:s,psshBoxes:t});if(!("string"===typeof i&&32===i.length&&G.test(i)||i instanceof Uint8Array&&16===i.byteLength))throw new TypeError("resolveKeyId must return a 32-character hex string or a 16-byte Uint8Array containing the decryption key.");return i instanceof Uint8Array?i:(e=>{E(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i<e.length;i+=2)t[i/2]=parseInt(e.slice(i,i+2),16);return t})(i)})();e.demuxer.decryptionKeyCache.set(s,t),n=await t}return"cenc"===a.scheme||"cens"===a.scheme?Sr(n,a,t,i):vr(n,a,t,i)},Sr=async(e,t,i,r)=>{const a=new Uint8Array(16);a.set(i.iv,0);const s=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),n=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:a,length:64},s,e);return new Uint8Array(t)};if(!i.subsamples)return n(r);E(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Pr(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let c=0;for(const m of o)for(const e of m.perSubsample)c+=e.length;const l=new Uint8Array(c);let u=0;for(const m of o)for(const e of m.perSubsample)l.set(r.subarray(e.offset,e.offset+e.length),u),u+=e.length;const d=await n(l),h=new Uint8Array(r);let f=0;for(const m of o)for(const e of m.perSubsample)h.set(d.subarray(f,f+e.length),e.offset),f+=e.length;return h},vr=(e,t,i,r)=>{const a=new nr;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,n=t.defaultSkipByteBlock;if(E(null!==s&&null!==n),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i<t;i++){const t=16*i;a.in.set(r.subarray(t,t+16)),a.decrypt(),e.set(a.out,t)}return e}if(0===s&&0===n)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),c=Pr(i.subsamples,s,n),l=new DataView(i.iv.buffer,i.iv.byteOffset,16);for(const u of c){a.iv[0]=l.getUint32(0,!1),a.iv[1]=l.getUint32(4,!1),a.iv[2]=l.getUint32(8,!1),a.iv[3]=l.getUint32(12,!1);for(const e of u.perSubsample){const t=e.length/16;for(let i=0;i<t;i++){const t=e.offset+16*i;a.in.set(r.subarray(t,t+16)),a.decrypt(),o.set(a.out,t)}}}return o},Pr=(e,t,i)=>{const r=[],a=0!==t||0!==i;let s=0;for(const n of e){s+=n.clearLen;const e=[];if(a){let r=n.protectedLen,a=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:a,length:s}),a+=s,r-=s;const n=Math.min(16*i,r);a+=n,r-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;r.push({perSubsample:e})}return r};var Ir,xr;(xr=Ir||(Ir={}))[xr.EBML=440786851]="EBML",xr[xr.EBMLVersion=17030]="EBMLVersion",xr[xr.EBMLReadVersion=17143]="EBMLReadVersion",xr[xr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",xr[xr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",xr[xr.DocType=17026]="DocType",xr[xr.DocTypeVersion=17031]="DocTypeVersion",xr[xr.DocTypeReadVersion=17029]="DocTypeReadVersion",xr[xr.Void=236]="Void",xr[xr.Segment=408125543]="Segment",xr[xr.SeekHead=290298740]="SeekHead",xr[xr.Seek=19899]="Seek",xr[xr.SeekID=21419]="SeekID",xr[xr.SeekPosition=21420]="SeekPosition",xr[xr.Duration=17545]="Duration",xr[xr.Info=357149030]="Info",xr[xr.TimestampScale=2807729]="TimestampScale",xr[xr.MuxingApp=19840]="MuxingApp",xr[xr.WritingApp=22337]="WritingApp",xr[xr.Tracks=374648427]="Tracks",xr[xr.TrackEntry=174]="TrackEntry",xr[xr.TrackNumber=215]="TrackNumber",xr[xr.TrackUID=29637]="TrackUID",xr[xr.TrackType=131]="TrackType",xr[xr.FlagEnabled=185]="FlagEnabled",xr[xr.FlagDefault=136]="FlagDefault",xr[xr.FlagForced=21930]="FlagForced",xr[xr.FlagOriginal=21934]="FlagOriginal",xr[xr.FlagHearingImpaired=21931]="FlagHearingImpaired",xr[xr.FlagVisualImpaired=21932]="FlagVisualImpaired",xr[xr.FlagCommentary=21935]="FlagCommentary",xr[xr.FlagLacing=156]="FlagLacing",xr[xr.Name=21358]="Name",xr[xr.Language=2274716]="Language",xr[xr.LanguageBCP47=2274717]="LanguageBCP47",xr[xr.CodecID=134]="CodecID",xr[xr.CodecPrivate=25506]="CodecPrivate",xr[xr.CodecDelay=22186]="CodecDelay",xr[xr.SeekPreRoll=22203]="SeekPreRoll",xr[xr.DefaultDuration=2352003]="DefaultDuration",xr[xr.Video=224]="Video",xr[xr.PixelWidth=176]="PixelWidth",xr[xr.PixelHeight=186]="PixelHeight",xr[xr.DisplayWidth=21680]="DisplayWidth",xr[xr.DisplayHeight=21690]="DisplayHeight",xr[xr.DisplayUnit=21682]="DisplayUnit",xr[xr.AlphaMode=21440]="AlphaMode",xr[xr.Audio=225]="Audio",xr[xr.SamplingFrequency=181]="SamplingFrequency",xr[xr.Channels=159]="Channels",xr[xr.BitDepth=25188]="BitDepth",xr[xr.SimpleBlock=163]="SimpleBlock",xr[xr.BlockGroup=160]="BlockGroup",xr[xr.Block=161]="Block",xr[xr.BlockAdditions=30113]="BlockAdditions",xr[xr.BlockMore=166]="BlockMore",xr[xr.BlockAdditional=165]="BlockAdditional",xr[xr.BlockAddID=238]="BlockAddID",xr[xr.BlockDuration=155]="BlockDuration",xr[xr.ReferenceBlock=251]="ReferenceBlock",xr[xr.Cluster=524531317]="Cluster",xr[xr.Timestamp=231]="Timestamp",xr[xr.Cues=475249515]="Cues",xr[xr.CuePoint=187]="CuePoint",xr[xr.CueTime=179]="CueTime",xr[xr.CueTrackPositions=183]="CueTrackPositions",xr[xr.CueTrack=247]="CueTrack",xr[xr.CueClusterPosition=241]="CueClusterPosition",xr[xr.Colour=21936]="Colour",xr[xr.MatrixCoefficients=21937]="MatrixCoefficients",xr[xr.TransferCharacteristics=21946]="TransferCharacteristics",xr[xr.Primaries=21947]="Primaries",xr[xr.Range=21945]="Range",xr[xr.Projection=30320]="Projection",xr[xr.ProjectionType=30321]="ProjectionType",xr[xr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",xr[xr.Attachments=423732329]="Attachments",xr[xr.AttachedFile=24999]="AttachedFile",xr[xr.FileDescription=18046]="FileDescription",xr[xr.FileName=18030]="FileName",xr[xr.FileMediaType=18016]="FileMediaType",xr[xr.FileData=18012]="FileData",xr[xr.FileUID=18094]="FileUID",xr[xr.Chapters=272869232]="Chapters",xr[xr.Tags=307544935]="Tags",xr[xr.Tag=29555]="Tag",xr[xr.Targets=25536]="Targets",xr[xr.TargetTypeValue=26826]="TargetTypeValue",xr[xr.TargetType=25546]="TargetType",xr[xr.TagTrackUID=25541]="TagTrackUID",xr[xr.TagEditionUID=25545]="TagEditionUID",xr[xr.TagChapterUID=25540]="TagChapterUID",xr[xr.TagAttachmentUID=25542]="TagAttachmentUID",xr[xr.SimpleTag=26568]="SimpleTag",xr[xr.TagName=17827]="TagName",xr[xr.TagLanguage=17530]="TagLanguage",xr[xr.TagString=17543]="TagString",xr[xr.TagBinary=17541]="TagBinary",xr[xr.ContentEncodings=28032]="ContentEncodings",xr[xr.ContentEncoding=25152]="ContentEncoding",xr[xr.ContentEncodingOrder=20529]="ContentEncodingOrder",xr[xr.ContentEncodingScope=20530]="ContentEncodingScope",xr[xr.ContentCompression=20532]="ContentCompression",xr[xr.ContentCompAlgo=16980]="ContentCompAlgo",xr[xr.ContentCompSettings=16981]="ContentCompSettings",xr[xr.ContentEncryption=20533]="ContentEncryption";const Cr=[Ir.EBML,Ir.Segment],Br=[Ir.SeekHead,Ir.Info,Ir.Cluster,Ir.Tracks,Ir.Cues,Ir.Attachments,Ir.Chapters,Ir.Tags],Er=[...Cr,...Br],_r=16,Rr=e=>{if(e.remainingLength<1)return null;const t=Wo(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength<i?null:i},Fr=e=>{if(e.remainingLength<1)return null;const t=Wo(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength<i-1)return null;let a=t&r-1;for(let s=1;s<i;s++)a*=256,a+=Wo(e);return a},Ar=(e,t)=>{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r<t;r++)i*=256,i+=Wo(e);return i},Dr=e=>{const t=Rr(e);if(null===t)return null;if(e.remainingLength<t)return null;return Ar(e,t)},Mr=e=>{if(e.remainingLength<1)return null;if(255===Wo(e))return;e.skip(-1);const t=Fr(e);return null===t?null:72057594037927940!==t?t:void 0},Nr=e=>{E(e.remainingLength>=2);const t=Dr(e);if(null===t)return null;const i=Mr(e);return null===i?null:{id:t,size:i}},Or=(e,t)=>{const i=qo(e,t);let r=0;for(;r<t&&0!==i[r];)r+=1;return String.fromCharCode(...i.subarray(0,r))},zr=(e,t)=>{const i=qo(e,t);let r=0;for(;r<t&&0!==i[r];)r+=1;return O.decode(i.subarray(0,r))},Lr=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?tc(e):ic(e)},Ur=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||s<r;){let t=e.requestSliceRange(s,2,_r);if(Re(t)&&(t=await t),!t)break;const i=Nr(t);if(!i)break;if(a.has(i.id))return{pos:s,found:!0};ia(i.size),s=t.filePos+i.size}return{pos:null!==r&&r>s?r:s,found:!1}},qr=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;s<r;){let t=e.requestSliceRange(s,0,Math.min(65536,r-s));if(Re(t)&&(t=await t),!t)break;if(t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=s;const e=Dr(t);if(null!==e&&a.has(e))return s;s++}}return null},Wr="V_MPEG4/ISO/AVC",Hr="V_MPEGH/ISO/HEVC",Vr="V_VP8",jr="V_VP9",Kr="V_AV1",Xr="V_PRORES",$r="A_AAC",Gr="A_MPEG/L3",Qr="A_OPUS",Yr="A_VORBIS",Jr="A_FLAC",Zr="A_AC3",ea="A_EAC3",ta="A_DTS";function ia(e){if(void 0===e)throw new Error("Undefined element size is used in a place where it is not supported.")}var ra,aa,sa,na,oa,ca;(aa=ra||(ra={}))[aa.None=0]="None",aa[aa.Xiph=1]="Xiph",aa[aa.FixedSize=2]="FixedSize",aa[aa.Ebml=3]="Ebml",(na=sa||(sa={}))[na.Block=1]="Block",na[na.Private=2]="Private",na[na.Next=4]="Next",(ca=oa||(oa={}))[ca.Zlib=0]="Zlib",ca[ca.Bzlib=1]="Bzlib",ca[ca.lzo1x=2]="lzo1x",ca[ca.HeaderStripping=3]="HeaderStripping";const la=[{id:Ir.SeekHead,flag:"seekHeadSeen"},{id:Ir.Info,flag:"infoSeen"},{id:Ir.Tracks,flag:"tracksSeen"},{id:Ir.Cues,flag:"cuesSeen"}],ua=10485760;class da extends Ui{constructor(e){super(e),this.readMetadataPromise=null,this.segments=[],this.currentSegment=null,this.currentTrack=null,this.currentCluster=null,this.currentBlock=null,this.currentBlockAdditional=null,this.currentCueTime=null,this.currentDecodingInstruction=null,this.currentTagTargetIsMovie=!0,this.currentSimpleTagName=null,this.currentAttachedFile=null,this.isWebM=!1,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,_r);if(Re(t)&&(t=await t),!t)break;const i=Nr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===Ir.EBML){ia(a);let e=this.reader.requestSlice(s,a);if(Re(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===Ir.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===Ir.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await Ur(this.reader,s,Er,this.reader.fileSize)).pos-s}const e=R(this.segments);e&&(e.elementEndPos=s+a)}ia(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,_r);if(Re(e)&&(e=await e),!e)break;const t=i,r=Nr(e);if(!r||!Br.includes(r.id)&&r.id!==Ir.Void){const e=await qr(this.reader,t,Br,Math.min(this.currentSegment.elementEndPos??1/0,t+ua));if(e){i=e;continue}break}const{id:a,size:s}=r,n=e.filePos,o=la.findIndex(e=>e.id===a);if(-1!==o){const e=la[o].flag;this.currentSegment[e]=!0,ia(s);let t=this.reader.requestSlice(n,s);Re(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===Ir.Tags||a===Ir.Attachments){a===Ir.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ia(s);let e=this.reader.requestSlice(n,s);Re(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===Ir.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=la.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,_r);if(Re(i)&&(i=await i),!i)continue;const r=Nr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;ia(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);Re(o)&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const n of this.currentSegment.tracks)null!==n.defaultDurationNs&&(n.defaultDuration=this.currentSegment.timestampFactor*n.defaultDurationNs/1e9);const r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const n of this.currentSegment.cuePoints){const e=r.get(n.trackId);e&&e.cuePoints.push(n)}for(const n of this.currentSegment.tracks){n.cuePoints.sort((e,t)=>e.time-t.time);for(let e=0;e<n.cuePoints.length-1;e++){const t=n.cuePoints[e],i=n.cuePoints[e+1];t.time===i.time&&(n.cuePoints.splice(e+1,1),e--)}}let a=null,s=-1/0;for(const n of this.currentSegment.tracks)n.cuePoints.length>s&&(s=n.cuePoints.length,a=n);for(const n of this.currentSegment.tracks)0===n.cuePoints.length&&(n.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,2,_r);Re(i)&&(i=await i),E(i);const r=e,a=Nr(i);E(a);E(a.id===Ir.Cluster);let s=a.size;const n=i.filePos;if(void 0===s){s=(await Ur(this.reader,n,Er,t.elementEndPos)).pos-n}let o=this.reader.requestSlice(n,s);Re(o)&&(o=await o);const c={segment:t,elementStartPos:r,elementEndPos:n+s,dataStartPos:n,timestamp:-1,trackData:new Map};if(this.currentCluster=c,o){const e=this.readContiguousElements(o,Er);c.elementEndPos=e}for(const[,l]of c.trackData){const e=l.track;E(l.blocks.length>0);let t=!1;for(let r=0;r<l.blocks.length;r++){const e=l.blocks[r];e.timestamp+=c.timestamp,t||(t=e.lacing!==ra.None)}l.presentationTimestamps=l.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r<l.presentationTimestamps.length;r++){const t=l.presentationTimestamps[r],i=l.blocks[t.blockIndex];if(null===l.firstKeyFrameTimestamp&&i.isKeyFrame&&(l.firstKeyFrameTimestamp=i.timestamp),r<l.presentationTimestamps.length-1){const e=l.presentationTimestamps[r+1];i.duration=e.timestamp-i.timestamp}else 0===i.duration&&null!=e.defaultDuration&&i.lacing===ra.None&&(i.duration=e.defaultDuration)}t&&(this.expandLacedBlocks(l.blocks,e),l.presentationTimestamps=l.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const i=l.blocks[l.presentationTimestamps[0].blockIndex],a=l.blocks[R(l.presentationTimestamps).blockIndex];l.startTimestamp=i.timestamp,l.endTimestamp=a.timestamp+a.duration;const s=Z(e.clusterPositionCache,l.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:l.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i<e.length;i++){const r=e[i];if(r.lacing===ra.None)continue;r.decoded||(r.data=this.decodeBlockData(t,r.data),r.decoded=!0);const a=Lo.tempFromBytes(r.data),s=[],n=Wo(a)+1;switch(r.lacing){case ra.Xiph:{let e=0;for(let t=0;t<n-1;t++){let t=0;for(;a.bufferPos<a.length;){const i=Wo(a);if(t+=i,i<255){s.push(t),e+=t;break}}}s.push(a.length-(a.bufferPos+e))}break;case ra.FixedSize:{const e=a.length-1,t=Math.floor(e/n);for(let i=0;i<n;i++)s.push(t)}break;case ra.Ebml:{const e=Fr(a);E(null!==e);let t=e;s.push(t);let i=t;for(let r=1;r<n-1;r++){const e=a.bufferPos,r=Fr(a);E(null!==r);t+=r-((1<<7*(a.bufferPos-e)-1)-1),s.push(t),i+=t}s.push(a.length-(a.bufferPos+i))}break;default:E(!1)}E(s.length===n),e.splice(i,1);const o=r.duration||n*(t.defaultDuration??0);for(let t=0;t<n;t++){const c=s[t],l=qo(a,c),u=r.timestamp+o*t/n,d=o/n;e.splice(i+t,0,{timestamp:u,duration:d,isKeyFrame:r.isKeyFrame,data:l,lacing:ra.None,decoded:!0,postProcessed:!1,mainAdditional:r.mainAdditional})}i+=n,i--}}async loadSegmentMetadata(e){for(const t of e.seekEntries){if(t.id!==Ir.Tags||e.tagsSeen){if(t.id!==Ir.Attachments||e.attachmentsSeen)continue}else;let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,_r);if(Re(i)&&(i=await i),!i)continue;const r=Nr(i);if(!r||r.id!==t.id)continue;const{size:a}=r;ia(a),E(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(i.filePos,a);Re(s)&&(s=await s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===Ir.Tags?e.tagsSeen=!0:t.id===Ir.Attachments&&(e.attachmentsSeen=!0)}}readContiguousElements(e,t){for(;e.remainingLength>=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=Nr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(ia(a),r){case Ir.DocType:this.isWebM="webm"===Or(e,a);break;case Ir.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Ir.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Ar(e,a)}break;case Ir.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Ar(e,a)}break;case Ir.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Ar(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Ir.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Lr(e,a);break;case Ir.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...Ge,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(s,a)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==sa.Block||e.data.algorithm!==oa.HeaderStripping)&&(Ke._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===Wr)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===Hr)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Vr)this.currentTrack.info.codec="vp8";else if(t===jr)this.currentTrack.info.codec="vp9";else if(t===Kr)this.currentTrack.info.codec="av1";else if(t===Xr){const e=this.currentTrack.codecPrivate?O.decode(this.currentTrack.codecPrivate):"";Ti.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new fa(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===$r?(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===Gr?this.currentTrack.info.codec="mp3":t===Qr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=xi):t===Yr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Jr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Zr?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ea?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ta?(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"));const e=this.currentTrack;this.currentTrack.trackBacking=new ma(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Ir.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Ar(e,a);break;case Ir.TrackType:{if(!this.currentTrack)break;const t=Ar(e,a);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:{...K},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 Ir.FlagEnabled:if(!this.currentTrack)break;Ar(e,a)||(this.currentTrack=null);break;case Ir.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Ar(e,a);break;case Ir.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Ar(e,a);break;case Ir.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Ar(e,a);break;case Ir.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Ar(e,a);break;case Ir.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Ar(e,a);break;case Ir.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Ar(e,a);break;case Ir.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Or(e,a);break;case Ir.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=qo(e,a);break;case Ir.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Ar(e,a);break;case Ir.Name:if(!this.currentTrack)break;this.currentTrack.name=zr(e,a);break;case Ir.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Or(e,a),ke(this.currentTrack.languageCode)||(this.currentTrack.languageCode=ue);break;case Ir.LanguageBCP47:{if(!this.currentTrack)break;const t=Or(e,a).split("-")[0];this.currentTrack.languageCode=t||ue,this.currentTrack.hasLanguageBcp47=!0}break;case Ir.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case Ir.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Ar(e,a);break;case Ir.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Ar(e,a);break;case Ir.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Ar(e,a);break;case Ir.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Ar(e,a);break;case Ir.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Ar(e,a);break;case Ir.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Ar(e,a);break;case Ir.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case Ir.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=Ar(e,a),i=V[t];this.currentTrack.info.colorSpace.matrix=i}break;case Ir.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=Ar(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case Ir.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=Ar(e,a),i=W[t];this.currentTrack.info.colorSpace.transfer=i}break;case Ir.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=Ar(e,a),i=U[t];this.currentTrack.info.colorSpace.primaries=i}break;case Ir.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case Ir.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-Lr(e,a);try{this.currentTrack.info.rotation=_(t)}catch{}}break;case Ir.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case Ir.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=Lr(e,a);break;case Ir.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Ar(e,a);break;case Ir.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Ar(e,a);break;case Ir.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case Ir.CueTime:this.currentCueTime=Ar(e,a);break;case Ir.CueTrackPositions:{if(null===this.currentCueTime)break;E(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Ir.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Ar(e,a)}break;case Ir.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;E(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Ar(e,a)}break;case Ir.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Ar(e,a);break;case Ir.SimpleBlock:{if(!this.currentCluster)break;const t=Fr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Ko(e),n=Wo(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=qo(e,a-(e.filePos-s)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case Ir.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case Ir.Block:{if(!this.currentCluster)break;const t=Fr(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Ko(e),n=Wo(e)>>1&3,o=qo(e,a-(e.filePos-s)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case Ir.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case Ir.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Ir.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=qo(e,a);break;case Ir.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Ar(e,a);break;case Ir.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Ar(e,a);break;case Ir.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Ir.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case Ir.Targets:this.readContiguousElements(e.slice(s,a));break;case Ir.TargetTypeValue:50!==Ar(e,a)&&(this.currentTagTargetIsMovie=!1);break;case Ir.TagTrackUID:case Ir.TagEditionUID:case Ir.TagChapterUID:case Ir.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Ir.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case Ir.TagName:this.currentSimpleTagName=zr(e,a);break;case Ir.TagString:{if(!this.currentSimpleTagName)break;const t=zr(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case Ir.TagBinary:{if(!this.currentSimpleTagName)break;const t=qo(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case Ir.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new $e(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??(t.images=[]),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 Ir.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;r<t;r++)i<<=8n,i+=BigInt(Wo(e));return i})(e,a);break;case Ir.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=zr(e,a);break;case Ir.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Or(e,a);break;case Ir.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=qo(e,a);break;case Ir.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=zr(e,a);break;case Ir.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(s,a)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case Ir.ContentEncoding:this.currentDecodingInstruction={order:0,scope:sa.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Ir.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Ar(e,a);break;case Ir.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Ar(e,a);break;case Ir.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:oa.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case Ir.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Ar(e,a);break;case Ir.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=qo(e,a);break;case Ir.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){E(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(E(r.data),"decompress"===r.data.type)if(r.data.algorithm===oa.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var i;if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??(r.raw={}),(i=r.raw)[e]??(i[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":r.title??(r.title=t);break;case"description":r.description??(r.description=t);break;case"artist":r.artist??(r.artist=t);break;case"album":r.album??(r.album=t);break;case"album_artist":r.albumArtist??(r.albumArtist=t);break;case"genre":r.genre??(r.genre=t);break;case"comment":r.comment??(r.comment=t);break;case"lyrics":r.lyrics??(r.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??(r.date=e))}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??(r.trackNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??(r.tracksTotal=a))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??(r.discNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??(r.discsTotal=a))}}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){E(r.trackBacking);const e=await r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=t??0,i}}class ha{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return de(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=Z(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i<t.endTimestamp}},i,i,t)}async getNextPacket(e,t){const i=this.packetToClusterLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,e=>{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1<t.blocks.length)return{blockIndex:i.blockIndex+1,correctBlockFound:!0}}else{if(e.trackData.get(this.internalTrack.id))return{blockIndex:0,correctBlockFound:!0}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async getKeyPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=ae(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i<t.endTimestamp}},i,i,t)}async getNextKeyPacket(e,t){const i=this.packetToClusterLocation.get(e);if(void 0===i)throw new Error("Packet was not created from this track.");return this.performClusterLookup(i.cluster,e=>{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id).blocks.findIndex((e,t)=>e.isKeyFrame&&t>i.blockIndex);if(-1!==t)return{blockIndex:t,correctBlockFound:!0}}else{const t=e.trackData.get(this.internalTrack.id);if(t&&null!==t.firstKeyFrameTimestamp){const e=t.blocks.findIndex(e=>e.isKeyFrame);return E(-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;const r=e.trackData.get(this.internalTrack.id).blocks[t];if(E(r),r.decoded||(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),r.decoded=!0),!r.postProcessed){if("prores"===this.internalTrack.info?.codec){if(!(r.data.length>=8&&105===r.data[4]&&99===r.data[5]&&112===r.data[6]&&102===r.data[7])){const e=new Uint8Array(r.data.length+8);N(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}const a=i.metadataOnly?qi:r.data,s=r.timestamp/this.internalTrack.segment.timestampFactor,n=r.duration/this.internalTrack.segment.timestampFactor,o={};r.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(o.alpha=i.metadataOnly?qi:r.mainAdditional,o.alphaByteLength=r.mainAdditional.byteLength);const c=new Wi(a,r.isKeyFrame?"key":"delta",s,n,e.dataStartPos+t,r.data.byteLength,o);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,i,r,a){const{demuxer:s,segment:n}=this.internalTrack;let o=null,c=null,l=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(c=e,l=i)}const u=Z(this.internalTrack.cuePoints,i,e=>e.time),d=-1!==u?this.internalTrack.cuePoints[u]:null,h=Z(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),f=-1!==h?this.internalTrack.clusterPositionCache[h]:null,m=Math.max(d?.clusterPosition??0,f?.elementStartPos??0)||null;let p;for(e?null===m||e.elementStartPos>=m?(p=e.elementEndPos,o=e):p=m:p=m??n.clusterSeekStartPos;null===n.elementEndPos||p<=n.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,2,_r);if(Re(e)&&(e=await e),!e)break;const i=p,u=Nr(e);if(!u||!Br.includes(u.id)&&u.id!==Ir.Void){const e=await qr(s.reader,i,Br,Math.min(n.elementEndPos??1/0,i+ua));if(e){p=e;continue}break}const d=u.id;let h=u.size;const f=e.filePos;if(d===Ir.Cluster){o=await s.readCluster(i,n),h=o.elementEndPos-f;const{blockIndex:e,correctBlockFound:r}=t(o);if(r)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,l=e)}if(void 0===h){E(d!==Ir.Cluster);h=(await Ur(s.reader,f,Er,n.elementEndPos)).pos-f}const m=f+h;if(null===n.elementEndPos){let e=s.reader.requestSliceRange(m,2,_r);if(Re(e)&&(e=await e),!e)break;if(Dr(e)===Ir.Segment){n.elementEndPos=m;break}}p=m}if(d&&(!c||c.elementStartPos<d.clusterPosition)){const e=this.internalTrack.cuePoints[u-1];E(!e||e.time<d.time);const i=e?.time??-1/0;return this.performClusterLookup(null,t,i,r,a)}return c?this.fetchPacketInCluster(c,l,a):null}}class fa extends ha{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(){const e=await this.getDecoderConfig();return e?{primaries:e.colorSpace?.primaries,transfer:e.colorSpace?.transfer,matrix:e.colorSpace?.matrix,fullRange:e.colorSpace?.fullRange}:this.internalTrack.info.colorSpace}async 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??(this.decoderConfigPromise=(async()=>{var e,t,i,r;let a=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(a=await this.getFirstPacket({}));const s={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&&a?gt(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?xt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?zt(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?Ut(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?qt(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!j(this.internalTrack.info.colorSpace)){const a=Pi(s);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const n={codec:vi(s),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})()):null}}class ma extends ha{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??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&ui(e.data)}return{codec:Ii({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}}const pa=async(e,t,i,r=null)=>{let a=t;for(;null===i||a<i;){const t=null!==i?Math.min(65536,i-a):65536;let s=e.requestSliceRange(a,4,t);if(Re(s)&&(s=await s),!s||s.length<4)break;for(;s.remainingLength>=4;){const t=s.filePos,i=$o(s),n=null!==e.fileSize?e.fileSize-a:null,o=Mi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&Li(o.header.channel)===Li(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class ga extends Ui{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 $,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new ka(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,uc);if(Re(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=mc(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await pa(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Di(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Re(r)&&(r=await r),r){const a=$o(r);if(a===Fi||a===Ai){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Re(t)&&(t=await t),t){const e=qo(t,12),i=N(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Oi.FrameCount?i.getUint32(4,!1):null,fileSize:r&Oi.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,uc);if(Re(i)&&(i=await i),!i)break;const r=mc(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(Re(a)&&(a=await a),!a)break;pc(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=lc){let e=this.reader.requestSlice(this.reader.fileSize-lc,lc);Re(e)&&(e=await e),E(e);"TAG"===rc(e,3)&&hc(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class ka{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return E(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(){const e=this.demuxer;if(E(null!==e.firstFrameHeader),E(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,a=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(a<<t):2===i?144*r/a:12*r/a*4),n=(e.reader.fileSize-e.firstFrameHeaderPos)/s;return Math.round(n)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}var t,i,r,a;return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ue}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return E(this.demuxer.firstFrameHeader),Li(this.demuxer.firstFrameHeader.channel)}getSampleRate(){return E(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return{...Ge}}async getDecoderConfig(){return E(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:Li(this.demuxer.firstFrameHeader.channel),sampleRate:this.demuxer.firstFrameHeader.sampleRate}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=qi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Re(e)&&(e=await e),!e)return null;r=qo(e,i.dataSize)}return new Wi(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=J(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Z(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ya=1399285583,ba=new Uint32Array(256);for(let zc=0;zc<256;zc++){let e=zc<<24;for(let t=0;t<8;t++)e=2147483648&e?e<<1^79764919:e<<1;ba[zc]=e>>>0&4294967295}const wa=e=>{const t=N(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let a=0;a<e.length;a++){const t=e[a];r=(r<<8^ba[r>>>24^t])>>>0}return t.setUint32(22,i,!0),r},Ta=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){E(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,n=(e[0]&s)>>1;if(n>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const c=t.vorbisInfo.modeBlockflags[n];if(a=t.vorbisInfo.blocksizes[c],1===c){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+a>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:Wt[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},Sa=27,va=282,Pa=e=>{const t=e.filePos;if(Go(e)!==ya)return null;e.skip(1);const i=Wo(e),r=ec(e),a=Go(e),s=Go(e),n=Go(e),o=Wo(e),c=new Uint8Array(o);for(let d=0;d<o;d++)c[d]=Wo(e);const l=27+o,u=c.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},Ia=(e,t)=>{for(;e.filePos<t-3;){const t=Go(e),i=79;if((255&t)===i||(t>>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===ya)return!0;e.skip(1)}}return!1};class xa extends Ui{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,Sa,va);if(Re(t)&&(t=await t),!t)break;const i=Pa(t);if(!i)break;if(!!!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const e=await this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?await this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&await this.readOpusMetadata(e,t),null!==t.codecInfo.codec&&this.trackBackings.push(new Ca(t,this)))}})())}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=await this.findNextPacketStart(r),!i)return;const a=await this.readPacket(i.startPage,i.startSegmentIndex);if(!a)return;if(3!==r.data[0]||5!==a.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const c=N(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&l),1<<(l>>4)],modeBlockflags:Ht(a.data).modeBlockflags},Xt(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const a=(e=>{const t=N(e),i=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}})(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=xi,t.codecInfo.opusInfo={preSkip:a.preSkip},Xt(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){E(t<e.lacingValues.length);let i=0;for(let u=0;u<t;u++)i+=e.lacingValues[u];let r=e,a=i,s=t;const n=[];e:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);Re(t)&&(t=await t),E(t);const o=qo(t,r.dataSize);for(;;){if(s===r.lacingValues.length){n.push(o.subarray(i,a));break}const e=r.lacingValues[s];if(a+=e,e<255){n.push(o.subarray(i,a));break e}s++}let c=r.headerStartPos+r.totalSize;for(;;){let t=this.reader.requestSliceRange(c,Sa,va);if(Re(t)&&(t=await t),!t)return null;const i=Pa(t);if(!i)return null;if(r=i,r.serialNumber===e.serialNumber)break;c=r.headerStartPos+r.totalSize}i=0,a=0,s=0}const o=n.reduce((e,t)=>e+t.length,0);if(0===o)return null;const c=new Uint8Array(o);let l=0;for(let u=0;u<n.length;u++){const e=n[u];c.set(e,l),l+=e.length}return{data:c,endPage:r,endSegmentIndex:s}}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,Sa,va);if(Re(i)&&(i=await i),!i)return null;const r=Pa(i);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}}async getMimeType(){await this.readMetadata();return(e=>{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Ca{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new $,this.internalSampleRate="opus"===e.codecInfo.codec?xi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return E(-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}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return E(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 ue}getDisposition(){return{...Ge,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(E(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=Ta(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Wi(i.metadataOnly?qi: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){E(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(E(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=await this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const a=i.timestampInSamples+i.durationInSamples,s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const i=de(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;E(this.bitstream.lastMetadataPacket);const r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let a=r.startPage,s=this.demuxer.reader.fileSize;const n=[a];e:for(;a.headerStartPos+a.totalSize<s;){const e=a.headerStartPos,t=Math.floor((e+s)/2);let r=t;for(;;){const e=Math.min(r+65307,s-Sa);let o=this.demuxer.reader.requestSlice(r,e-r);Re(o)&&(o=await o),E(o);if(!Ia(o,e)){s=t+Sa;continue e}let c=this.demuxer.reader.requestSliceRange(o.filePos,Sa,va);Re(c)&&(c=await c),E(c);const l=Pa(c);E(l);let u=!1;if(l.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(l.headerStartPos,l.totalSize);Re(e)&&(e=await e),E(e);const t=qo(e,l.totalSize);u=wa(t)===l.checksum}if(!u){r=l.headerStartPos+4;continue}if(u&&l.serialNumber!==this.bitstream.serialNumber){r=l.headerStartPos+l.totalSize;continue}if(!(-1===l.granulePosition)){this.granulePositionToTimestampInSamples(l.granulePosition)>i?s=l.headerStartPos:(a=l,n.push(l));continue e}r=l.headerStartPos+l.totalSize}}let o=r.startPage;for(const k of n){if(k.granulePosition===a.granulePosition)break;(!o||k.headerStartPos>o.headerStartPos)&&(o=k)}let c=o;const l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Sa,va);Re(t)&&(t=await t),E(t);const i=Pa(t);E(i),c=i,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}E(-1!==c.granulePosition);let u,d,h=null,f=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),d=!0,h=0;else{u=0,d=!1;for(let t=c.lacingValues.length-1;t>=0;t--){if(c.lacingValues[t]<255){h=t+1;break}}if(null===h)throw new Error("Invalid page with granule position: no packets end on this page.");m=h-1;const e={data:qi,endPage:f,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){const e=Ea(l,c,h);E(e);const t=Ba(l,e.page,e.segmentIndex);t&&(c=t.page,h=t.segmentIndex)}else for(;;){const e=Ea(l,c,h);if(!e)break;const t=Ba(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,h=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,m=e.segmentIndex;break}}}let p=null,g=null;for(;null!==c;){E(null!==h);const e=await this.demuxer.readPacket(c,h);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&h<r.startSegmentIndex)){let r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u,vorbisLastBlocksize:g?.vorbisBlockSize??null},t);E(r);let a=this.encodedPacketToMetadata.get(r);if(E(a),d||e.endPage.headerStartPos!==f.headerStartPos||e.endSegmentIndex!==m?u+=a.durationInSamples:(u=this.granulePositionToTimestampInSamples(c.granulePosition),d=!0,r=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:u-a.durationInSamples,vorbisLastBlocksize:g?.vorbisBlockSize??null},t),E(r),a=this.encodedPacketToMetadata.get(r),E(a)),p=r,g=a,d&&(Math.max(u,0)>i||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,h=a.startSegmentIndex}return p}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=de(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=Z(this.sequentialScanCache,i,e=>e.timestampInSamples);let a;if(-1!==r){const e=this.sequentialScanCache[r];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let s=0;for(;a&&a.timestamp<e;){const i=await this.getNextPacket(a,t);if(!i||i.timestamp>e)break;if(a=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(a);E(e),this.sequentialScanCache.length>0&&E(R(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ba=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}E(-1===a);if(!(1&r.headerType)){a=0;break}const t=re(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;r=t,a=r.lacingValues.length}if(E(-1!==a),a===r.lacingValues.length){const t=e[e.indexOf(r)+1];E(t),r=t,a=0}return{page:r,segmentIndex:a}},Ea=(e,t,i)=>{if(i>0)return{page:t,segmentIndex:i-1};const r=re(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var _a,Ra;(Ra=_a||(_a={}))[Ra.PCM=1]="PCM",Ra[Ra.IEEE_FLOAT=3]="IEEE_FLOAT",Ra[Ra.ALAW=6]="ALAW",Ra[Ra.MULAW=7]="MULAW",Ra[Ra.EXTENSIBLE=65534]="EXTENSIBLE";class Fa extends Ui{constructor(e){super(e),this.metadataPromise=null,this.dataStart=-1,this.dataSize=-1,this.audioInfo=null,this.trackBackings=[],this.lastKnownPacketIndex=0,this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,12);Re(e)&&(e=await e),E(e);const t=rc(e,4),i="RIFX"!==t,r="RF64"===t,a=Xo(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==rc(e,4))throw new Error("Invalid WAVE file - wrong format");let n=0,o=null,c=e.filePos;for(;null===s||c<s;){let e=this.reader.requestSlice(c,8);if(Re(e)&&(e=await e),!e)break;const t=rc(e,4),a=Xo(e,i),l=e.filePos;if(r&&0===n&&"ds64"!==t)throw new Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===t)await this.parseFmtChunk(l,a,i);else if("data"===t){if(o??(o=a),this.dataStart=e.filePos,this.dataSize=Math.min(o,(s??1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===t){let e=this.reader.requestSlice(l,a);if(Re(e)&&(e=await e),!e)break;const t=Yo(e,i);o=Yo(e,i),s=Math.min(t+8,this.reader.fileSize??1/0)}else"LIST"===t?await this.parseListChunk(l,a,i):"ID3 "!==t&&"id3 "!==t||await this.parseId3Chunk(l,a);c=l+a+(1&a),n++}if(!this.audioInfo)throw new Error('Invalid WAVE file - missing "fmt " chunk');if(-1===this.dataStart)throw new Error('Invalid WAVE file - missing "data" chunk');const l=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/l)*l,this.trackBackings.push(new Da(this))})())}async parseFmtChunk(e,t,i){let r=this.reader.requestSlice(e,t);if(Re(r)&&(r=await r),!r)return;let a=Ho(r,i);const s=Ho(r,i),n=Xo(r,i);r.skip(4);const o=Ho(r,i);let c;if(c=14===t?8:Ho(r,i),t>=18&&357!==a){const e=Ho(r,i),s=t-18;if(Math.min(s,e)>=22&&a===_a.EXTENSIBLE){r.skip(6);const e=qo(r,16);a=e[0]|e[1]<<8}}if(a!==_a.MULAW&&a!==_a.ALAW||(c=8),a!==_a.PCM&&a!==_a.IEEE_FLOAT&&a!==_a.ALAW&&a!==_a.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===_a.PCM&&![8,16,24,32].includes(c))throw new Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(a===_a.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,d,h,f;let m=this.reader.requestSlice(e,t);if(Re(m)&&(m=await m),!m)return;const p=rc(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=rc(m,4),t=Xo(m,i),p=qo(m,t);let k=0;for(let i=0;i<p.length&&0!==p[i];i++)k++;const y=String.fromCharCode(...p.subarray(0,k));switch((r=this.metadataTags).raw??(r.raw={}),this.metadataTags.raw[e]=y,e){case"INAM":case"TITL":(a=this.metadataTags).title??(a.title=y);break;case"TIT3":(s=this.metadataTags).description??(s.description=y);break;case"IART":(n=this.metadataTags).artist??(n.artist=y);break;case"IPRD":(o=this.metadataTags).album??(o.album=y);break;case"IPRT":case"ITRK":case"TRCK":{const e=y.split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&((c=this.metadataTags).trackNumber??(c.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((l=this.metadataTags).tracksTotal??(l.tracksTotal=i))}break;case"ICRD":case"IDIT":{const e=new Date(y);Number.isNaN(e.getTime())||((u=this.metadataTags).date??(u.date=e))}break;case"YEAR":{const e=Number.parseInt(y,10);Number.isInteger(e)&&e>0&&((d=this.metadataTags).date??(d.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(h=this.metadataTags).genre??(h.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(Re(i)&&(i=await i),!i)return;const r=mc(i);if(r){const a=t-uc;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+uc,r.size);pc(t,r,this.metadataTags)}}}getCodec(){if(E(this.audioInfo),this.audioInfo.format===_a.MULAW)return"ulaw";if(this.audioInfo.format===_a.ALAW)return"alaw";if(this.audioInfo.format===_a.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===_a.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}E(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Aa=2048;class Da{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return E(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(E(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return E(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return E(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return E(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 E(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return ue}getDisposition(){return{...Ge}}async getPacketAtIndex(e,t){E(e>=0),E(this.demuxer.audioInfo);const i=e*Aa*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(Aa*this.demuxer.audioInfo.blockSizeInBytes,this.demuxer.dataSize-i);if(null===this.demuxer.reader.fileSize){let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);if(Re(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=qi;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Re(e)&&(e=await e),E(e),a=qo(e,r)}const s=e*Aa/this.demuxer.audioInfo.sampleRate,n=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Wi(a,"key",s,n,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){E(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Aa,(this.demuxer.dataSize-1)/(Aa*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=await this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;E(null===this.demuxer.reader.fileSize);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){const e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){E(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Aa);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ma=e=>{const t=e.filePos,i=qo(e,9),r=new Qe(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const a=r.readBits(1),s=r.readBits(2)+1,n=r.readBits(4);if(15===n)return null;r.skipBits(1);const o=r.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const c=r.readBits(13);r.skipBits(11);const l=r.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===a?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:n,channelConfiguration:o,frameLength:c,numberOfAacFrames:l,crcCheck:u,startPos:t}},Na=1024;class Oa extends Ui{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new $,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();E(this.firstFrameHeader),this.trackBackings=[new za(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,uc);if(Re(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=mc(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Re(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ma(e);if(!t)return void(this.lastSampleLoaded=!0);if(null!==this.reader.fileSize&&t.startPos+t.frameLength>this.reader.fileSize)return void(this.lastSampleLoaded=!0);this.firstFrameHeader||(this.firstFrameHeader=t);const i=Ye[t.samplingFrequencyIndex];E(void 0!==i);const r=Na/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=Na,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,uc);if(Re(t)&&(t=await t),!t)break;const i=mc(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Re(r)&&(r=await r),!r)break;pc(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class za{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Na}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 ue}getCodec(){return"aac"}getInternalCodecId(){return E(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){E(this.demuxer.firstFrameHeader);const e=Je[this.demuxer.firstFrameHeader.channelConfiguration];return E(void 0!==e),e}getSampleRate(){E(this.demuxer.firstFrameHeader);const e=Ye[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return E(void 0!==e),e}getDisposition(){return{...Ge}}async getDecoderConfig(){return E(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=qi;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Re(e)&&(e=await e),!e)return null;r=qo(e,i.dataSize)}return new Wi(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=J(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Z(this.demuxer.loadedSamples,e,e=>e.timestamp);if(-1===i&&this.demuxer.loadedSamples.length>0)return null;if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(i,t);if(i>=0&&i+1<this.demuxer.loadedSamples.length)return this.getPacketAtIndex(i,t);await this.demuxer.advanceReader()}}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}class La extends Ui{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 $,this.lastSampleLoaded=!1,this.reader=e._reader}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}async getTrackBackings(){return await this.readMetadata(),E(this.trackBacking),[this.trackBacking]}async getMimeType(){return"audio/flac"}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{var e;let t=0;for(;;){let e=this.reader.requestSlice(t,uc);if(Re(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=mc(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Re(r)&&(r=await r),E(r),pc(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||t<this.reader.fileSize;){let i=this.reader.requestSlice(t,4);if(Re(i)&&(i=await i),t+=4,null===i)throw new Error(`Metadata block at position ${t} is too small! Corrupted file.`);E(i);const r=Wo(i),a=jo(i),s=0!==(128&r);switch(127&r){case jt.STREAMINFO:{let e=this.reader.requestSlice(t,a);if(Re(e)&&(e=await e),E(e),null===e)throw new Error(`StreamInfo block at position ${t} is too small! Corrupted file.`);const i=qo(e,34),r=new Qe(i),s=r.readBits(16),n=r.readBits(16),o=r.readBits(24),c=r.readBits(24),l=r.readBits(20),u=r.readBits(3)+1;r.readBits(5);const d=r.readBits(36);r.skipBits(128);const h=new Uint8Array(42);h.set(new Uint8Array([102,76,97,67]),0),h.set(new Uint8Array([128,0,0,34]),4),h.set(i,8),this.audioInfo={numberOfChannels:u,sampleRate:l,totalSamples:d,minimumBlockSize:s,maximumBlockSize:n,minimumFrameSize:o,maximumFrameSize:c,description:h},this.trackBacking=new Ua(this);break}case jt.VORBIS_COMMENT:{let e=this.reader.requestSlice(t,a);Re(e)&&(e=await e),E(e),Xt(qo(e,a),this.metadataTags);break}case jt.PICTURE:{let i=this.reader.requestSlice(t,a);Re(i)&&(i=await i),E(i);const r=$o(i),s=$o(i),n=O.decode(qo(i,s)),o=$o(i),c=O.decode(qo(i,o));i.skip(16);const l=$o(i),u=qo(i,l);(e=this.metadataTags).images??(e.images=[]),this.metadataTags.images.push({data:u,mimeType:n,kind:3===r?"coverFront":4===r?"coverBack":"unknown",description:c});break}}if(t+=a,s){this.lastLoadedPos=t;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")})())}async readNextFlacFrame({startPos:e,isFirstPacket:t}){E(this.audioInfo);const i=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,r=this.audioInfo.minimumFrameSize||10,a=(this.audioInfo.maximumFrameSize||i)+16,s=await this.reader.requestSliceRange(e,16,a);if(!s)return null;const n=this.readFlacFrameHeader({slice:s,isFirstPacket:t});if(!n)return null;for(s.filePos=e+r;;){if(s.filePos>s.end-6)return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:s.end-e,isLastFrame:!0};if(255===Wo(s)){const t=s.filePos;if(Wo(s)!==(1===this.blockingBit?249:248)){s.filePos=t;continue}s.skip(-2);const i=s.filePos-e,r=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!r){s.filePos=t;continue}if(0===this.blockingBit){if(r.num-n.num!==1){s.filePos=t;continue}}else if(r.num-n.num!==n.blockSize){s.filePos=t;continue}return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=qo(e,4),a=new Qe(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){E(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){E(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");E(!t);if(0!==a.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(a.readBits(4));if(!s)return null;E(this.audioInfo);const 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}})(a.readBits(4),this.audioInfo.sampleRate);if(!n)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const o=(e=>{let t=0;const i=new Qe(qo(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new Qe(qo(e,a)),n=8-t-1;for(let o=0;o<n;o++)r.unshift(i.readBits(1));for(let o=0;o<a;o++)for(let e=0;e<8;e++){const t=s.readBits(1);e<2||r.unshift(t)}return r.reduce((e,t,i)=>e|t<<i,0)})(e),c=((e,t)=>"uncommon-u16"===t?Vo(e)+1:"uncommon-u8"===t?Wo(e)+1:"number"===typeof t?t:(se(t),void E(!1)))(e,s),l=((e,t)=>"uncommon-u16"===t?Vo(e):"uncommon-u16-10"===t?10*Vo(e):"uncommon-u8"===t?Wo(e):"number"===typeof t?t:null)(e,n);if(null===l)return null;if(l!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,d=Wo(e);e.skip(-u),e.skip(-1);const h=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(qo(e,u));return d!==h?null:{num:o,blockSize:c,sampleRate:l}}async advanceReader(){await this.readMetadata(),E(null!==this.lastLoadedPos),E(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class Ua{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return E(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return E(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return ue}getTimeResolution(){return E(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 E(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...Ge}}async getDecoderConfig(){return E(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(E(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=Z(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){await this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],a=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=qi;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Re(e)&&(e=await e),!e)return null;r=qo(e,i.byteSize)}E(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Wi(r,"key",a,s,e,i.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const qa=9e4,Wa=2**33,Ha=188,Va="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.",ja=new Set([133,134,162]),Ka=new Set;class Xa extends Ui{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.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,205);Re(e)&&(e=await e),E(e);const t=qo(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=Ha;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,r=null,a=!1,s=!1;for(;;){const e=await this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){i+=this.packetStride;continue}const t=await this.readSection(i,!0,!s);if(!t)break;const n=3,o=32;let c=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new Qe(t.payload),i=e.readAlignedByte();e.skipBits(8*i);c=2===e.readBits(8)}}if(0!==t.pid||a)if(t.pid!==r&&!c||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=Ga(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(await this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const r=new es(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,await r.markNextPacket(),"avc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=gt(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];E(t);const i=wt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const a=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;a>0&&s>0&&(a>s?(e.info.squarePixelWidth=Math.round(e.info.width*a/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/a))),e.info.colorSpace={primaries:U[i.colourPrimaries],transfer:W[i.transferCharacteristics],matrix:V[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}if("hevc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid HEVC video stream; could not extract HVCDecoderConfigurationRecord from first packet.");if(e.info.hevcCodecInfo=xt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===nt.SPS_NUT).nalUnits[0];E(t);const i=It(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:U[i.colourPrimaries],transfer:W[i.transferCharacteristics],matrix:V[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:vi({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 new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=Lo.tempFromBytes(r.suppliedPacket.data),i=Ma(t);if(!i)throw new Error("Invalid AAC audio stream; could not read ADTS frame header from first packet.");e.info.aacCodecInfo={isMpeg2:!1,objectType:i.objectType},e.info.numberOfChannels=Je[i.channelConfiguration],e.info.sampleRate=Ye[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=$o(Lo.tempFromBytes(r.suppliedPacket.data)),i=Mi(t,r.suppliedPacket.data.byteLength);if(!i.header)throw new Error("Invalid MP3 audio stream; could not read frame header from first packet.");e.info.numberOfChannels=Li(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Gt(r.suppliedPacket.data);if(!t)throw new Error("Invalid AC-3 audio stream; could not read sync frame from first packet.");if(3===t.fscod)throw new Error("Invalid AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=$t[t.acmod]+t.lfeon,e.info.sampleRate=it[t.fscod]}else if("eac3"===e.info.codec){const t=Jt(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Zt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=ei(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=li(r.suppliedPacket.data);if(!t)throw new 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")}}e.info.decoderConfig={codec:Ii({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{const e=new Qe(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const a=e.readBits(10),c=e.pos+8*a;let l=!1;for(;e.pos<c;){const t=e.readBits(8),i=e.readBits(8),r=e.pos+8*i;if(5===t&&i>=4){const t=e.readBits(32);l||(l=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=c;8*(r+n)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),a=e.pos+8*r;let s=!1,n=!1,o=!1;for(;e.pos<a;){const 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)o=!0;else if(5===t&&i>=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let c=null;const u=l&&ja.has(t)?130:t;switch(u){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:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",c={type:"audio",codec:e,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}:o&&(c={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Ka.has(t)||(Ke._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Ka.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}s=!0}else{const e=new Qe(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+n)-e.pos>o;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==r)throw new Error("Only files with a single program are supported.");r=i}}if(null===r)throw new Error("Program Association Table must link to a Program Map Table.");a=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!a)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const n of this.elementaryStreams)n.initialized&&("video"===n.info.type?this.trackBackingEntries.push(new Ya(n)):this.trackBackingEntries.push(new Ja(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(n&&(h=1+e.body[0],e===c&&h>1&&(u=e.body[1]>>6&1)),d&&(0===h?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(h)),o+=e.body.byteLength-h)),r=a,!t&&o>=64){l=!1;break}if(-1!==J(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=Z(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!c)return null;if(1===s.length)n=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);n=new Uint8Array(e);let t=0;for(const i of s)n.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:c.pid,payload:n,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(Re(t)&&(t=await t),!t)return null;if(71!==Wo(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Vo(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:Wo(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,Ha);if(Re(t)&&(t=await t),!t)return null;const i=qo(t,Ha);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=Wa-t?-8589934592:Wa}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e<t?e+i:e}}const $a=(e,t,i)=>{if(t.payload.byteLength<3)return null;const r=new Qe(t.payload);if(1!==r.readBits(24))return null;const a=r.readBits(8);if(r.skipBits(16),188===a||190===a||191===a||240===a||241===a||255===a||242===a||248===a)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let n=null;if(2===s||3===s)n=0,r.skipBits(4),n+=r.readBits(3)*(1<<30),r.skipBits(1),n+=32768*r.readBits(15),r.skipBits(1),n+=r.readBits(15),n=e.normalizeTimestamp(n);else if(i)throw new Error(Va);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},Ga=(e,t,i)=>{E(null!==t.endPos);const r=$a(e,t,i);if(!r)return null;const a=new Qe(t.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const n=a.readBits(8),o=a.pos+8*n;a.pos=o;const c=o/8;E(Number.isInteger(c));const l=t.payload.subarray(c,s>0?6+s:t.payload.byteLength);return{...r,data:l}};class Qa{constructor(e){this.elementaryStream=e,this.packetBuffers=new WeakMap,this.packetSectionStarts=new WeakMap}getId(){return this.elementaryStream.pid}getNumber(){const e=this.elementaryStream.demuxer,t=this.elementaryStream.info.type;let i=0;for(const r of e.trackBackingEntries)if(r.getType()===t&&i++,E(r instanceof Qa),r.elementaryStream===this.elementaryStream)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.elementaryStream.streamType}getName(){return null}getLanguageCode(){return ue}getDisposition(){return{...Ge,primary:!1}}getTimeResolution(){return qa}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Wi(i.metadataOnly?qi:e.data,r,e.pts/qa,Math.max(t/qa,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;E(t);const i=Ga(this.elementaryStream.demuxer,t,!0);E(i);const r=new es(this.elementaryStream,i),a=new ts(this,r),s=await a.readNext();if(!s)return null;const n=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(n,a),this.packetSectionStarts.set(n,s.packet.sectionStartPos),n}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const r=await i.readNext();if(!r)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(a,i),this.packetSectionStarts.set(a,r.packet.sectionStartPos),a}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const a=this.elementaryStream.demuxer,s=await a.readSection(r,!0);E(s);const n=Ga(a,s,!0);E(n);const o=new es(this.elementaryStream,n);i=new ts(this,o);const c=e.sequenceNumber;for(;;){const e=await i.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){const 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),!i)return null;if("key"===i.type)return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){const r=de(e*qa),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:n}=a,o=this.elementaryStream.pid,c=async(e,t,i)=>{let r=e;for(;r<t;){const e=await a.readPacketHeader(r);if(!e)return null;if(e.pid===o&&1===e.payloadUnitStartIndicator){const e=await a.readSection(r,i);if(!e)return null;const t=$a(a,e,!1);if(t&&null!==t.pts)return{pesPacketHeader:t,section:e}}r+=a.packetStride}return null},l=this.elementaryStream.firstSection;E(l);const u=$a(a,l,!0);if(E(u),r<u.pts)return null;let d;const h=this.elementaryStream.referencePesPackets,f=Z(h,r,e=>e.pts),m=-1!==f?h[f]:null;if(m&&r-m.pts<45e3)d=m.sectionStartPos;else{let e=0;if(null!==s.fileSize){const t=Math.ceil(s.fileSize/n);if(t>1){let i=0,s=t-1;for(e=i;i<=s;){const t=Math.floor((i+s)/2),o=me(t*n,a.packetStride)+u.sectionStartPos,l=o+n,d=await c(o,l,!1);d?d.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}d=me(e*n,a.packetStride)+u.sectionStartPos}const p=await c(d,s.fileSize??1/0,!1);let g=p?.pesPacketHeader??null;g||(g=u);const k=this.getReorderSize(),y=async(e,t)=>{const s=await a.readSection(e,!0);E(s);const n=Ga(a,s,!0);E(n);const o=new es(this.elementaryStream,n),c=new ts(this,o);for(;;){if((R(c.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await c.readNextPacket()))break}const l=ae(c.presentationOrderPackets,t);if(-1===l)return null;const u=c.presentationOrderPackets[l],d=0===l?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=d;const h=await c.readNext();E(h);const f=this.createEncodedPacket(h.packet,h.duration,i);return this.packetBuffers.set(f,c),this.packetSectionStarts.set(f,h.packet.sectionStartPos),f};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=g.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=$a(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;g=e,Za(this.elementaryStream,g);break}}}e+=a.packetStride}}e:for(let e=0;e<k+1;e++){let e=g.sectionStartPos-a.packetStride;for(;e>=a.packetOffset;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=$a(a,t,!1);if(e&&null!==e.pts){g=e;break}}}e-=a.packetStride}}return y(g.sectionStartPos,e=>e.pts<=r)}{let e=d,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let d=null;const h=e<=u.sectionStartPos;let f,m=null;if(h)f=u,m=l;else{const t=await c(e,s.fileSize??1/0,i);f=t?.pesPacketHeader??null,m=t?.section??null}let p=!1,g=0;e:for(;f&&!(null!==t&&f.sectionStartPos>=t);){if(f.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===f.randomAccessIndicator;else{E(m);const t=Ga(a,m,!0);E(t);const i=new es(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(d=f)}if(f.pts>r&&(p=!0),p&&(g++,g>k))break;let e=f.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,i);if(t){const e=$a(a,t,!1);if(e&&null!==e.pts){f=e,m=t,Za(this.elementaryStream,f);break}}}e+=a.packetStride}}if(d){let e=d;if(0===g)e:for(let r=0;r<k;r++){let t=e.sectionStartPos-a.packetStride;for(;t>=a.packetOffset;){const r=await a.readPacketHeader(t);if(!r)break e;if(r.pid===o&&1===r.payloadUnitStartIndicator){const r=await a.readSection(t,i);if(r){const t=$a(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await y(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return E(t),t}if(h)return null;t=e,e=Math.max(me(e-u.sectionStartPos-n,a.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}}class Ya extends Qa{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return E(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Ja extends Qa{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return E(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Za=(e,t)=>{const i=e.referencePesPackets,r=Z(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const a=i[r];if(t.pts<=a.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos<s)return!1;if(r<i.length-1){const e=i[r+1];if(e.pts<t.pts)return!1;if(e.sectionStartPos-t.sectionStartPos<s)return!1}}return i.splice(r+1,0,t),!0};class es{constructor(e,t){this.currentPos=0,this.pesPackets=[],this.currentPesPacketIndex=0,this.currentPesPacketPos=0,this.endPos=0,this.lastSuppliedPesPacket=null,this.nextPts=null,this.suppliedPacket=null,this.elementaryStream=e,this.pid=e.pid,this.demuxer=e.demuxer,this.startingPesPacket=t}ensureBuffered(e){const t=this.endPos-this.currentPos;return t>=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return E(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos<t;){let e;if(0===this.pesPackets.length)e=this.startingPesPacket;else{let t=R(this.pesPackets).sectionEndPos;for(E(null!==t);;){const i=await this.demuxer.readPacketHeader(t);if(!i)return;if(i.pid===this.pid){const i=await this.demuxer.readSection(t,!0);if(!i)return;const r=Ga(this.demuxer,i,!1);if(r){e=r;break}}t+=this.demuxer.packetStride}}this.pesPackets.push(e),this.endPos+=e.data.byteLength}}readBytes(e){const t=this.getCurrentPesPacket(),i=this.currentPos-this.currentPesPacketPos,r=i+e;if(this.currentPos+=e,r<=t.data.byteLength)return t.data.subarray(i,r);const a=new Uint8Array(e);a.set(t.data.subarray(i));let s=t.data.byteLength-i;for(;;){this.advanceCurrentPacket();const t=this.getCurrentPesPacket(),i=e-s;if(i<=t.data.byteLength){a.set(t.data.subarray(0,i),s);break}a.set(t.data,s),s+=t.data.byteLength}return a}readU8(){let e=this.getCurrentPesPacket();const t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const e=this.getCurrentPesPacket();this.currentPesPacketPos-=e.data.byteLength}else for(;;){const t=this.getCurrentPesPacket();if(e<this.currentPesPacketPos+t.data.byteLength)break;this.currentPesPacketPos+=t.data.byteLength,this.currentPesPacketIndex++}this.currentPos=e}}skip(e){this.seekTo(this.currentPos+e)}advanceCurrentPacket(){this.currentPesPacketPos+=this.getCurrentPesPacket().data.byteLength,this.currentPesPacketIndex++}async markNextPacket(){E(!this.suppliedPacket);const e=this.elementaryStream;if("video"===e.info.type){const t=e.info.codec,i=1024;if("avc"!==t&&"hevc"!==t)throw new Error("Unhandled.");const r="avc"===t?1:2;let a=null,s=!1,n=0;for(;;){let e=this.ensureBuffered(i);if(Re(e)&&(e=await e),0===e)break;const o=this.currentPos,c=this.readBytes(e),l=c.byteLength;let u=0;for(;u<l;){const e=c.indexOf(0,u);if(-1===e||e>=l)break;u=e;const i=o+u;if(u+3>=l){this.seekTo(i);break}const d=c[u+1],h=c[u+2],f=c[u+3];let m=0;if(0===d&&0===h&&1===f?m=4:0===d&&1===h&&(m=3),0===m){u++;continue}const p=i;a??(a=p);const g=u+m,k=g+r,y=6;if(k+("avc"===t?y:1)>l){this.seekTo(i);break}const b=c[g];let w,T,S;if("avc"===t)w=dt(b),T=w===at.NON_IDR_SLICE||w===at.SLICE_DPA||w===at.IDR,S=w===at.SEI||w===at.SPS||w===at.PPS||w===at.AUD;else{w=Pt(b);if(((1&b)<<5|c[g+1]>>3)>0){u+=m;continue}T=w<=nt.RASL_R||w>=nt.BLA_W_LP&&w<=21,S=w>=nt.VPS_NUT&&w<=37||w===nt.PREFIX_SEI_NUT||w>=41&&w<=44||w>=48&&w<=55}let v=!1;if(T){let e;if("avc"===t){const t=c.subarray(k,k+y),i=F(new Qe(t));e=!s||i<=n,n=i}else e=c[k]>>7===1;e&&(s?v=!0:s=!0)}else S&&s&&(v=!0);if(v){const e=p-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=m}if(e<i)break}if(null!==a&&this.endPos>a){const e=this.endPos-a;return this.seekTo(a),this.supplyPacket(e,0)}}else{const t=e.info.codec,i=128;for(;;){let r=this.ensureBuffered(i);Re(r)&&(r=await r);const a=this.currentPos;for(;this.currentPos-a<r;){const i=this.readU8();if("aac"===t){if(255!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(9);if(Re(r)&&(r=await r),r<9)return;const a=this.readBytes(9),s=Ma(Lo.tempFromBytes(a));if(s){this.seekTo(t);let i=this.ensureBuffered(s.frameLength);return Re(i)&&(i=await i),this.supplyPacket(i,Math.round(9216e4/e.info.sampleRate))}this.seekTo(t+1)}else{if("mp3"!==t){if("ac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(Re(r)&&(r=await r),r<5)return;const a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}const s=a[4]>>6,n=63&a[4];if(3===s||n>37){this.seekTo(t+1);continue}const o=Qt[3*n+s];E(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),Re(r)&&(r=await r);const c=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,c)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(Re(r)&&(r=await r),r<5)return;const a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}const s=2*(((7&a[2])<<8|a[3])+1),n=3===a[4]>>6?3:a[4]>>4&3,o=Yt[n];this.seekTo(t),r=this.ensureBuffered(s),Re(r)&&(r=await r);const c=256*o,l=Math.round(c*qa/e.info.sampleRate);return this.supplyPacket(r,l)}if("dts"===t){if(127!==i&&100!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(18);if(Re(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=di(a);let n=s?null:hi(a);if(!s&&!n){this.seekTo(t+1);continue}if(n&&!n.asset){this.seekTo(t);const e=Math.min(n.frameSize,4096);let i=this.ensureBuffered(e);Re(i)&&(i=await i),n=hi(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);const i=e+10;let r=this.ensureBuffered(i);if(Re(r)&&(r=await r),r<i)break;this.seekTo(t+e);const a=hi(this.readBytes(10));if(!a)break;e+=a.frameSize,o=e}}const c=s?.sampleCount??n.asset?.sampleCount;if(void 0===c){this.seekTo(t+1);continue}this.seekTo(t),r=this.ensureBuffered(o),Re(r)&&(r=await r);const l=Math.round(c*qa/e.info.sampleRate);return this.supplyPacket(r,l)}throw new Error("Unhandled.")}{if(255!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(4);if(Re(r)&&(r=await r),r<4)return;const a=this.readBytes(4),s=N(a).getUint32(0),n=Mi(s,null);if(n.header){this.seekTo(t);let i=this.ensureBuffered(n.header.totalSize);Re(i)&&(i=await i);const r=n.header.audioSamplesInFrame*qa/e.info.sampleRate;return this.supplyPacket(i,Math.round(r))}this.seekTo(t+1)}}}if(r<i)break}}}supplyPacket(e,t){const i=this.getCurrentPesPacket();let r;if(this.lastSuppliedPesPacket===i)E(null!==this.nextPts),r=this.nextPts;else{if(null===i.pts)throw new Error(Va);r=i.pts,Za(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=r+t;const a=i.sectionStartPos,s=a+(this.currentPos-this.currentPesPacketPos),n=this.readBytes(e);let o=i.randomAccessIndicator;if(0===o&&!this.elementaryStream.canBeTrustedWithKeyPackets)if("audio"===this.elementaryStream.info.type)o=1;else if(this.elementaryStream.info.decoderConfig){const e="key"===Vt(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,n);o=Number(e)}this.suppliedPacket={pts:r,data:n,sequenceNumber:s,sectionStartPos:a,randomAccessIndicator:o},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class ts{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(),E(this.reorderSize>=0)}async readNext(){if(0===this.decodeOrderPackets.length){if(!(await this.readNextPacket()))return null}await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(E(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(E(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(await this.readNextPacket()))break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;i<this.reorderBuffer.length;i++)this.reorderBuffer[i].pts<this.reorderBuffer[e].pts&&(e=i);const t=this.reorderBuffer[e];this.presentationOrderPackets.push(t),this.reorderBuffer.splice(e,1)}}flushReorderBuffer(){this.reorderBuffer.sort((e,t)=>e.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const is="application/vnd.apple.mpegurl",rs="#EXT-X-STREAM-INF:",as="#EXT-X-I-FRAME-STREAM-INF:",ss="#EXT-X-MEDIA:",ns="#EXTINF:",os="#EXT-X-MAP:",cs="#EXT-X-KEY:",ls="#EXT-X-MEDIA-SEQUENCE:",us="#EXT-X-BYTERANGE:",ds="#EXT-X-PROGRAM-DATE-TIME:",hs="#EXT-X-TARGETDURATION:",fs="#EXT-X-PLAYLIST-TYPE:",ms=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class ps{constructor(e){this._attributes={};let t="",i="",r=!1,a=!1;for(let s=0;s<e.length;s++){const n=e[s];'"'===n?a=!a:"="!==n||r||a?","!==n||a?r?i+=n:t+=n:(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",r=!1):r=!0}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){return this._attributes[e.toLowerCase()]??null}getAsNumber(e){const t=this.get(e);if(null===t)return null;const i=Number(t);return Number.isFinite(i)?i:null}merge(e){Object.assign(this._attributes,e._attributes)}}class gs{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}async getDurationFromMetadata(e){const 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??(t=await this.getFirstSegment({})),!t||null===t.unixEpochTimestamp)return null;const i=e-t.timestamp;return t.unixEpochTimestamp+i}async getTrackBackings(){return this.trackBackingsPromise??(this.trackBackingsPromise=(async()=>{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=ze(e,e=>"video"===e.getType())+1;e.push(new ys(this,t,i))}else if("audio"===t.type){const i=ze(e,e=>"audio"===e.getType())+1;e.push(new bs(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=await t.getTracks();for(const r of i)if("video"===r.type){const t=ze(e,e=>"video"===e.getType())+1;e.push(new ys(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=ze(e,e=>"audio"===e.getType())+1;e.push(new bs(this,{id:e.length+1,type:"audio"},t))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let r;if(this.firstSegmentFirstTimestamps.has(i))r=this.firstSegmentFirstTimestamps.get(i);else{const e=this.getInputForSegment(i);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(i,r)}if(i===e)return i.timestamp-r;const a=await this.getFirstTimestampForInput(t),s=e.timestamp-i.timestamp,n=a-r-s;return Math.abs(n)<=Math.min(.25,s)?i.timestamp-r:e.timestamp-a}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class ks{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??(this.hydrationPromise=(async()=>{var e;if((e=this.segmentedInput).firstSegment??(e.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let t=this.segmentedInput.firstSegment,i=null;for(;t;){const e=this.segmentedInput.getInputForSegment(t);if(i=(await e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,i)break;t=await this.segmentedInput.getNextSegment(t,{})}if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i,this.firstSegment=t})())}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(),E(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)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){E(e.sequenceNumber>=0),E(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:fe(e.timestamp+r,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s}async getFirstPacket(e){await this.hydrate(),E(this.firstInputTrack),E(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){const r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,i,t)}if(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait}),!i)break;const 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){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const a=i?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(a)return this.createAdjustedPacket(a,r.segment,r.track);let s=r.segment;for(;;){const e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=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}const n=await a._backing.getFirstPacket(t);return n?this.createAdjustedPacket(n,e,a):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){const a=this.segmentedInput.getInputForSegment(r),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const n=e-await this.segmentedInput.getMediaOffset(r,a),o=i?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(o)return this.createAdjustedPacket(o,r,s);r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null}}class ys extends ks{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class bs extends ks{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())}}Me();const ws=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class Ts extends He{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 Oo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,ws),e=this._getFileSize(),E(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new Oo;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Ns(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Ss(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Ss{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;E(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class vs extends Ts{constructor(e,t){if("string"!==typeof e)throw new TypeError("rootPath must be a string.");if("function"!==typeof t)throw new TypeError("requestHandler must be a function.");super(),this.rootPath=e,this.requestHandler=t}_resolveRequest(e){const t=this.requestHandler(e),i=e=>{var t;if(!(e instanceof Ts||e instanceof Ss))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof Ts?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Re(t)?t.then(i):i(t)}}const Ps=(e,t)=>e.path===t.path;class Is extends vs{constructor(){super(...arguments),this._root=null,this._rootRequest=null}_read(e,t,i,r){if(!this._root){if(!this._rootRequest){const e=this._resolveRequest({path:this.rootPath,isRoot:!0}),t=e=>{const t=e instanceof Ts?e.ref():e;return this._root=t,this._rootRequest=null,t};Re(e)?this._rootRequest=e.then(t):(t(e),E(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())}}const xs="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class Cs extends Ts{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!Ne(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Ms({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),xs?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Ds.fileSystem,handleUnhandledError:t.handleUnhandledError}),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){E(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Pe()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),xs?.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:i,value:r}=await t.read();if(i)throw this._orchestrator.onWorkerFinished(e),new Error("Blob reader stopped unexpectedly before all requested data was read.");if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+r.length),this._orchestrator.supplyWorkerData(e,r)}else{const t=await this._blob.slice(e.currentPos,e.targetPos).arrayBuffer();if(e.aborted)break;this._dispatchRead(e.currentPos,e.currentPos+t.byteLength),this._orchestrator.supplyWorkerData(e,new Uint8Array(t))}this._orchestrator.signalWorkerStoppedRunning(e),e.aborted&&await(t?.cancel())}_dispose(){this._orchestrator.dispose()}}const Bs=(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&&"undefined"!==typeof 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 Ke._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)},Es=new Set;class _s extends vs{constructor(e,t={}){if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Ne(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new _s(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??Bs,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...we(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){const t=e.headers.get("Range");if(null!==t){i??(i=t);const r=new Request(e);r.headers.delete("Range"),this._url=r}}if(null!==i){const e=Fs(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new Ms({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:Ds.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:le(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const a=this._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 Re(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await Te(this._options.fetchFn??fetch,this._url,be(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);r.redirected&&(this.rootPath=r.url);e:if(null===this._orchestrator.fileSize&&(206===r.status||"basic"===r.type&&!r.headers.has("Content-Encoding"))){const t=r.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=r.headers.get("Content-Length");if(i){const t=206===r.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==r.status){if(this._sequentialBacking)return void r.body.cancel();if(!this._usedForHls){const 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")||Es.has(e.origin)||(Ke._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.`),Es.add(e.origin))}return void this._transitionToSequentialMode(r.body)}const a=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return i.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let r;try{r=await a.read()}catch(t){if(this._disposed)throw t;const e=this._getRetryDelay(1,t,this._url);if(null!==e){Ke._error("Error while reading response stream. Attempting to resume.",t),await We(1e3*e);break}throw t}if(e.aborted)continue;const{done:s,value:n}=r;if(s){if(e.currentPos>=e.targetPos)return void this._orchestrator.onWorkerFinished(e);if(e.strictTarget)break;return void this._orchestrator.onWorkerFinished(e)}this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const a=new ReadableStream({pull:async e=>{for(;;){let s;try{s=await t.read()}catch(a){if(this._disposed)throw a;const e=this._getRetryDelay(1,a,this._url);if(null===e)throw a;Ke._error("Error while reading response stream. Attempting to resume.",a),await We(1e3*e);const s=await Te(this._options.fetchFn??fetch,this._url,be(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=s.body.getReader(),r=206===s.status?0:i;continue}if(s.done)return void e.close();let n=s.value;if(r>0){const e=Math.min(r,n.length);r-=e,n=n.subarray(e)}if(0!==n.length)return i+=n.length,void e.enqueue(n)}},cancel:()=>t.cancel()}),s=new As(a,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});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;const n=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)n.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)n.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of n){const e=s._read(o.start,o.start+o.bytes.length);Re(e)?e.then(e=>{e?(E(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(E(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Rs=/^bytes=(\d+)-(\d*)$/,Fs=e=>{const t=Rs.exec(e.trim());if(!t)return null;const 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 As extends Ts{constructor(e,t={}){if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Ne(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._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??33554432,this._handleUnhandledError=t.handleUnhandledError}_getFileSize(){return this._endIndex}_read(e,t){if(null!==this._endIndex&&t>this._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=Z(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let a=e;const s=new Uint8Array(t-e);if(-1!==i)for(let l=i;l<this._cache.length;l++){const i=this._cache[l];if(i.start>=t)break;const r=Math.max(e,i.start);r>a&&this._throwDueToCacheMiss();const n=Math.min(t,i.end);r<n&&(s.set(i.bytes.subarray(r-i.start,n-i.start),r-e),a=n)}if(a===t)return{bytes:s,view:N(s),offset:e};this._currentIndex>a&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:c}=te();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),n}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=await this._reader.read();if(e){for(const e of this._pendingSlices)e.resolve(null);this._pendingSlices.length=0,this._endIndex=this._currentIndex;break}const i=this._currentIndex,r=this._currentIndex+t.byteLength;this._dispatchRead(i,r);for(let a=0;a<this._pendingSlices.length;a++){const e=this._pendingSlices[a],s=Math.max(i,e.start),n=Math.min(r,e.end);s<n&&(e.bytes.set(t.subarray(s-i,n-i),s-e.start),n===e.end&&(e.resolve({bytes:e.bytes,view:N(e.bytes),offset:e.start}),this._pendingSlices.splice(a,1),a--))}for(this._cache.push({start:i,end:r,bytes:t,view:N(t),age:0});this._cache.length>0;){const e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new Oo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Ds={fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(Ae(e,t,r,a.targetPos)){const e=a.targetPos-a.startPos,r=Math.ceil((e+1)/i)*i,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,r);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+524288)}}};class Ms{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){E(!this.disposed);const a=this.options.prefetchProfile(e,t,this.workers),s=Math.max(a.start,i),n=Math.min(a.end,this.fileSize??1/0,r);E(s<=e&&t<=n);let o=null;const c=Z(this.cache,e,e=>e.start),l=-1!==c?this.cache[c]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,o={bytes:l.bytes,view:l.view,offset:l.start});const u=Z(this.cache,s,e=>e.start),d=o?null:new Uint8Array(t-e);let h=0,f=s;const m=[];if(-1!==u){for(let i=u;i<this.cache.length;i++){const r=this.cache[i];if(r.start>=n)break;if(r.end<=s)continue;const a=Math.max(s,r.start),o=Math.min(n,r.end);if(E(a<=o),f<a&&m.push({start:f,end:a}),f=o,d){const i=Math.max(e,r.start),a=Math.min(t,r.end);if(i<a){const t=i-e;d.set(r.bytes.subarray(i-r.start,a-r.start),t),t===h&&(h=a-e)}}r.age=this.nextAge++}f<n&&m.push({start:f,end:n})}else m.push({start:s,end:n});if(d&&h>=d.length&&(o={bytes:d,view:N(d),offset:e}),0===m.length)return E(o),o;const{promise:p,resolve:g,reject:k}=te(),y=[];for(const w of m){const i=Math.max(e,w.start),r=Math.min(t,w.end);i===w.start&&r===w.end?y.push(w):i<r&&y.push({start:i,end:r})}const b=d&&{start:e,bytes:d,holes:y,resolve:g,reject:k};e:for(const w of m){for(const i of this.workers){if(this.checkHoleAgainstWorker(i,w,b?[b]:[])){this.checkQueuedReadsAgainstWorker(i);continue e}}const e=w.end<n||null!==this.fileSize,t=this.createWorker(w.start,w.end,e);if(t)b&&(t.pendingSlices=[b]),this.runWorker(t);else{let t=Z(this.queuedReads,w.start,e=>e.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&w.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,w.end),i.strictTarget&&(i.strictTarget=e),b&&i.pendingSlices.push(b)):(t++,i={hole:{start:w.start,end:w.end},strictTarget:e,pendingSlices:b?[b]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1<this.queuedReads.length;){const e=this.queuedReads[t+1];if(e.hole.start>i.hole.end)break;i.hole.end=Math.max(i.hole.end,e.hole.end),i.pendingSlices.push(...e.pendingSlices),i.strictTarget&&(i.strictTarget=e.strictTarget),i.age=Math.min(i.age,e.age),this.queuedReads.splice(t+1,1)}}}return o?p.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(E(d),o=p.then(t=>t&&{bytes:t,view:N(t),offset:e})),o}checkHoleAgainstWorker(e,t,i){if(Ae(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t<i.length;t++){const r=i[t];e.pendingSlices.includes(r)||e.pendingSlices.push(r)}return e.running||this.runWorker(e),!0}return!1}checkQueuedReadsAgainstWorker(e){let t=!1;for(let i=0;i<this.queuedReads.length;i++){const r=this.queuedReads[i];if(this.checkHoleAgainstWorker(e,r.hole,r.pendingSlices))this.queuedReads.splice(i,1),i--,t=!0;else if(t)break}}createWorker(e,t,i){if(this.workers.length>=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i<this.workers.length;i++){const r=this.workers[i];r.running||0!==r.pendingSlices.length||e&&!(r.age<e.age)||(t=i,e=r)}if(!e)return null;E(null!==t),E(0===e.pendingSlices.length),this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e)}const 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){E(!e.running),E(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;r<this.queuedReads.length;r++){this.queuedReads[r].age<this.queuedReads[e].age&&(e=r)}const t=this.queuedReads[e],i=this.createWorker(t.hole.start,t.hole.end,t.strictTarget);if(!i)return;this.queuedReads.splice(e,1),i.pendingSlices=t.pendingSlices,this.runWorker(i)}})}supplyWorkerData(e,t){E(!e.aborted);const i=e.currentPos,r=i+t.length;this.insertIntoCache({start:i,end:r,bytes:t,view:N(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++){const 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++){const 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 a=0;a<this.workers.length;a++){const t=this.workers[a];e===t||t.running||Ae(i,r,t.currentPos,t.targetPos)&&(this.workers.splice(a,1),this.options.onIdleWorkerRemoved?.(t),a--)}}supplyFileSize(e){E(null===this.fileSize),this.fileSize=e;for(const t of this.workers){t.targetPos=Math.min(t.targetPos,e),t.strictTarget=!0;for(let i=0;i<t.pendingSlices.length;i++){const r=t.pendingSlices[i];for(const a of r.holes)if(a.end>e){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t<this.queuedReads.length;t++){const i=this.queuedReads[t];if(i.hole.start>=e){for(const e of i.pendingSlices)e.resolve(null);this.queuedReads.splice(t,1),t--}else if(i.hole.end>e){i.hole.end=e,i.strictTarget=!0;for(let t=0;t<i.pendingSlices.length;t++){const r=i.pendingSlices[t];r.start>=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const t=this.workers.indexOf(e);E(-1!==t),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=Z(this.cache,e.start,e=>e.start)+1;if(t>0){const i=this.cache[t-1];if(i.end>=e.end)return;if(i.end>e.start){const r=new Uint8Array(e.end-i.start);r.set(i.bytes,0),r.set(e.bytes,e.start-i.start),this.currentCacheSize+=e.end-i.end,i.bytes=r,i.view=N(r),i.end=e.end,t--,e=i}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length}else this.cache.splice(t,0,e),this.currentCacheSize+=e.bytes.length;for(let i=t+1;i<this.cache.length;i++){const t=this.cache[i];if(e.end<=t.start)break;if(e.end>=t.end){this.cache.splice(i,1),this.currentCacheSize-=t.bytes.length,i--;continue}const r=new Uint8Array(t.end-e.start);r.set(e.bytes,0),r.set(t.bytes,t.start-e.start),this.currentCacheSize-=e.end-t.start,e.bytes=r,e.view=N(r),e.end=t.end,this.cache.splice(i,1);break}for(;this.currentCacheSize>this.options.maxCacheSize;){let e=0,t=this.cache[0];for(let i=1;i<this.cache.length;i++){const r=this.cache[i];r.age<t.age&&(e=i,t=r)}if(this.currentCacheSize-t.bytes.length<=this.options.maxCacheSize)break;this.cache.splice(e,1),this.currentCacheSize-=t.bytes.length}}dispose(){for(const e of this.workers){for(const t of e.pendingSlices)t.reject(new Oo);e.pendingSlices.length=0,e.aborted=!0,e.running||this.options.onIdleWorkerRemoved?.(e)}for(const e of this.queuedReads)for(const t of e.pendingSlices)t.reject(new Oo);this.workers.length=0,this.cache.length=0,this.queuedReads.length=0,this.disposed=!0}}class Ns extends Ts{constructor(e,t,i){if(super(),this._ref=null,e._disposed)throw new Error("Cannot create a slice of a disposed source.");this._baseSource=e,this._offset=t,this._length=i??null}_getFileSize(){const e=this._baseSource._getFileSize();return void 0===e?null!==this._length?this._length:void 0:null===e?null!==this._length?this._length:null:le(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return Re(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var Os=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},zs=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const Ls=/^0[xX][0-9a-fA-F]+$/,Us=/^data:.*;base64,/i;class qs extends gs{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??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await We(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const t={stack:[],error:void 0,hasError:!1};try{const i=Os(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new zo(i.source),a=await r.requestEntireFile();E(a),e=ac(a,a.length,{ignore:ms}),i.source instanceof vs&&(this.rootPath=i.source.rootPath)}catch(y){t.error=y,t.hasError=!0}finally{zs(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,n=null,o=0,c=null,l=null,u=null,d=null,h=null,f=null,m=!1,p=R(this.segments)??null;const g=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},k=e=>{o=e,p&&(E(null!==p.sequenceNumber),p.sequenceNumber<e&&(r=p.timestamp+p.duration,c=p.firstSegment,l=p.initSegment,h=p.lastProgramDateTimeSeconds,a=null!==p.unixEpochTimestamp?p.unixEpochTimestamp+p.duration:null,p=null))};for(let b=0;b<e.length;b++){const y=e[b];if(i){if(!y.startsWith("#")){if(!p){if(null===s)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let e=n;if(e&&"AES-128"===e.method&&!e.iv){const t=new Uint8Array(Yi),i=N(t);i.setUint32(8,Math.floor(o/2**32)),i.setUint32(12,o),e={...e,iv:t}}const t=Oe(this.rootPath,y),i={timestamp:r,unixEpochTimestamp:a,firstSegment:c,sequenceNumber:o,location:{path:t,offset:d?.offset??0,length:d?.length??null},duration:s,encryption:e,initSegment:l,lastProgramDateTimeSeconds:h};c??(c=i),r+=s,null!==a&&(a+=s),this.segments.push(i)}s=null,null===d?u=null:d=null,k(o+1)}if(y.startsWith(ns)){if(p){m=!0;continue}m||(null===h&&o>0&&null!==f&&(r=o*f),m=!0);const e=y.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);s=a}else if(y.startsWith(os)){const e=new ps(y.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let o=null;if(null!==i&&(o=g(i)),o&&null===o.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!p){const e={path:Oe(this.rootPath,t),offset:o?.offset??0,length:o?.length??null};if("AES-128"===n?.method&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:h}}s=null,null===d?u=null:d=null}else if(y.startsWith(cs)){const e=new ps(y.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!Ls.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Yi);for(let t=0;t<Yi;t++){const r=-32+t;i[t]=parseInt(e.slice(r,r+2),16)}}const a=e.get("keyformat")??"identity";if("identity"!==a)throw new Error("For AES-128 encryption, only the 'identity' KEYFORMAT is currently supported. If you think other formats should be supported, please raise an issue.");n={method:"AES-128",keyUri:Oe(this.rootPath,t),iv:i,keyFormat:a}}else{if("SAMPLE-AES"!==t&&"SAMPLE-AES-CTR"!==t)throw new Error(`Unsupported encryption method '${t}'. If you think this method should be supported, please raise an issue.`);{const i=e.get("uri");if(!i)throw new Error(`Invalid #EXT-X-KEY: ${t} requires a URI attribute.`);if("identity"===(e.get("keyformat")??"identity"))throw new Error("For SAMPLE-AES and SAMPLE-AES-CTR encryption, the 'identity' KEYFORMAT is not supported. If you think this format should be supported, please raise an issue.");let r=null;if(Us.test(i)){const e=i.indexOf(","),t=De(i.slice(e+1));if(t.length>=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=N(t).getUint32(0);r=Hi(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(y.startsWith(ls)){const e=y.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);k(t)}else if(y.startsWith(us)){const e=g(y.slice(17));if(null===e.offset){if(null===u)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=u}d=e,u=e.offset+e.length}else if(y.startsWith(ds)){if(p)continue;const e=y.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(h===s)continue;if(null===h&&this.segments.length>0){const e=R(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}h=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===y)c=null;else if(y.startsWith(hs)){const e=y.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,f=t}else{if("#EXT-X-ENDLIST"===y){this.streamHasEnded=!0;break}if(y.startsWith(fs)){"vod"===y.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==y)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0}}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return 0===this.segments.length&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){0===this.segments.length&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=Z(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r<this.segments.length-1||this.streamHasEnded||i)return this.segments[r];const a=this.segments[r];if(e<a.timestamp+a.duration)return a;await this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}}async getNextSegment(e,t){const i=this.segments.indexOf(e);E(-1!==i);const r=i+1;let a=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(r<this.segments.length)return this.segments[r];if(this.streamHasEnded||a)return null;await this.runUpdateSegments(),t.skipLiveWait&&(a=!0)}}async getPreviousSegment(e){const t=this.segments.indexOf(e);return E(-1!==t),this.segments[t-1]??null}getInputForSegment(e){const t=e,i=this.inputCache.find(e=>e.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let r=null;(t.initSegment||t.firstSegment)&&(r=this.getInputForSegment(t.initSegment??t.firstSegment));const a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let i=e.psshBoxes;const{psshBox:r}=t.encryption;return null!==r.keyIds&&!r.keyIds.includes(e.keyId)||i.some(e=>Vi(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new Mo({source:new Is(t.location.path,async e=>{E(e.isRoot);const i={...e,isRoot:!1};let r;const a=t.location.offset>0||null!==t.location.length;if(t.encryption&&"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method)if("AES-128"===t.encryption.method){const e=t.encryption;E(e.iv);let s=await this.input._getSourceCached(i);if(a){const e=s.source.slice(t.location.offset,t.location.length??void 0).ref();s.free(),s=e}const n=((e,t,i)=>{let r=!1,a=0;const s=new nr;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(Re(o)&&(o=await o),!o||0===o.length)throw new Error("Invalid ciphertext.");const c=o.length;if(c%16!==0)throw new Error("Invalid ciphertext.");const l=65552===c?c-16:c,u=qo(o,l),d=new Uint8Array(l);for(let e=0;e<l;e+=16)s.in.set(u.subarray(e,e+16)),s.decrypt(),d.set(s.out,e);if(l<c)n.enqueue(d),a+=l;else{const e=d[l-1];if(0===e||e>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=d.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new zo(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=Os(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},Do),!1),r=new zo(i.source),a=await r.requestSlice(0,Yi);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:qo(a,Yi),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{zs(t)}},()=>{s.free()});r=new As(n).ref()}else E(!1);else if(r=await this.input._getSourceCached(i),a){const e=r.source.slice(t.location.offset,t.location.length??void 0).ref();r.free(),r=e}return r}),formats:this.input._formats.filter(e=>!(e instanceof cn)),initInput:r??void 0,formatOptions:a});s._onFormatDetermined=e=>{if(("SAMPLE-AES"===t.encryption?.method||"SAMPLE-AES-CTR"===t.encryption?.method)&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:s,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=Le(this.inputCache,e=>e.age);E(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class Ws extends Ui{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{E(this.input._rootSource instanceof vs);const e=await this.input._reader.requestEntireFile();E(e);const t=ac(e,e.length,{ignore:ms}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let u=1;u<t.length;u++){const e=t[u];if(e.startsWith(rs)){const a=u,s=t[++u];if(void 0===s)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const n=Oe(i,s),o=new ps(e.slice(18));if(null===o.getAsNumber("bandwidth"))throw new Error("Invalid M3U8 file; #EXT-X-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");r.push({fullPath:n,attributes:o,lineNumber:a,hasOnlyKeyPackets:!1})}else if(e.startsWith(as)){const t=new ps(e.slice(26)),a=t.get("uri");if(null===a)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(null===t.getAsNumber("bandwidth"))throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a BANDWIDTH attribute with a valid numerical value.");const s=Oe(i,a);r.push({fullPath:s,attributes:t,lineNumber:u,hasOnlyKeyPackets:!0})}else if(e.startsWith(ss)){const t=new ps(e.slice(13));if(null===t.get("type"))throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(null===t.get("group-id"))throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let r=null;const s=t.get("uri");null!==s&&(r=Oe(i,s)),a.push({fullPath:r,attributes:t,lineNumber:u})}else if("#EXT-X-I-FRAMES-ONLY"===e);else if(e.startsWith(ns)){const e=new qs(this,i,null,t);return this.segmentedInputs=[e],this.hasMasterPlaylist=!1,void(this.trackBackings=await e.getTrackBackings())}}const s=[...new Set(a.filter(e=>"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],n=[...new Set(a.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=await Promise.all(r.map(async(e,t)=>{const r=[],o=e.attributes.get("codecs");let c;if(o)c=o.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=await t.getTrackBackings(),r=await Promise.all(i.map(async e=>({track:e,codec:await e.getCodec()})));c=await Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const l=e.attributes.get("video"),u=e.attributes.get("audio"),d=c.some(e=>mi.includes(Ei(e))),h=c.some(e=>gi.includes(Ei(e)));if(null!==l&&!d){if(!s.includes(l))throw new Error(`Invalid M3U8 file; variant stream references video group "${l}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===l&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Oe(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);E(null!==n),c.push(n)}}if(null!==u&&!h){if(!n.includes(u))throw new Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Oe(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);E(null!==n),c.push(n)}}c=[...new Set(c)];let f=null,m=null;const p=e.attributes.getAsNumber("bandwidth");E(null!==p);const g=e.attributes.getAsNumber("average-bandwidth"),k=e.attributes.get("name");for(const i of c){const o=Ei(i);if(null!==o)if(mi.includes(o)){if(null!==f)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");f=i;const n=e.attributes.get("video");if(null===n){const i=e.attributes.get("resolution");let a=null,s=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(a=Number(e[1]),s=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ue,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:f,pairingMask:1n<<BigInt(t),peakBitrate:p,averageBitrate:g,name:k,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"video",width:a,height:s}})}else{if(!s.includes(n))throw new Error(`Invalid M3U8 file; variant stream references video group "${n}" which is not defined in any #EXT-X-MEDIA tags.`);for(const i of a){const a=i.attributes.get("group-id"),s=i.attributes.get("type");if(a!==n||"video"!==s.toLowerCase())continue;const o=i.attributes.get("resolution")??e.attributes.get("resolution");let c=null,l=null;if(o){const e=o.match(/^(\d+)x(\d+)$/);e&&(c=Number(e[1]),l=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:Ks(i.attributes),autoselect:Ks(i.attributes)||Xs(i.attributes),languageCode:$s(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:c,height:l}})}}}else if(gi.includes(o)){if(null!==m)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");m=i;const s=e.attributes.get("audio");if(null===s){const i=e.attributes.get("channels"),a=null!==i?Number(i.split("/")[0]):null;r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:ue,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:p,averageBitrate:g,name:k,hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==a&&Number.isInteger(a)&&a>0?a:null}})}else{if(!n.includes(s))throw new Error(`Invalid M3U8 file; variant stream references audio group "${s}" which is not defined in any #EXT-X-MEDIA tags.`);for(const i of a){const a=i.attributes.get("group-id"),n=i.attributes.get("type");if(a!==s||"audio"!==n.toLowerCase())continue;const o=i.attributes.get("channels")??e.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;r.push({id:-1,demuxer:this,backingTrack:null,default:Ks(i.attributes),autoselect:Ks(i.attributes)||Xs(i.attributes),languageCode:$s(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<<BigInt(t),peakBitrate:null,averageBitrate:null,name:i.attributes.get("name"),hasOnlyKeyPackets:e.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==c&&Number.isInteger(c)&&c>0?c:null}})}}}}return r})),c=[],l=e=>{const t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||(t.default=e.default),t.autoselect||(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)),t.languageCode===ue&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(const u of o)for(const e of u)l(e);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of c)"video"===u.info.type?this.trackBackings.push(new Vs(u)):this.trackBackings.push(new js(u));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),E(this.trackBackings),this.trackBackings}getSegmentedInputForPath(e){let t=this.segmentedInputs.find(t=>t.path===e);if(t)return t;let i=null;if(this.internalTracks){i=this.internalTracks.filter(t=>t.fullPath===e).map(e=>({id:e.id,type:e.info.type}))}return t=new qs(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return is}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Hs{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof Vs){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{E(this instanceof js);for(const e of i)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...Ge,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(){E(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}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)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class Vs extends Hs{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ei(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class js extends Hs{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ei(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()}}const Ks=e=>{const t=e.get("default");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA DEFAULT attribute must be YES or NO, got "${t}".`)},Xs=e=>{const t=e.get("autoselect");if(null===t)return!1;const i=t.toUpperCase();if("YES"===i)return!0;if("NO"===i)return!1;throw new Error(`Invalid M3U8 file; #EXT-X-MEDIA AUTOSELECT attribute must be YES or NO, got "${t}".`)},$s=e=>{if(null===e)return ue;const t=e.split("-")[0];return t||ue};class Gs{constructor(){this._isIsobmff=!1}}class Qs extends Gs{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Re(t)&&(t=await t),!t)return null;t.skip(4);const i=rc(t,4);return"ftyp"!==i&&"styp"!==i?null:rc(t,4)}_createDemuxer(e){return new or(e)}}class Ys extends Qs{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(Re(t)&&(t=await t),!t)return!1;let r=$o(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Re(t)&&(t=await t),!t)return!1;r=Jo(t),a=16}if(r<a)return!1;const s=rc(t,4);if("moof"===s||"sidx"===s)return!0;if("emsg"!==s&&"prft"!==s&&"free"!==s)return!1;i+=r}return!1}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class Js extends Qs{async _canReadInput(e){return"qt "===await this._getMajorBrand(e)}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class Zs extends Gs{async isSupportedEBMLOfDocType(e,t){let i=e._reader.requestSlice(0,_r);if(Re(i)&&(i=await i),!i)return!1;const r=Rr(i);if(null===r)return!1;if(r<1||r>8)return!1;if(Ar(i,r)!==Ir.EBML)return!1;const a=Mr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(Re(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Nr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case Ir.EBMLVersion:if(1!==Ar(s,r))return!1;break;case Ir.EBMLReadVersion:if(1!==Ar(s,r))return!1;break;case Ir.DocType:if(Or(s,r)!==t)return!1;break;case Ir.DocTypeVersion:if(Ar(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new da(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class en extends Zs{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class tn extends Gs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,uc);if(Re(i)&&(i=await i),!i)break;const r=mc(i);if(!r)break;t=i.filePos+r.size}const i=await pa(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=Di(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(Re(s)&&(s=await s),!s)return!1;const n=$o(s);if(n===Fi||n===Ai)return!0;t=i.startPos+i.header.totalSize;const o=await pa(e._reader,t,t+4);if(!o)return!1;const c=o.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new ga(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class rn extends Gs{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(Re(t)&&(t=await t),!t)return!1;const i=rc(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===rc(t,4)}_createDemuxer(e){return new Fa(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class an extends Gs{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return Re(t)&&(t=await t),!!t&&"OggS"===rc(t,4)}_createDemuxer(e){return new xa(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class sn extends Gs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,uc);if(Re(i)&&(i=await i),!i)break;const r=mc(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Re(i)&&(i=await i),!!i&&"fLaC"===rc(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new La(e)}}class nn extends Gs{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,uc);if(Re(i)&&(i=await i),!i)break;const r=mc(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Re(i)&&(i=await i),!i)return!1;const r=Ma(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Re(i)&&(i=await i),!i)return!1;const a=Ma(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new Oa(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class on extends Gs{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(Re(t)&&(t=await t),!t)return!1;const i=qo(t,205);return 71===i[0]&&71===i[188]||(71===i[0]&&71===i[204]||71===i[4]&&71===i[196])}_createDemuxer(e){return new Xa(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class cn extends Gs{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(Re(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===rc(t,7)))return!1;if(!(e._rootSource instanceof vs))throw new TypeError("HLS inputs require `InputOptions.source` to be a PathedSource or a ref to one.");return e._rootSource._usedForHls=!0,!0}_createDemuxer(e){return new Ws(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return is}}const ln=new Ys,un=new Js,dn=new Zs,hn=new en,fn=new tn,mn=new rn,pn=new an,gn=new nn,kn=new sn,yn=new on,bn=new cn,wn=[bn,ln,un,dn,hn,mn,pn,kn,fn,gn,yn],Tn=[bn,ln,un,fn,gn,yn];var Sn=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});Me();let vn=-1/0,Pn=-1/0,In=null;"undefined"!==typeof FinalizationRegistry&&(In=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-vn>=1e3&&(Ke._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."),vn=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Pn>=1e3&&(Ke._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."),Pn=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class xn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Cn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Bn=new Set(Cn);class En{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(ye*this.timestamp)}get microsecondDuration(){return Math.trunc(ye*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 new TypeError("init must be an object.");if(void 0===t.format||!Bn.has(t.format))throw new TypeError("init.format must be one of: "+Cn.join(", "));if(!Number.isInteger(t.codedWidth)||t.codedWidth<=0)throw new TypeError("init.codedWidth must be a positive integer.");if(!Number.isInteger(t.codedHeight)||t.codedHeight<=0)throw new TypeError("init.codedHeight must be a positive integer.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.layout){if(!Array.isArray(t.layout))throw new TypeError("init.layout, when provided, must be an array.");for(const e of t.layout){if(!e||"object"!==typeof e||Array.isArray(e))throw new TypeError("Each entry in init.layout must be an object.");if(!Number.isInteger(e.offset)||e.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(e.stride)||e.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==t.visibleRect&&qe(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new 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;const i=t.layout??Ln(t.format,t.codedWidth,t.codedHeight);let 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?M(e):M(e).slice(),this._layout=i,this.colorSpace=new Dn(r)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==t?.visibleRect&&qe(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 Dn(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 new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&qe(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new En(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*ye),duration:Math.trunc((t.duration??0)*ye)||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;if("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 new TypeError("Could not determine dimensions.");const a=t.visibleRect??{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(a.width,a.height),n=s.getContext("2d",{alpha:xe(),willReadFrequently:!0});if(!n)throw new 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 Dn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof xn))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!Cn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=Ue({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),In?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return E(null!==this._data),this._data instanceof xn?new En(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Mn(this._data)?new En(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(E(this._layout),new En(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 En(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||(In?.unregister(this),this._data instanceof xn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Mn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(zn(e),this._closed)throw new Error("VideoSample is closed.");if(null==(e.format??this.format))throw new Error("Cannot get allocation size when format is null.");if(Mn(this._data))return this._data.allocationSize(e);return qn(this,e).allocationSize}async copyTo(e,t={}){if(!X(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(zn(t),this._closed)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(E(null!==this._data),Mn(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 xn)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(i,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(r instanceof En))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(r.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${r.format}' instead.`);return await r.copyTo(e,t)}catch(c){i.error=c,i.hasError=!0}finally{Sn(i)}}}const i=qn(this,t);E(this.format);const r=M(e);if(r.byteLength<i.allocationSize)throw new TypeError(`Destination buffer too small. Required: ${i.allocationSize}, Available: ${r.byteLength}`);const a=Un(this.format);let s;if(this._data instanceof xn){let e=this._data.getDataPlanes();if(Re(e)&&(e=await e),!Array.isArray(e)||e.some(e=>!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=e}else if(this._data instanceof Uint8Array)E(this._layout),E(this._layout.length===a.length),s=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");E(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:M(t.data),stride:4*this.codedWidth}]}const n=[],o=a.length;for(let l=0;l<o;l++){const e=i.computedLayouts[l],t=s[l].stride,a=s[l].data;let o=e.sourceTop*t;o+=e.sourceLeftBytes;let c=e.destinationOffset;const u=e.sourceWidthBytes,d={offset:c,stride:e.destinationStride};for(let i=0;i<e.sourceHeight;i++){if(o+u>a.byteLength)throw new Error("Source buffer OOB read.");if(c+u>r.byteLength)throw new Error("Destination buffer OOB write.");const i=a.subarray(o,o+u);r.set(i,c),o+=t,c+=e.destinationStride}n.push(d)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;t<i.allocationSize;t+=4){if(e){const e=r[t],i=r[t+2];r[t]=i,r[t+2]=e}a&&(r[t+3]=255)}}return n}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");if(E(null!==this._data),this._data instanceof xn){if(null===this.format)throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if format is null.");const e=this._data.getDataPlanes();if(Re(e))throw new Error("Cannot convert a VideoSampleResource-backed VideoSample to VideoFrame if getDataPlanes() returns a promise.");const t=e.reduce((e,t)=>e+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const a=[];for(const s of e)i.set(s.data,r),a.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:a[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Mn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(E(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,c){let l=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,d=r,h=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(l,u,d,h,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&On(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,d=t.crop;d&&(d=Nn(d,s,n));const{sx:h,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],d="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*d,u=a*d,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),h,f,m,p,o,c,l,u),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){const 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,c=i.crop?i.crop.height:n;let l=0;2*r<o&&2*a<c&&(l=Math.floor(Math.log2(Math.min(o/r,c/a))));const u=r*2**l,d=a*2**l,{canvas:h,context:f,isNew:m}=l>0?An(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>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 new Error("VideoSample is closed.");if(E(null!==this._data),this._data instanceof xn||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(e){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new 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 new 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 new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&On(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=_(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=Nn(a,i,r));const s=a?a.width:i,n=a?a.height:r,o=s/n;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/o):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*o):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=n),c=he(c,e.roundDimensionsTo??1),l=he(l,e.roundDimensionsTo??1);const u={width:c,height:l,fit:e.fit??"fill",rotation:t,crop:a??{left:0,top:0,width:i,height:r},alpha:e.alpha??"keep"};for(const m of _n){let e=m(this,u);if(Re(e)&&(e=await e),null!==e)return e}const{canvas:d,context:h,isNew:f}=An(u.width,u.height);return this._drawWithFitAndMipmapping(d,h,{fit:u.fit,rotation:u.rotation,crop:u.crop,targetIsFresh:f,fillBlack:"discard"===u.alpha}),new En(d,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const _n=[],Rn=[];let Fn=0;const An=(e,t)=>{for(const a of Rn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=Fn++,{canvas:a.canvas,context:a.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Rn.length>=3&&Rn.splice(Le(Rn,e=>e.age),1),Rn.push({canvas:i,context:r,age:Fn++}),{canvas:i,context:r,isNew:!0}};class Dn{constructor(e){if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(L);if(null!=e.primaries&&!t.includes(e.primaries))throw new TypeError(`init.colorSpace.primaries, when provided, must be one of ${t.join(", ")}.`);const i=Object.keys(q);if(null!=e.transfer&&!i.includes(e.transfer))throw new TypeError(`init.colorSpace.transfer, when provided, must be one of ${i.join(", ")}.`);const r=Object.keys(H);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!==typeof e.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Mn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Nn=(e,t,i)=>{const r=Math.min(e.left,t),a=Math.min(e.top,i),s=Math.min(e.width,t-r),n=Math.min(e.height,i-a);return E(s>=0),E(n>=0),{left:r,top:a,width:s,height:n}},On=(e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(t+"crop, when provided, must be an object.");if(!Number.isInteger(e.left)||e.left<0)throw new TypeError(t+"crop.left must be a non-negative integer.");if(!Number.isInteger(e.top)||e.top<0)throw new TypeError(t+"crop.top must be a non-negative integer.");if(!Number.isInteger(e.width)||e.width<0)throw new TypeError(t+"crop.width must be a non-negative integer.");if(!Number.isInteger(e.height)||e.height<0)throw new TypeError(t+"crop.height must be a non-negative integer.")},zn=e=>{if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.colorSpace&&!["display-p3","srgb"].includes(e.colorSpace))throw new TypeError("options.colorSpace, when provided, must be 'display-p3' or 'srgb'.");if(void 0!==e.format&&"string"!==typeof e.format)throw new TypeError("options.format, when provided, must be a string.");if(void 0!==e.layout){if(!Array.isArray(e.layout))throw new TypeError("options.layout, when provided, must be an array.");for(const t of e.layout){if(!t||"object"!==typeof t)throw new TypeError("Each entry in options.layout must be an object.");if(!Number.isInteger(t.offset)||t.offset<0)throw new TypeError("plane.offset must be a non-negative integer.");if(!Number.isInteger(t.stride)||t.stride<0)throw new TypeError("plane.stride must be a non-negative integer.")}}if(void 0!==e.rect){if(!e.rect||"object"!==typeof e.rect)throw new TypeError("options.rect, when provided, must be an object.");if(void 0!==e.rect.x&&(!Number.isInteger(e.rect.x)||e.rect.x<0))throw new TypeError("options.rect.x, when provided, must be a non-negative integer.");if(void 0!==e.rect.y&&(!Number.isInteger(e.rect.y)||e.rect.y<0))throw new TypeError("options.rect.y, when provided, must be a non-negative integer.");if(void 0!==e.rect.width&&(!Number.isInteger(e.rect.width)||e.rect.width<0))throw new TypeError("options.rect.width, when provided, must be a non-negative integer.");if(void 0!==e.rect.height&&(!Number.isInteger(e.rect.height)||e.rect.height<0))throw new TypeError("options.rect.height, when provided, must be a non-negative integer.")}},Ln=(e,t,i)=>{const r=Un(e),a=[];let s=0;for(const n of r){const e=Math.ceil(t/n.widthDivisor),r=Math.ceil(i/n.heightDivisor),o=e*n.sampleBytes,c=o*r;a.push({offset:s,stride:o}),s+=c}return a},Un=e=>{const t=(e,t,i,r,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:se(e),E(!1)}},qn=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=Wn(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let n;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");n=t.format}else n=e.format;return Vn(a,n,s)},Wn=(e,t,i,r,a)=>{const s={...e};if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!Hn(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},Hn=(e,t)=>{if(null===e)return!0;const i=Un(e);for(let r=0;r<i.length;r++){const e=i[r],a=e.widthDivisor,s=e.heightDivisor;if((t.x||0)%a!==0)return!1;if((t.y||0)%s!==0)return!1}return!0},Vn=(e,t,i)=>{const r=Un(t),a=r.length;if(void 0!==i&&i.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const n=[],o=[];for(let c=0;c<a;c++){const t=r[c],a=t.sampleBytes,l=t.widthDivisor,u=t.heightDivisor,d={destinationOffset:0,destinationStride:0,sourceTop:0,sourceHeight:0,sourceLeftBytes:0,sourceWidthBytes:0};if(d.sourceTop=Math.ceil(Math.trunc(e.y||0)/u),d.sourceHeight=Math.ceil(Math.trunc(e.height||0)/u),d.sourceLeftBytes=Math.floor(Math.trunc(e.x||0)/l)*a,d.sourceWidthBytes=Math.floor(Math.trunc(e.width||0)/l)*a,void 0!==i){const e=i[c];if(e.stride<d.sourceWidthBytes)throw new TypeError(`Stride for plane ${c} is too small.`);d.destinationOffset=e.offset,d.destinationStride=e.stride}else d.destinationOffset=s,d.destinationStride=d.sourceWidthBytes;const h=d.destinationStride*d.sourceHeight+d.destinationOffset;if(h>4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let e=0;e<c;e++){const t=n[e];if(!(o[c]<=t.destinationOffset||o[e]<=d.destinationOffset))throw new TypeError("Planes overlap.")}n.push(d)}return{allocationSize:s,computedLayouts:n}},jn=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Kn{constructor(){this._referenceCount=0}}class Xn{get microsecondTimestamp(){return Math.trunc(ye*this.timestamp)}get microsecondDuration(){return Math.trunc(ye*this.duration)}constructor(e){if(this._closed=!1,Jn(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else if(e instanceof Kn){if(this._data=e,e._referenceCount++,this.format=e.getFormat(),!jn.has(this.format))throw new TypeError("getFormat() must return an AudioSampleFormat.");if(this.sampleRate=e.getSampleRate(),!Number.isInteger(this.sampleRate)||this.sampleRate<=0)throw new TypeError("getSampleRate() must return a positive integer.");if(this.numberOfFrames=e.getNumberOfFrames(),!Number.isInteger(this.numberOfFrames)||this.numberOfFrames<0)throw new TypeError("getNumberOfFrames() must return a non-negative integer.");if(this.numberOfChannels=e.getNumberOfChannels(),!Number.isInteger(this.numberOfChannels)||this.numberOfChannels<=0)throw new TypeError("getNumberOfChannels() must return a positive integer.");if(this.timestamp=e.getTimestamp(),!Number.isFinite(this.timestamp))throw new TypeError("getTimestamp() must return a finite number.");this.duration=this.numberOfFrames/this.sampleRate}else{if(!e||"object"!==typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!jn.has(e.format))throw new TypeError("Invalid AudioDataInit: invalid format.");if(!Number.isFinite(e.sampleRate)||e.sampleRate<=0)throw new TypeError("Invalid AudioDataInit: sampleRate must be > 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/($n(e.format)*e.numberOfChannels);if(!Number.isInteger(t))throw new TypeError("Invalid AudioDataInit: data size is not a multiple of frame size.");let i;if(this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=t,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp,this.duration=t/e.sampleRate,e.data instanceof ArrayBuffer)i=new Uint8Array(e.data);else{if(!ArrayBuffer.isView(e.data))throw new TypeError("Invalid AudioDataInit: data is not a BufferSource.");i=new Uint8Array(e.data.buffer,e.data.byteOffset,e.data.byteLength)}const r=this.numberOfFrames*this.numberOfChannels*$n(this.format);if(i.byteLength<r)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}In?.register(this,{type:"audio",data:this._data},this)}allocationSize(e){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(!Number.isInteger(e.planeIndex)||e.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==e.format&&!jn.has(e.format))throw new TypeError("Invalid format.");if(void 0!==e.frameOffset&&(!Number.isInteger(e.frameOffset)||e.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==e.frameCount&&(!Number.isInteger(e.frameCount)||e.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const t=e.format??this.format,i=e.frameOffset??0;if(i>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const a=$n(t),s=Gn(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?r:r*this.numberOfChannels)*a}copyTo(e,t){if(!X(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!Number.isInteger(t.planeIndex)||t.planeIndex<0)throw new TypeError("planeIndex must be a non-negative integer.");if(void 0!==t.format&&!jn.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:a}=t;let{planeIndex:s}=t,n=this.format;const o=i??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw new RangeError("frameOffset out of range");const d=void 0!==r?r:c-u;if(d>c-u)throw new RangeError("frameCount out of range");const h=$n(o),f=Gn(o);if(f&&s>=l)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?d:d*l)*h;if(e.byteLength<m)throw new RangeError("Destination buffer is too small");const p=N(e),g=Yn(o);if(Jn(this._data)){if(Pe()&&l>2&&o!==n)return void Zn(this._data,p,n,o,l,s,u,d);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:d,format:o})}catch(S){if("f32-planar"===o)throw S;n="f32-planar"}}const k=Qn(n),y=$n(n),b=Gn(n);let w;if(this._data instanceof Kn){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=c*y*(b?1:l);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)w=e(s),s=0;else{w=new Uint8Array(c*y*l);for(let t=0;t<l;t++){const i=e(t);w.set(i,t*c*y)}}else w=e(0)}else if(this._data instanceof Uint8Array)w=this._data;else if(E("f32-planar"===n),f)w=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:s})),this._data.copyTo(w,{format:"f32-planar",planeIndex:s}),s=0;else{w=new Uint8Array(this._data.allocationSize({format:"f32-planar",planeIndex:0})*l);for(let e=0;e<l;e++)this._data.copyTo(w.subarray(e*c*y,(e+1)*c*y),{format:"f32-planar",planeIndex:e})}const T=N(w);for(let v=0;v<d;v++)if(f){let e;e=b?(s*c+(v+u))*y:((v+u)*l+s)*y;g(p,v*h,k(T,e))}else for(let e=0;e<l;e++){let t;t=b?(e*c+(v+u))*y:((v+u)*l+e)*y;g(p,(v*l+e)*h,k(T,t))}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(this._data instanceof Kn){const e=new Xn(this._data);return e.setTimestamp(this.timestamp),e}if(Jn(this._data)){const e=new Xn(this._data.clone());return e.setTimestamp(this.timestamp),e}return new Xn({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}trim(e,t=this.numberOfFrames){if(!Number.isInteger(e)||e<0)throw new TypeError("startFrame must be a non-negative integer.");if(!Number.isInteger(t)||t<0)throw new TypeError("endFrame must be a non-negative integer.");if(e>this.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t<e)throw new RangeError("endFrame must not be less than startFrame.");if(this._closed)throw new Error("AudioSample is closed.");const i=t-e,r=$n(this.format);let a;if(Gn(this.format)){const t=i*r;if(a=new Uint8Array(t*this.numberOfChannels),i>0)for(let r=0;r<this.numberOfChannels;r++)this.copyTo(a.subarray(r*t,(r+1)*t),{planeIndex:r,format:this.format,frameOffset:e,frameCount:i})}else a=new Uint8Array(i*this.numberOfChannels*r),i>0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Xn({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(In?.unregister(this),this._data instanceof Kn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Jn(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof Kn?this._createAudioDataFromData():Jn(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(Gn(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(new Uint8Array(t,i*e,e),{planeIndex:i,format:this.format});return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:t})}{const e=new ArrayBuffer(this.allocationSize({planeIndex:0,format:this.format}));return this.copyTo(e,{planeIndex:0,format:this.format}),new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:e})}}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let i=0;i<this.numberOfChannels;i++)this.copyTo(t,{planeIndex:i,format:"f32-planar"}),e.copyToChannel(t,i);return e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}[Symbol.dispose](){this.close()}static*_fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=e.numberOfChannels,r=e.sampleRate,a=e.length,s=Math.floor(24e4/i);let n=0,o=a;for(;o>0;){const 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);yield new Xn({format:"f32-planar",sampleRate:r,numberOfFrames:a,numberOfChannels:i,timestamp:t+n/r,data:c}),n+=a,o-=a}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=e.numberOfChannels,r=e.sampleRate,a=e.length,s=Math.floor(24e4/i);let n=0,o=a;const c=[];for(;o>0;){const 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);const u=new Xn({format:"f32-planar",sampleRate:r,numberOfFrames:a,numberOfChannels:i,timestamp:t+n/r,data:l});c.push(u),n+=a,o-=a}return c}}const $n=e=>{switch(e){case"u8":case"u8-planar":return 1;case"s16":case"s16-planar":return 2;case"s32":case"s32-planar":case"f32":case"f32-planar":return 4;default:throw new Error("Unknown AudioSampleFormat")}},Gn=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},Qn=e=>{switch(e){case"u8":case"u8-planar":return(e,t)=>(e.getUint8(t)-128)/128;case"s16":case"s16-planar":return(e,t)=>e.getInt16(t,!0)/32768;case"s32":case"s32-planar":return(e,t)=>e.getInt32(t,!0)/2147483648;case"f32":case"f32-planar":return(e,t)=>e.getFloat32(t,!0)}},Yn=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,le(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,le(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,le(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Jn=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Zn=(e,t,i,r,a,s,n,o)=>{const c=Qn(i),l=Yn(r),u=$n(i),d=$n(r),h=Gn(i);if(Gn(r))if(h){const r=new ArrayBuffer(o*u),a=N(r);e.copyTo(r,{planeIndex:s,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++){l(t,e*d,c(a,e*u))}}else{const r=new ArrayBuffer(o*a*u),h=N(r);e.copyTo(r,{planeIndex:0,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++){l(t,e*d,c(h,(e*a+s)*u))}}else if(h){const r=new ArrayBuffer(o*u),s=N(r);for(let h=0;h<a;h++){e.copyTo(r,{planeIndex:h,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++){l(t,(e*a+h)*d,c(s,e*u))}}}else{const r=new ArrayBuffer(o*a*u),s=N(r);e.copyTo(r,{planeIndex:0,frameOffset:n,frameCount:o,format:i});for(let e=0;e<o;e++)for(let i=0;i<a;i++){const r=e*a+i;l(t,r*d,c(s,r*u))}}},eo=[],to=[],io=e=>{if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.metadataOnly&&"boolean"!==typeof e.metadataOnly)throw new TypeError("options.metadataOnly, when defined, must be a boolean.");if(void 0!==e.verifyKeyPackets&&"boolean"!==typeof e.verifyKeyPackets)throw new TypeError("options.verifyKeyPackets, when defined, must be a boolean.");if(e.verifyKeyPackets&&e.metadataOnly)throw new TypeError("options.verifyKeyPackets and options.metadataOnly cannot be enabled together.");if(void 0!==e.skipLiveWait&&"boolean"!==typeof e.skipLiveWait)throw new TypeError("options.skipLiveWait, when defined, must be a boolean.")},ro=e=>{if(!Ne(e))throw new TypeError("timestamp must be a number.")},ao=(e,t,i)=>i.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const i=await e.determinePacketType(t);return i&&(t.type=i),t}):t;class so{constructor(e){if(!(e instanceof To))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(io(e),this._track.input._disposed)throw new Oo;return ao(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){io(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(ro(e),io(t),this._track.input._disposed)throw new Oo;return ao(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof Wi))throw new TypeError("packet must be an EncodedPacket.");if(io(t),this._track.input._disposed)throw new Oo;return ao(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(ro(e),io(t),this._track.input._disposed)throw new Oo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;E("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i}async getNextKeyPacket(e,t={}){if(!(e instanceof Wi))throw new TypeError("packet must be an EncodedPacket.");if(io(t),this._track.input._disposed)throw new Oo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;E("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,t):i}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Wi))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Wi))throw new TypeError("endPacket must be an EncodedPacket.");if(io(i),this._track.input._disposed)throw new Oo;const r=[];let{promise:a,resolve:s}=te(),{promise:n,resolve:o}=te(),c=!1,l=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=te()),await n):(r.push(u),s(),({promise:a,resolve:s}=te()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Oo;if(l)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const 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}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class no{constructor(e,t){this.onSample=e,this.onError=t}}class oo{mediaSamplesInRange(e=-1/0,t=1/0,i){ro(e),ro(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=te(),{promise:c,resolve:l}=te(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(d=!0),d?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}=te())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!d&&!this._track.input._disposed;){const e=co(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=te()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),h||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new Oo;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(h=!0,d=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:n}=te(),{promise:o,resolve:c}=te(),l=!1,u=!1,d=null,h=null,f=!1;const m=e=>{a.push(e),n(),({promise:s,resolve:n}=te())},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{d=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++)m(i<t-1?e.clone():e);else e.close()},e=>{f||(h=e,f=!0,n())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=async()=>{E(s),E(d);let t=s;for(d.decode(t);t.sequenceNumber<g;){const i=co(a.length);for(;a.length+d.getDecodeQueueSize()>i&&!u;)({promise:o,resolve:c}=te()),await o;if(u)break;const r=await e.getNextPacket(t,p);E(r),d.decode(r),t=r}g=-1},y=async()=>{E(d),await d.flush();for(let e=0;e<r.length;e++)m(null);r.length=0};for await(const a of i){if(ro(a),u||this._track.input._disposed)break;const i=await e.getPacket(a,p),n=i&&await e.getKeyPacket(a,p);n?(t&&(n.sequenceNumber!==s.sequenceNumber||i.timestamp<t.timestamp)&&(await k(),await y()),r.push(i.timestamp),g=Math.max(i.sequenceNumber,g),t=i,s=n):(-1!==g&&(await k(),await y()),m(null),t=null)}u||this._track.input._disposed||(-1!==g&&await k(),await y()),l=!0,n()})().catch(e=>{f||(h=e,f=!0,n())}).finally(()=>{d?.close()});const g=this._track,k=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(g.input._disposed)throw u=!0,k(),new Oo;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),h;if(a.length>0){const e=a.shift();return E(void 0!==e),c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await s}},return:async()=>(u=!0,c(),n(),k(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const co=e=>0===e?40:8;class lo extends no{constructor(e,t,i,r,a,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=a,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Se,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=[];const n=eo.find(e=>e.supports(i,r));if(n)this.customDecoder=new n,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof En))throw new 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{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();E(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(Be()){if("avc"===i&&this.decoderConfig.description){const e=yt(M(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=wt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=St(t),this.decoderConfig={...this.decoderConfig,description:kt(e)}))}}j(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(E(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(E(this.decoder),Pe()||ee(this.inputTimestamps,e.timestamp,e=>e),Be()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of ut(e.data,this.decoderConfig)){const r=dt(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===at.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(a.offset,a.offset+a.length))}if(!this.decoderConfig.description)for(let e=0;e<t.length;e++){const i=t[e];if(dt(i[0])!==at.SPS)continue;const r=wt(i);r&&0!==r.maxDecFrameBuffering&&1!==r.bitstreamRestrictionFlag&&(t[e]=St(r));break}const r=((e,t)=>{if(t.description){const i=3&M(t.description)[4];return pt(e,i+1)}return mt(e)})(t,this.decoderConfig);e=new Wi(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Nt(e.data,this.decoderConfig);t&&(e=new Wi(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 ho),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();E(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){const e=this.colorQueue.shift();E(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=Vt(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of vt(e,this.decoderConfig)){const i=Pt(e[t.offset]);if(i===nt.RASL_N||i===nt.RASL_R)return!0}return!1}sampleHandler(e){if(Pe()){if(this.sampleQueue.length>0&&e.timestamp>=R(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ee(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();E(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){const i=te();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){E(this.merger);const i=await this.merger.merge(e,t);r.sample=new En(i)}else r.sample=new En(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){ie(this.finalSamples,r),this.onError(a)}finally{ie(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(E(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),Pe()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(E(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());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let uo=null;class ho{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!uo){const e=new Blob([`(${fo.toString()})()`],{type:"application/javascript"});uo=URL.createObjectURL(e)}const e=le(navigator.hardwareConcurrency,1,4);for(let t=0;t<e;t++){const e=new Worker(uo);e.addEventListener("message",e=>{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=te();this.pendingRequests.set(i,r);const 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(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const fo=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:a,alpha:s}=e.data;i=i.then(async()=>{try{const e=await r(a,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{a.close(),s.close()}})});const r=async(e,t)=>{const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),c=i.includes("P12"),l=r.includes("P10"),u=r.includes("P12");if(l!==o||u!==c)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);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 new Error(`CPU color/alpha merging does not support format '${i}'.`)},a=async(e,t,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=new Uint8Array(4*s);await e.copyTo(n);const c=await o(t,r,a,1);for(let o=0,u=3;o<s;o++,u+=4)n[u]=c[o];const l={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,l)},s=async(e,t,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=i.includes("P10"),n=i.includes("P12"),c=s||n?2:1;let l,u;i.startsWith("I420")?(l=Math.ceil(r/2),u=Math.ceil(a/2)):i.startsWith("I422")?(l=Math.ceil(r/2),u=a):(l=r,u=a);const d=r*a,h=d*c,f=l*u*c,m=new Uint8Array(h+2*f+d*c);await e.copyTo(m);const p=await o(t,r,a,c),g=h+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,d=s+n,h=s;for(let o=0;o<n;o++)l[u+o]=t[h+2*o],l[d+o]=t[h+2*o+1];const f=await o(i,r,a,1);l.set(f,s+2*n);const m={format:"I420A",codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[l.buffer]};return new VideoFrame(l,m)},o=async(t,i,r,a)=>{const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e);const n=t.format;if("RGBA"===n||"BGRA"===n||"RGBX"===n||"BGRX"===n){const t="RGBA"===n||"RGBX"===n?0:2,a=i*r;for(let i=0;i<a;i++)e[i]=e[4*i+t];return e.subarray(0,a)}return e.subarray(0,i*r*a)}},mo=e=>{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class po extends oo{constructor(e,t={}){if(!(e instanceof Po))throw new TypeError("videoTrack must be an InputVideoTrack.");mo(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(Ee("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getRotation();let a=await this._track.getDecoderConfig();const s=await this._track.getTimeResolution();return E(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new lo(e,t,i,a,r,s)}_createPacketSink(){return new so(this._track)}async getSample(e,t={}){ro(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class go{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Po))throw new TypeError("videoTrack must be an InputVideoTrack.");if(t&&"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.alpha&&"boolean"!==typeof t.alpha)throw new TypeError("options.alpha, when provided, must be a boolean.");if(void 0!==t.width&&(!Number.isInteger(t.width)||t.width<=0))throw new TypeError("options.width, when defined, must be a positive integer.");if(void 0!==t.height&&(!Number.isInteger(t.height)||t.height<=0))throw new TypeError("options.height, when defined, must be a positive integer.");if(void 0!==t.fit&&!["fill","contain","cover"].includes(t.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==t.width&&void 0!==t.height&&void 0===t.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180 or 270.");if(void 0!==t.crop&&On(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&mo(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new po(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[s,n]=i%180===0?[r,a]:[a,r];let o=e.crop;o&&(o=Nn(o,s,n));let[c,l]=o?[o.width,o.height]:[s,n];const u=c/l;void 0!==e.width&&void 0===e.height?(c=e.width,l=Math.round(c/u)):void 0===e.width&&void 0!==e.height?(l=e.height,c=Math.round(l*u)):void 0!==e.width&&void 0!==e.height&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=i,this._crop=o})())}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],a=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||xe()});E(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&xe()});const n={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e,t){ro(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*ce(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*ce(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class ko extends no{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Se,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const a=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=to.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 Xn))throw new 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{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new Xn(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(E(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--)):(E(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(E(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(E(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class yo extends no{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,E(pi.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=Bi(this.codec);switch(this.inputSampleSize=a,a){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),i=5+((240&r)>>4);const a=(1<<i|(15&r)<<i-4|1<<i-5)-33;return 0===t?a:-a})(e.getUint8(t)):"alaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=85^e;128&r&&(r&=-129,t=-1),i=4+((240&r)>>4);let a=0;return a=4!==i?1<<i|(15&r)<<i-4|1<<i-5:r<<1|1,0===t?a:-a})(e.getUint8(t)):E(!1);break;case 2:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint16(t,s)-32768:"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):E(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>ne(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>ne(e,t,i)<<8>>8)(e,t,s):E(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-2**31:"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):E(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):E(!1);break;default:se(a),E(!1)}switch(a){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:se(a),E(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=N(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(r),s=new DataView(a);for(let l=0;l<i*this.decoderConfig.numberOfChannels;l++){const e=l*this.inputSampleSize,i=l*this.outputSampleSize,r=this.readInputValue(t,e);this.writeOutputValue(s,i,r)}const n=i/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const c=new Xn({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class bo extends oo{constructor(e){if(!(e instanceof Io))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(Ee("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getDecoderConfig();return E(i&&r),pi.includes(r.codec)?new yo(e,t,r):new ko(e,t,i,r)}_createPacketSink(){return new so(this._track)}async getSample(e,t={}){ro(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class wo{constructor(e){if(!(e instanceof Io))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new bo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){ro(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return ce(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return ce(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class To{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Po}isAudioTrack(){return this instanceof Io}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return So(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return So(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return So(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return So(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return null!==await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())}async getDisposition(){return this._backing.getDisposition()}get disposition(){return So(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return fe((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new so(this);let r=1/0,a=-1/0,s=0,n=0;for await(const o of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-r)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-r)).toPrecision(16)):0}}async isLive(){return null!==await this._backing.getLiveRefreshInterval()}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof To))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&0n!==(this._backing.getPairingMask()&e._backing.getPairingMask())}async getPairableTracks(e){return this.input.getTracks(Eo({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(Eo({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(Eo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(Eo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(Eo({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=vo(e));const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=vo(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=vo(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const So=(e,t,i)=>{if(Re(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},vo=e=>{if(void 0!==e&&"function"!==typeof e)throw new TypeError("predicate, when provided, must be a function.");return e?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("predicate must return or resolve to a boolean value.");return e},r=e(t);return Re(r)?r.then(i):i(r)}:void 0};class Po extends To{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 So(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??"prores"===await this._backing.getCodec()}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return So(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return So(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return So(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return So(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return So(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=Ue({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=Ue({num:So(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*So(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:So(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*So(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){const e=await(this._backing.getMetadataDisplayWidth?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(void 0!==e){const t=So(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=So(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return So(t,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await(this._backing.getMetadataDisplayHeight?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(void 0!==e){const t=So(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=So(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return So(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(E(null!==t),eo.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return Ke._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Wi))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(null===t)return null;const i=await this.getDecoderConfig();return E(i),Vt(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!Ne(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,r=new so(this),a=[];let s=-1/0,n=0;for await(const I of r.packets(void 0,void 0,{metadataOnly:!0})){if(a.length>=i&&I.timestamp>=s)break;a.push(I.timestamp),s=Math.max(s,I.timestamp),n++}const o=new Float64Array(a.length);for(let I=0;I<a.length;I++)o[I]=Math.round(a[I]*t);o.sort();let c=1;for(let I=1;I<o.length;I++)o[I]!==o[c-1]&&(o[c++]=o[I]);if(c<2)return{underlyingFrameRate:null,bestGuessFrameRate:t,minFrameRate:t,maxFrameRate:t,averageFrameRate:t,medianFrameRate:t,frameRateIsConstant:!0,probedPacketCount:n};const l=o.subarray(0,c),u=Ro(l,t),d=u??t,h=null!==u?t/u:null,f=new Map;let m=1/0,p=-1/0,g=0;for(let I=1;I<c;I++){const e=l[I]-l[I-1],t=null!==h?Math.max(1,Math.round(e/h)):e;f.set(t,(f.get(t)??0)+1),m=Math.min(m,t),p=Math.max(p,t),g+=t}const k=c-1,y=[...f.keys()].sort((e,t)=>e-t),b=k-1>>1,w=k>>1;let T=0,S=0,v=0;for(const I of y)if(v+=f.get(I),0===T&&v>b&&(T=I),v>w){S=I;break}const P=(d/T+d/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:Ao(P),minFrameRate:d/p,maxFrameRate:d/m,averageFrameRate:d*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class Io extends To{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return So(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return So(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return So(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(E(null!==t),to.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return Ke._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof Wi))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const xo=e=>-(e??-1/0),Co=e=>-e,Bo=e=>{if("object"!==typeof e||!e)throw new TypeError("query must be an object.");if(void 0!==e.filter&&"function"!==typeof e.filter)throw new TypeError("query.filter, when provided, must be a function.");if(void 0!==e.sortBy&&"function"!==typeof e.sortBy)throw new TypeError("query.sortBy, when provided, must be a function.");return{filter:e.filter?t=>{const i=e=>{if("boolean"!==typeof e)throw new TypeError("query.filter must return or resolve to a boolean.");return e},r=e.filter(t);return Re(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return Re(r)?r.then(i):i(r)}:void 0}},Eo=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return Re(r)?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Re(r)||Re(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),_o=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>Re(e))){const t=await Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!t?.sortBy)return i;const r=i.map(e=>t.sortBy(e)),a=r.some(e=>Re(e))?await Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{const i=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(i.length,r.length);for(let s=0;s<a;s++){const e=i[s]??0,t=r[s]??0;if(e!==t)return e-t}return 0}).map(e=>e.track)},Ro=(e,t)=>{const i=1e6,r=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let T=1;T<e.length;T++){const t=e[T]-e[T-1];if(!(t>0))return null;s[T-1]=t}const n=s.slice();n.sort();let o=n[Math.floor(.05*n.length)];for(let T=0;T<6;T++){let e=0,t=0;for(const a of s){const i=Math.max(1,Math.round(a/o));Math.abs(a-i*o)>=r||(e+=a,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let c=0,l=0,u=0;for(const T of s){const e=Math.max(1,Math.round(T/o));Math.abs(T-e*o)>=r||(c++,l+=T,u+=e)}if(c/s.length<.98)return null;o=l/u;const d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const T of a){if(T<m||T>p)continue;const e=Math.abs(T/g-1);e<y&&(k=T,y=e)}if(null===k){const e=Fo(h,f,i),r=Fo(m,p,i);if(r&&(!e||r.den<e.den||r.den===e.den&&r.num<=e.num))k=r.num/r.den;else{if(!e)return null;k=t*e.den/e.num}}const b=t/k;let w=0;for(const T of s){const e=Math.max(1,Math.round(T/b));Math.abs(T-e*b)<r&&w++}return w/s.length<.98?null:k},Fo=(e,t,i)=>{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r<t)return Ue({num:i,den:r})}return null},Ao=e=>{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,a=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t<a&&(r=s,a=t)}return r};Me();const Do=2;class Mo extends He{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 new TypeError("options must be an object.");if(!Array.isArray(e.formats)||e.formats.some(e=>!(e instanceof Gs)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Ts||e.source instanceof Ss))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Ts&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Mo))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new 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 Ts?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){E(this._rootSource instanceof vs);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){const i=this._sourceCache.find(i=>i.cacheGroup===t&&Ps(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Ps(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(ze(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Le(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);E(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),ie(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);E(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:a}),a.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new zo(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)}throw new No})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),E(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof No)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=await Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e),r=(await Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)}async getTracks(e){e&&(e=Bo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return _o(t,e)}async getVideoTracks(e){e&&(e=Bo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return _o(t,e)}async getAudioTracks(e){e&&(e=Bo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return _o(t,e)}async getPrimaryVideoTrack(e){e&&(e=Bo(e));const t=Eo(e,{sortBy:async e=>[Co((await e.getDisposition()).default),Co(await e.hasPairableAudioTrack()),Co(!(await e.hasOnlyKeyPackets())),xo(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Bo(e));const t=await this.getPrimaryVideoTrack(),i=Eo(e,{sortBy:async e=>[Co(!t||e.canBePairedWith(t)),Co((await e.getDisposition()).default),xo(await e.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new Po(this,e):new Io(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class No extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Oo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class zo{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new Oo;if(e<0)return null;if(null!==this.fileSizeNonStrict&&e+t>this.fileSizeNonStrict)return null;if(0===t){const t=new Uint8Array(0);return new Lo(t,N(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,ws);return Re(r)?r.then(t=>t?new Lo(t.bytes,t.view,t.offset,e,i):null):r?new Lo(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Oo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,le(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(E(null!==this.fileSizeNonStrict),this.requestSlice(e,le(this.fileSizeNonStrict-e,t,i)));return Re(r)?r.then(a):a(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(async()=>{const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(Re(i)&&(i=await i),!i||0===i.length)break;const r=qo(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new Lo(i,N(i),0,0,t)})()}}class Lo{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 Lo(e,N(e),0,0,e.length)}get length(){return this.end-this.start}get filePos(){return this.offset+this.bufferPos}set filePos(e){this.bufferPos=e-this.offset}get remainingLength(){return Math.max(this.end-this.filePos,0)}skip(e){this.bufferPos+=e}slice(e,t=this.end-e){if(e<this.start||e+t>this.end)throw new RangeError("Slicing outside of original slice.");return new Lo(this.bytes,this.view,this.offset,e,e+t)}}const Uo=(e,t)=>{if(e.filePos<e.start||e.filePos+t>e.end)throw new RangeError(`Tried reading [${e.filePos}, ${e.filePos+t}), but slice is [${e.start}, ${e.end}). This is likely an internal error, please report it alongside the file that caused it.`)},qo=(e,t)=>{Uo(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},Wo=e=>(Uo(e,1),e.view.getUint8(e.bufferPos++)),Ho=(e,t)=>{Uo(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Vo=e=>{Uo(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},jo=e=>{Uo(e,3);const t=ne(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Ko=e=>{Uo(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Xo=(e,t)=>{Uo(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},$o=e=>{Uo(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Go=e=>{Uo(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Qo=e=>{Uo(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Yo=(e,t)=>{let i,r;return t?(i=Xo(e,!0),r=Xo(e,!0)):(r=Xo(e,!1),i=Xo(e,!1)),4294967296*r+i},Jo=e=>4294967296*$o(e)+$o(e),Zo=e=>4294967296*Qo(e)+$o(e),ec=e=>{const t=Go(e),i=(e=>{Uo(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},tc=e=>{Uo(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},ic=e=>{Uo(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},rc=(e,t)=>{Uo(e,t);let i="";for(let r=0;r<t;r++)i+=String.fromCharCode(e.bytes[e.bufferPos++]);return i},ac=(e,t,i)=>O.decode(qo(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var sc,nc,oc,cc;(nc=sc||(sc={}))[nc.Unsynchronisation=128]="Unsynchronisation",nc[nc.ExtendedHeader=64]="ExtendedHeader",nc[nc.ExperimentalIndicator=32]="ExperimentalIndicator",nc[nc.Footer=16]="Footer",(cc=oc||(oc={}))[cc.ISO_8859_1=0]="ISO_8859_1",cc[cc.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",cc[cc.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",cc[cc.UTF_8=3]="UTF_8";const lc=128,uc=10,dc=["Blues","Classic rock","Country","Dance","Disco","Funk","Grunge","Hip-hop","Jazz","Metal","New age","Oldies","Other","Pop","Rhythm and blues","Rap","Reggae","Rock","Techno","Industrial","Alternative","Ska","Death metal","Pranks","Soundtrack","Euro-techno","Ambient","Trip-hop","Vocal","Jazz & funk","Fusion","Trance","Classical","Instrumental","Acid","House","Game","Sound clip","Gospel","Noise","Alternative rock","Bass","Soul","Punk","Space","Meditative","Instrumental pop","Instrumental rock","Ethnic","Gothic","Darkwave","Techno-industrial","Electronic","Pop-folk","Eurodance","Dream","Southern rock","Comedy","Cult","Gangsta","Top 40","Christian rap","Pop/funk","Jungle music","Native US","Cabaret","New wave","Psychedelic","Rave","Showtunes","Trailer","Lo-fi","Tribal","Acid punk","Acid jazz","Polka","Retro","Musical","Rock 'n' roll","Hard rock","Folk","Folk rock","National folk","Swing","Fast fusion","Bebop","Latin","Revival","Celtic","Bluegrass","Avantgarde","Gothic rock","Progressive rock","Psychedelic rock","Symphonic rock","Slow rock","Big band","Chorus","Easy listening","Acoustic","Humour","Speech","Chanson","Opera","Chamber music","Sonata","Symphony","Booty bass","Primus","Porn groove","Satire","Slow jam","Club","Tango","Samba","Folklore","Ballad","Power ballad","Rhythmic Soul","Freestyle","Duet","Punk rock","Drum solo","A cappella","Euro-house","Dance hall","Goa music","Drum & bass","Club-house","Hardcore techno","Terror","Indie","Britpop","Negerpunk","Polsk punk","Beat","Christian gangsta rap","Heavy metal","Black metal","Crossover","Contemporary Christian","Christian rock","Merengue","Salsa","Thrash metal","Anime","Jpop","Synthpop","Christmas","Art rock","Baroque","Bhangra","Big beat","Breakbeat","Chillout","Downtempo","Dub","EBM","Eclectic","Electro","Electroclash","Emo","Experimental","Garage","Global","IDM","Illbient","Industro-Goth","Jam Band","Krautrock","Leftfield","Lounge","Math rock","New romantic","Nu-breakz","Post-punk","Post-rock","Psytrance","Shoegaze","Space rock","Trop rock","World music","Neoclassical","Audiobook","Audio theatre","Neue Deutsche Welle","Podcast","Indie rock","G-Funk","Dubstep","Garage rock","Psybient"],hc=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=qo(e,lc-3)),e.filePos=r;const a=fc(e,30);a&&(t.title??(t.title=a));const s=fc(e,30);s&&(t.artist??(t.artist=s));const n=fc(e,30);n&&(t.album??(t.album=n));const o=fc(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=qo(e,30);let u;if(0===l[28]&&0!==l[29]){const i=l[29];i>0&&(t.trackNumber??(t.trackNumber=i)),e.skip(-30),u=fc(e,28),e.skip(2)}else e.skip(-30),u=fc(e,30);u&&(t.comment??(t.comment=u));const d=Wo(e);d<dc.length&&(t.genre??(t.genre=dc[d]))},fc=(e,t)=>{const i=qo(e,t),r=Fe(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n<a.length;n++)s+=String.fromCharCode(a[n]);return s.trimEnd()},mc=e=>{const t=e.filePos,i=rc(e,3),r=Wo(e),a=Wo(e),s=Wo(e),n=$o(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=Ni(n);return s&sc.Footer&&(o+=uc),{majorVersion:r,revision:a,flags:s,size:o}},pc=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void Ke._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&sc.Footer?t.size-uc:t.size,l=qo(e,c),u=new gc(t,l);if(t.flags&sc.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&sc.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let d=!1,h=!1,f=!1;if(3===t.majorVersion?(d=!!(64&e.flags),h=!!(128&e.flags)):4===t.majorVersion&&(d=!!(4&e.flags),h=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&sc.Unsynchronisation)),d)Ke._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(h)Ke._warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=l;else{if(f&&u.ununsynchronizeRegion(u.pos,l),i.raw??(i.raw={}),"TXXX"===e.id){const e=(r=i.raw).TXXX??(r.TXXX={}),t=u.readId3V2TextEncoding(),a=u.readId3V2Text(t,l),s=u.readId3V2Text(t,l);e[a]??(e[a]=s)}else"T"===e.id[0]?(a=i.raw)[s=e.id]??(a[s]=u.readId3V2EncodingAndText(l)):(n=i.raw)[o=e.id]??(n[o]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":i.title??(i.title=u.readId3V2EncodingAndText(l));break;case"TIT3":case"TT3":i.description??(i.description=u.readId3V2EncodingAndText(l));break;case"TPE1":case"TP1":i.artist??(i.artist=u.readId3V2EncodingAndText(l));break;case"TALB":case"TAL":i.album??(i.album=u.readId3V2EncodingAndText(l));break;case"TPE2":case"TP2":i.albumArtist??(i.albumArtist=u.readId3V2EncodingAndText(l));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.trackNumber??(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.tracksTotal??(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.discNumber??(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.discsTotal??(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(l);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==dc[e]){i.genre??(i.genre=dc[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==dc[e]){i.genre??(i.genre=dc[e]);break}}i.genre??(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(l),t=new Date(e);Number.isNaN(t.getTime())||(i.date??(i.date=t))}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(l),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.lyrics??(i.lyrics=u.readId3V2Text(e,l))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.comment??(i.comment=u.readId3V2Text(e,l))}break;case"APIC":case"PIC":{const e=u.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=u.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=u.readId3V2Text(e,l);const a=u.readU8(),s=u.readId3V2Text(e,l).trimEnd(),n=l-u.pos;if(n>=0){const e=u.readBytes(n);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===a?"coverFront":4===a?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=l}}};class gc{constructor(e,t){this.header=e,this.bytes=t,this.pos=0,this.view=new DataView(t.buffer,t.byteOffset,t.byteLength)}frameHeaderSize(){return 2===this.header.majorVersion?6:10}ununsynchronizeAll(){const e=[];for(let t=0;t<this.bytes.length;t++){const i=this.bytes[t];if(e.push(i),255===i&&t!==this.bytes.length-1){0===this.bytes[t]&&t++}}this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}ununsynchronizeRegion(e,t){const i=[];for(let s=e;s<t;s++){const e=this.bytes[s];if(i.push(e),255===e&&s!==t-1){0===this.bytes[s+1]&&s++}}const r=this.bytes.subarray(0,e),a=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+i.length+a.length),this.bytes.set(r,0),this.bytes.set(i,r.length),this.bytes.set(a,r.length+i.length),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+2);return this.pos+=3,256*e+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let i=0;i<e;i++)t+=String.fromCharCode(this.view.getUint8(this.pos+i));return this.pos+=e,t}readId3V2Frame(){if(2===this.header.majorVersion){const e=this.readAscii(3);if("\0\0\0"===e)return null;return{id:e,size:this.readU24(),flags:0}}{const e=this.readAscii(4);if("\0\0\0\0"===e)return null;const t=this.readU32();let i=4===this.header.majorVersion?Ni(t):t;const r=this.readU16(),a=this.pos,s=e=>{const t=this.pos+e;if(t>this.bytes.length)return!1;if(t<=this.bytes.length-this.frameHeaderSize()){this.pos+=e;const t=this.readAscii(4);if("\0\0\0\0"!==t&&!/[0-9A-Z]{4}/.test(t))return!1}return!0};if(!s(i)){const e=4===this.header.majorVersion?t:Ni(t);s(e)&&(i=e)}return this.pos=a,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case oc.ISO_8859_1:{let e="";for(let t=0;t<r.length;t++){const a=r[t];if(0===a){this.pos=i+t+1;break}e+=String.fromCharCode(a)}return e}case oc.UTF_16_WITH_BOM:if(255===r[0]&&254===r[1]){const e=new TextDecoder("utf-16le"),t=Fe(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2===0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}if(254===r[0]&&255===r[1]){const e=new TextDecoder("utf-16be"),t=Fe(r.findIndex((e,t)=>0===e&&0===r[t+1]&&t%2===0),r.length);return this.pos=i+Math.min(t+2,r.length),e.decode(r.subarray(2,t))}{const e=Fe(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),O.decode(r.subarray(0,e))}case oc.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=Fe(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 oc.UTF_8:{const e=Fe(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),O.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class kc{constructor(e){this.events=e,this.input=null,this.audioSink=null,this.audioIterator=null,this.audioContext=null,this.gainNode=null,this.audioContextStartTime=0,this.playbackTimeAtStart=0,this.latestScheduledEndTime=0,this.duration=Number.NaN,this.paused=!0,this.volume=.7,this.muted=!1,this.playbackRate=1,this.asyncId=0,this.queuedNodes=new Set}get currentTime(){return this.paused?this.playbackTimeAtStart:(this.audioContext.currentTime-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart}ensureAudioContext(e){if(this.audioContext)return;const t=window.AudioContext||window.webkitAudioContext;try{this.audioContext=new t({sampleRate:e})}catch{this.audioContext=new t}this.gainNode=this.audioContext.createGain(),this.gainNode.connect(this.audioContext.destination),this.updateGain()}updateGain(){if(!this.gainNode)return;const e=this.muted?0:this.volume;this.gainNode.gain.value=e*e}stopQueuedNodes(){this.queuedNodes.forEach(e=>e.stop()),this.queuedNodes.clear()}async stopIterator(){await(this.audioIterator?.return()),this.audioIterator=null}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}async load(e,t){++this.asyncId,await this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:a}=e;return this.input=i,this.duration=a,r?null!==r.codec&&await r.canDecode()?(this.ensureAudioContext(r.sampleRate),this.audioSink=new wo(r),void t?.()):(this.audioSink=null,this.ensureAudioContext(),void t?.()):(this.handleNoAudioTrack(),void t?.())}async runIterator(e){if(!this.audioSink)return;await this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);for(;;){if(e!==this.asyncId||this.paused)return;const i=[];let r=!1;try{for(let e=0;e<16;e++){const e=await this.audioIterator.next();if(e.done){r=!0;break}i.push(e.value)}}catch(t){console.error("Audio iterator error:",t),r=!0}if(e!==this.asyncId||this.paused)return;i.length>0&&"suspended"===this.audioContext.state&&(await this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing"));for(const{buffer:e,timestamp:t}of i){const i=this.audioContext.createBufferSource();i.buffer=e,i.connect(this.gainNode),i.playbackRate.value=this.playbackRate;const r=this.audioContextStartTime+(t-this.playbackTimeAtStart)/this.playbackRate,a=(r+e.duration/this.playbackRate-this.audioContextStartTime)*this.playbackRate+this.playbackTimeAtStart;a>this.latestScheduledEndTime&&(this.latestScheduledEndTime=a),r>=this.audioContext.currentTime?i.start(r):i.start(this.audioContext.currentTime,(this.audioContext.currentTime-r)*this.playbackRate),this.queuedNodes.add(i),i.onended=()=>this.queuedNodes.delete(i)}if(r)break;await new Promise(e=>setTimeout(e,0));const a=1;for(;this.latestScheduledEndTime-this.currentTime>a;){if(e!==this.asyncId||this.paused)return;await new Promise(e=>setTimeout(e,50))}}}async play(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&await this.audioContext.resume(),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1;const e=++this.asyncId;this.runIterator(e)}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}async seek(e){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart;const t=++this.asyncId;this.paused||this.runIterator(t)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(e!==this.playbackRate&&(this.paused||(this.playbackTimeAtStart=this.currentTime,this.audioContextStartTime=this.audioContext.currentTime),this.playbackRate=e,!this.paused)){const e=++this.asyncId;this.runIterator(e)}}destroy(){this.asyncId++,this.pause(),this.audioContext?.close(),this.audioContext=null,this.input=null,this.audioSink=null}}async function yc(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const bc=/\.m3u8(?:$|[?#])/i;function wc(e){return"string"===typeof e&&bc.test(e)}function Tc(e){const t=function(e){return"string"===typeof e?new _s(e):e instanceof Blob?new Cs(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new As(e):e??null}(e);return t?new Mo({source:t,formats:wc(e)?Tn:wn}):null}class Sc{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){return this.controller?.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}async wait(e,t){try{await Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,e?.dispose()}cancel(){if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),this.controller?.abort(),this.disposeInput()}}}function vc(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}async function Pc({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),a=t||i,s=Boolean(a&&await a.isLive());let n=Number.NaN;return r.length>0&&(n=await e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==n||s||(n=await e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:n??Number.NaN}function Ic(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class xc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null,this.audioStart=null}operation(){return{...Ic(),source:this.host.loadSeq,complete:Ic()}}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,e?.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,e?.complete.resolve(),e?.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}async startAudio(){this.audioStart||(this.audioStart=this.host.audio.play());const e=this.audioStart;try{await e}finally{this.audioStart===e&&(this.audioStart=null)}}async runPlay(e){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(await this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,await this.startAudio(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),vc(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}}seek(e,t){return this.position(async t=>{const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();await Promise.all([i,r])},["seeked"],!1,t)}replace(e,t){return this.position(async i=>{e.duration=await Pc(e),i()&&(this.host.media=e,await Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(await Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))},["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=r??(this.seeking?this.wanted:!this.host.paused),this.cancelPlay();const a=this.seeking,s=this.operation();return this.seeking=s,a?.complete.resolve(),a?.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}async runPosition(e,t,i,r){const a=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!a())return;if(this.host.ended=!1,this.host.seeking=!0,vc(this.host.events,a,["seeking","waiting"]),!a())return;if(r||this.stop(),!a())return;if(await t(a),!a())return;if(this.host.seeking=!1,e.complete.resolve(),vc(this.host.events,a,i),!a())return;this.seeking=null,s=this.wanted}catch(n){if(!a())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(n),n}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&await this.play()}}const Cc=new WeakMap,Bc=new WeakMap;function Ec(e){const t=Bc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>e.value??null);Bc.set(e,i);const r=()=>{Bc.get(e)===i&&Bc.delete(e)};return i.then(r,r),i}function _c(e,t,i,r,a){const s=i?Math.max(.06,r/Math.max(1,a)):0;return i&&e<t-s?"skip":e<=t+s?"draw":"queue"}class Rc{constructor(){this.image=null}cancel(){this.image&&(this.image.onload=null,this.image.onerror=null,this.image=null)}draw(e,t,i,r){this.cancel();const a=new Image;this.image=a,a.onload=()=>{if(this.image===a&&t()){this.cancel();try{i(a)}catch(e){r(e)}}},a.onerror=()=>{this.image===a&&this.cancel()},a.src=e}}class Fc{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}async update(e){const t=this.host.videoIterator;if(!t||!this.ready()||!this.current(e)||this.host.isFetching)return;const i={};this.fetching=i,this.host.isFetching=!0;const r=()=>this.current(e)&&this.host.videoIterator===t;try{for(;r();){const e=await Ec(t);if(!r()||!e)return;const i=this.host.audioClock?.currentTime;if(void 0===i)return;const a=_c(e.timestamp,i,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==a){if("draw"!==a)return void(this.host.nextFrame=e);this.draw(e)}}}catch(a){if(r())throw a}finally{this.fetching===i&&(this.fetching=null,this.host.isFetching=!1)}}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void vc(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(vc(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i<this.host.duration&&!this.host.stalled&&(this.host.stalled=!0,this.host.events.emit("waiting")));this.schedule(e)}else this.schedule(e)}start(e){this.closed||(this.stop(),this.stopped=!1,this.host.audioClock=e,this.host.stalled=!1,this.host.nextFrame||this.request(this.host.asyncId),this.schedule(this.host.asyncId))}stop(){this.stopped=!0,this.host.asyncId++,this.cancelFrame(),this.fetching=null,this.host.isFetching=!1}destroy(){this.closed||(this.stop(),this.closed=!0)}}class Ac{constructor({canvas:e,ctx:h,events:f,timeupdateInterval:p=250,avSyncTolerance:k=.12,dropLateFrames:y=!1,poster:b="",preflightRange:w=!1,onError:T}){v(this,d),v(this,t,0),v(this,i,0),v(this,r,null),v(this,a,null),v(this,s,null),v(this,n,!1),v(this,o,!1),v(this,c,new Rc),v(this,l),v(this,u),this.canvas=e,this.ctx=h,this.events=f,this.timeupdateInterval=p,this.avSyncTolerance=k,this.dropLateFrames=y,this.poster=b,this.preflightRange=w,this.input=null,this.videoSink=null,this.videoIterator=null,this.nextFrame=null,this.rafId=0,this.asyncId=0,this.width=0,this.height=0,this.duration=Number.NaN,this.audioClock=null,this.lastTimeUpdate=0,this.stalled=!1,this.playbackRate=1,this.posterDrawn=!1,this.isFetching=!1,P(this,u,T),P(this,l,new Fc(this,()=>!S(this,o),e=>I(this,d,g).call(this,e,!0),e=>I(this,d,m).call(this,e)))}async preflight(e,t,i){return async function(e,t,i,r,a=()=>!0){if(r?.aborted||!a())return!1;if(!t||"string"!==typeof e||wc(e))return!0;try{const t=await fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if(r?.aborted||!a())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!(r?.aborted||!a())&&(console.warn("Preflight check failed:",s),!0)}}(e,this.preflightRange,this.events,t,i)}drawPoster(){if(S(this,n)||!this.poster||this.posterDrawn)return;const e=S(this,t);S(this,c).draw(this.poster,()=>I(this,d,h).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,I(this,d,f).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>I(this,d,m).call(this,e))}async stopIterator(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,await function(e){if(!e)return Promise.resolve();const t=Cc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return Cc.set(e,i),i}(e)}clear(){I(this,d,f).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){x(this,t)._++,x(this,i)._++,this.stop(),I(this,d,p).call(this),S(this,c).cancel(),P(this,o,!1),P(this,r,null),P(this,a,null),P(this,s,null),this.videoSink=null,this.input=null}async load(e,a){if(S(this,n))return;this.cancelPending();const s=S(this,t),c=S(this,i);P(this,o,!0);const l=Promise.resolve().then(()=>I(this,d,k).call(this,e,s,c,a));P(this,r,l);try{await l}finally{S(this,r)===l&&P(this,r,null)}}handleNoVideoTrack(){S(this,n)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}async resetIterator(e){if(S(this,n))return;const a=S(this,t),s=++x(this,i)._,l=S(this,r);this.stop(),S(this,c).cancel(),P(this,o,!0);try{l&&await l,await I(this,d,y).call(this,e,a,s)}catch(u){if(I(this,d,h).call(this,a)&&S(this,i)===s)throw I(this,d,p).call(this),u}finally{I(this,d,h).call(this,a)&&S(this,i)===s&&P(this,o,!1)}}async updateNextFrame(e){await S(this,l).update(e)}render(){S(this,l).render()}start(e){S(this,l).start(e)}stop(){S(this,l).stop()}async seek(e){await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){S(this,n)||(P(this,n,!0),x(this,t)._++,S(this,l).destroy(),S(this,c).cancel(),I(this,d,p).call(this),this.posterDrawn=!1,P(this,a,null),P(this,s,null),this.videoSink=null,this.input=null,this.audioClock=null)}}t=new WeakMap,i=new WeakMap,r=new WeakMap,a=new WeakMap,s=new WeakMap,n=new WeakMap,o=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakMap,d=new WeakSet,h=function(e){return!S(this,n)&&S(this,t)===e},f=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},m=function(e){S(this,n)||(I(this,d,p).call(this),S(this,u)?S(this,u).call(this,e):this.events.emit("error",e))},p=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},g=function(e,t){S(this,c).cancel(),t&&this.clear(),I(this,d,f).call(this).drawImage(e.canvas,0,0)},k=async function(e,t,r,s){if(I(this,d,h).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:n,duration:o}=e;if(this.input=i,this.duration=o,!n)return this.handleNoVideoTrack(),void s?.();const c=null!==n.codec&&await n.canDecode();if(!I(this,d,h).call(this,t))return;if(!c)return this.handleNoVideoTrack(),void s?.();const l=await n.canBeTransparent();if(!I(this,d,h).call(this,t))return;P(this,a,()=>new go(n,{poolSize:2,fit:"contain",alpha:l})),this.videoSink=S(this,a).call(this),this.width=n.displayWidth,this.height=n.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,s?.(),I(this,d,h).call(this,t)&&await I(this,d,y).call(this,0,t,r)}catch(n){if(I(this,d,h).call(this,t))throw I(this,d,p).call(this),n}finally{I(this,d,h).call(this,t)&&S(this,i)===r&&P(this,o,!1)}},y=async function(e,t,r){if(!I(this,d,h).call(this,t)||S(this,i)!==r)return;I(this,d,p).call(this),S(this,a)&&this.videoSink===S(this,s)&&(this.videoSink=S(this,a).call(this));const n=this.videoSink;if(!n||!I(this,d,h).call(this,t))return;P(this,s,n);const o=n.canvases(e);this.videoIterator=o;const c=()=>I(this,d,h).call(this,t)&&S(this,i)===r&&this.videoIterator===o,l=await Ec(o);if(!c())return;const u=await Ec(o);c()&&(this.nextFrame=u,l?I(this,d,g).call(this,l,!1):this.drawPoster())};class Dc{constructor({canvas:e,ctx:t,events:i,option:r={}}){v(this,b),this.events=i,this.option=r,this.audio=new kc(i),this.video=new Ac({canvas:e,ctx:t,events:i,timeupdateInterval:r.timeupdateInterval??250,avSyncTolerance:r.avSyncTolerance??.12,dropLateFrames:r.dropLateFrames??!1,poster:r.poster??"",preflightRange:r.preflightRange??!1,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,P(this,b,new xc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,S(this,b).ended())})}async load(e){if(this.destroyed)return;const t=++this.loadSeq;if(S(this,b).invalidate(),this.video.cancelPending(),this.loadSession?.cancel(),t!==this.loadSeq||this.destroyed)return;if(this.pause(),t!==this.loadSeq||this.destroyed)return;this.disposeInput();const i=new Sc;this.loadSession=i,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,i.defer(()=>this.events.emit("waiting")),i.defer(()=>this.events.emit("loadstart"));const r=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout??0:0;try{await i.wait(this.performLoad(e,t,i),r)}catch(a){if(t!==this.loadSeq)return;const e=++this.loadSeq;if(S(this,b).invalidate(),this.video.cancelPending(),i.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}}async performLoad(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(await this.video.preflight(e,i.signal,r))||!r())return;const a=Tc(e);if(!a)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(a);const s=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await Pc({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=wc(t);return{input:e,videoTrack:i,audioTrack:r,duration:a,isLive:!Number.isFinite(a)&&Boolean(s&&await s.isLive()),isHls:n,videoMode:n?"auto":"manual",audioMode:n?"auto":"manual"}}(a,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=a,this.media=s;const n=function(e,t){let i=!1,r=!1,a=!1;function s(s){t()&&!a&&("video"===s?i=!0:r=!0,i&&r&&(a=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,vc(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,n.video),t=r()?this.audio.load(s,n.audio):Promise.resolve();if(await Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,vc(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){this.loadSession?.disposeInput(),this.input=null,this.media=null}async replaceTracks(e){if(this.media&&!this.destroyed)return S(this,b).replace({...this.media,...e},this.currentTime)}async selectHlsQuality(e){return async function(e,t){const{input:i,media:r,loadSeq:a}=e;if(!r?.isHls||!i||e.destroyed)return;const s=()=>!e.destroyed&&e.loadSeq===a&&e.input===i&&e.media===r;let n;try{const e=await i.getVideoTracks();if(!s())return;const a="auto"===t?await i.getPrimaryVideoTrack():e.find(e=>e.id===t)??r.videoTrack;if(!s()||!a)return;let o=r.audioTrack,c=r.audioMode;o&&a.canBePairedWith(o)||(o=await a.getPrimaryPairableAudioTrack(),c="auto"),n={videoTrack:a,audioTrack:o,videoMode:"auto"===t?"auto":"manual",audioMode:c}}catch(o){if(!s())return;throw o}s()&&await e.replaceTracks(n)}(this,e)}async selectHlsAudio(e){return async function(e,t){const{input:i,media:r,loadSeq:a}=e;if(!r?.isHls||!i||e.destroyed)return;const s=()=>!e.destroyed&&e.loadSeq===a&&e.input===i&&e.media===r;let n;try{const e=await i.getAudioTracks();if(!s())return;const a="auto"===t?r.videoTrack?await r.videoTrack.getPrimaryPairableAudioTrack():await i.getPrimaryAudioTrack():e.find(e=>e.id===t)??r.audioTrack;if(!s()||!a)return;let o=r.videoTrack,c=r.videoMode;o&&a.canBePairedWith(o)||(o=await a.getPrimaryPairableVideoTrack(),c="auto"),n={videoTrack:o,audioTrack:a,videoMode:c,audioMode:"auto"===t?"auto":"manual"}}catch(o){if(!s())return;throw o}s()&&await e.replaceTracks(n)}(this,e)}async getHlsState(){const e=this.media;if(this.destroyed)return null;try{const t=await async function(e){if(!e?.isHls||!e.input)return null;const[t,i]=await Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[r,a]=await Promise.all([Promise.all(t.map(async(e,t)=>({id:e.id,track:e,index:t,name:await e.getName(),height:await e.getDisplayHeight(),bitrate:await yc(e)}))),Promise.all(i.map(async(e,t)=>{const i=await e.getName(),r=await e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:await yc(e)}}))]);return{levels:r,audios:a,currentLevel:e.videoTrack?r.find(t=>t.id===e.videoTrack?.id)??null:null,currentAudio:e.audioTrack?a.find(t=>t.id===e.audioTrack?.id)??null:null,videoMode:e.videoMode??"auto",audioMode:e.audioMode??"auto"}}(e);return this.destroyed||this.media!==e?null:t}catch(t){if(this.destroyed||this.media!==e)return null;throw t}}async play(){return S(this,b).play()}pause(){S(this,b).pause()}async seek(e){return S(this,b).seek(e)}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,S(this,b).invalidate();const e=[];for(const i of[()=>this.loadSession?.cancel(),()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){return this.media?.duration??this.audio.duration??this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}b=new WeakMap;const Mc=new WeakMap;function Nc(e){let t=Mc.get(e);return t||(t={closed:!1,frames:new Set},Mc.set(e,t)),t}class Oc{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new B,this.engine=new Dc({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=r.volume??.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:e.option?.url&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=Nc(e);if(i.closed)return 0;const r=requestAnimationFrame(a=>{i.frames.delete(r),i.closed||t(a,{presentationTime:e.engine.currentTime,expectedDisplayTime:a+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:a,receiveTime:a,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){Nc(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=Nc(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,a=r("canvas"),s=a.getContext("2d"),n=new Oc({art:t,canvas:a,ctx:s,option:e});t.mediabunny=n;const o={};for(const e in a)"function"===typeof a[e]&&(o[e]=a[e].bind(a));const c=new Set([...Object.getOwnPropertyNames(n),...Object.getOwnPropertyNames(Object.getPrototypeOf(n))]);for(const e of c)"constructor"!==e&&(e in a||Object.defineProperty(a,e,{get(){const t=n[e];return"function"===typeof t?t.bind(n):t},set(t){n[e]=t},configurable:!0,enumerable:!0}));for(const e in o)a[e]=(...t)=>o[e](...t);function l(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(a.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",l),t.on("video:loadedmetadata",l),function({art:e,shim:t,option:i}){if(i.m3u8)return e.on("video:loadedmetadata",u),e.on("restart",u),{update:u};function r(t){e.controls.cache.has(t)&&e.controls.remove(t)}function a(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),a("mediabunny-quality")}function n(){r("mediabunny-audio"),a("mediabunny-audio")}function o(e={}){return e.control||e.setting}async function c(r){const a=i.m3u8?.quality||{};if(!o(a)||!r?.levels.length)return void s();const n=a.auto||"Auto",c=a.title||"Quality",l=a.getName||(e=>e.name||`${e.height}P`),d=r.currentLevel?l(r.currentLevel):n,h=C(r.levels.map(e=>({html:l(e),value:e.id,default:r.currentLevel?.id===e.id})),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),a=r.levels.find(e=>e.id===t.value);return(a?.height||0)-(i?.height||0)});h.push({html:n,value:"auto",default:!r.currentLevel});const f=async i=>(await t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,await u(),i.html);a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:d,style:{padding:"0 10px"},selector:h,onSelect:f}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:d,html:c,icon:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" height="18"><path fill="#fff" d="M0 96C0 60.7 28.7 32 64 32l384 0c35.3 0 64 28.7 64 64l0 320c0 35.3-28.7 64-64 64L64 480c-35.3 0-64-28.7-64-64L0 96zM323.8 202.5c-4.5-6.6-11.9-10.5-19.8-10.5s-15.4 3.9-19.8 10.5l-87 127.6L170.7 297c-4.6-5.7-11.5-9-18.7-9s-14.2 3.3-18.7 9l-64 80c-5.8 7.2-6.9 17.1-2.9 25.4s12.4 13.6 21.6 13.6l96 0 32 0 208 0c8.9 0 17.1-4.9 21.2-12.8s3.6-17.4-1.4-24.7l-120-176zM112 192a48 48 0 1 0 0-96 48 48 0 1 0 0 96z"/></svg>',width:200,selector:h,onSelect:f})}async function l(r){const a=i.m3u8?.audio||{};if(!o(a)||!r?.audios.length||r.audios.length<2)return void n();const s=a.auto||"Auto",c=a.title||"Audio",l=a.getName||(e=>e.name||e.lang||e.language),d=r.currentAudio?l(r.currentAudio):s,h=C(r.audios.map(e=>({html:l(e),value:e.id,default:r.currentAudio?.id===e.id})),"html");h.push({html:s,value:"auto",default:!r.currentAudio});const f=async i=>(await t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,await u(),i.html);a.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:d,style:{padding:"0 10px"},selector:h,onSelect:f}),a.setting&&e.setting.update({name:"mediabunny-audio",tooltip:d,html:c,icon:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512" height="18"><path fill="#fff" d="M256 80C149.9 80 62.4 159.4 49.6 262c9.4-3.8 19.6-6 30.4-6c26.5 0 48 21.5 48 48l0 128c0 26.5-21.5 48-48 48c-44.2 0-80-35.8-80-80l0-16 0-48 0-48C0 146.6 114.6 32 256 32s256 114.6 256 256l0 48 0 48 0 16c0 44.2-35.8 80-80 80c-26.5 0-48-21.5-48-48l0-128c0-26.5 21.5-48 48-48c10.8 0 21 2.1 30.4 6C449.6 159.4 362.1 80 256 80z"/></svg>',width:200,selector:h,onSelect:f})}async function u(){const e=await t.getM3u8State();if(!e)return s(),void n();await Promise.all([c(e),l(e)])}}({art:t,shim:n,option:e}),t.on("destroy",()=>{delete t.mediabunny,n.destroy()}),a}}});