Files
ArtPlayer/docs/compiled/artplayer-proxy-mediabunny.legacy.js
Harvey Zhao 26841c5b1c feat: enable fullscreenWeb option in Artplayer configuration
feat: add danmuku plugin and i18n setup documentation

- Introduced a new danmuku plugin with multiple run code options in the documentation.
- Added language settings documentation for i18n, including default languages, import instructions, and examples for adding and modifying languages.
- Implemented input handling for media sources in the artplayer-proxy-mediabunny package, supporting various formats including HLS.
- Created m3u8 control functionalities for managing audio and video quality settings in the player.

Update mediabunny.js
2026-05-04 13:22:32 +08:00

8 lines
381 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?(t.artplayerProxyMediabunny=t(),define(function(){return t.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e=Object.defineProperty,t=Object.defineProperties,i=Object.getOwnPropertyDescriptors,r=Object.getOwnPropertySymbols,n=Object.prototype.hasOwnProperty,s=Object.prototype.propertyIsEnumerable,a=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),o=Math.pow,l=(t,i,r)=>i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[i]=r,c=(e,t)=>{for(var i in t||(t={}))n.call(t,i)&&l(e,i,t[i]);if(r)for(var i of r(t))s.call(t,i)&&l(e,i,t[i]);return e},u=(e,r)=>t(e,i(r)),d=(e,t,i)=>new Promise((r,n)=>{var s=e=>{try{o(i.next(e))}catch(t){n(t)}},a=e=>{try{o(i.throw(e))}catch(t){n(t)}},o=e=>e.done?r(e.value):Promise.resolve(e.value).then(s,a);o((i=i.apply(e,t)).next())}),h=function(e,t){this[0]=e,this[1]=t},f=(e,t,i)=>{var r=(e,t,n,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof h,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?r("return"===e?e:"next",t[1]?{done:i.done,value:i.value}:i,n,s):n({value:i,done:l})).catch(e=>r("throw",e,n,s))}catch(c){s(c)}},n=e=>s[e]=t=>new Promise((i,n)=>r(e,t,i,n)),s={};return i=i.apply(e,t),s[a("asyncIterator")]=()=>s,n("next"),n("throw"),n("return"),s},m=e=>{var t,i=e[a("asyncIterator")],r=!1,n={};return null==i?(i=e[a("iterator")](),t=e=>n[e]=t=>i[e](t)):(i=i.call(e),t=e=>n[e]=t=>{if(r){if(r=!1,"throw"===e)throw t;return t}return r=!0,{done:!1,value:new h(new Promise(r=>{var n=i[e](t);n instanceof Object||(e=>{throw TypeError(e)})("Object expected"),r(n)}),1)}}),n[a("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},p=(e,t,i)=>(t=e[a("asyncIterator")])?t.call(e):(e=e[a("iterator")](),t={},(i=(i,r)=>(r=e[i])&&(t[i]=t=>new Promise((i,n,s)=>(t=r.call(e,t),s=t.done,Promise.resolve(t.value).then(e=>i({value:e,done:s}),n)))))("next"),i("return"),t);function g(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 k{constructor(){this.listeners=new Map}addEventListener(e,t){this.listeners.has(e)||this.listeners.set(e,[]),this.listeners.get(e).push(t)}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(e,t){const i=new Event(e);i.detail=t;const r=this.listeners.get(e);r&&r.forEach(e=>e(i))}}function y(e){if(!e)throw new Error("Assertion failed.")}const b=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},T=e=>e&&e[e.length-1],S=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)},v=e=>{const t=S(e);return 0===(1&t)?-(t>>1):t+1>>1},w=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),P=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),I=new TextDecoder,x=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),C={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},B=x(C),E={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},_=x(E),A={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},F=x(A),R=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class D{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return d(this,null,function*(){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++,yield i,e})}}const M=/^[0-9a-fA-F]+$/,N=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),O=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,L=(e,t,i)=>{let r=0,n=e.length-1,s=-1;for(;r<=n;){const a=r+n>>1,o=i(e[a]);o===t?(s=a,n=a-1):o<t?r=a+1:n=a-1}return s},z=(e,t,i)=>{let r=0,n=e.length-1,s=-1;for(;r<=n;){const a=r+(n-r+1)/2|0;i(e[a])<=t?(s=a,r=a+1):n=a-1}return s},U=(e,t,i)=>{const r=z(e,i(t),i);e.splice(r+1,0,t)},q=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},W=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},V=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},H=e=>{throw new Error(`Unexpected value: ${e}`)},K=(e,t,i)=>{const r=e.getUint8(t),n=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|n<<8|s<<16:r<<16|n<<8|s},j=(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)},X=(e,t)=>({next(){return d(this,null,function*(){const i=yield 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}}),$=(e,t,i)=>Math.max(t,Math.min(i,e)),Q="und",G=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Y=(e,t)=>Math.round(e*t)/t,J=(e,t)=>Math.floor(e/t)*t,Z=/^[a-z]{3}$/,ee=e=>Z.test(e),te=1e6*(1+Number.EPSILON),ie=(e,t)=>{const i=c(c({},e),t);if(e.headers||t.headers){const r=e.headers?re(e.headers):{},n=t.headers?re(t.headers):{},s=c({},r);Object.entries(n).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},re=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},ne=(e,t,i,r,n)=>d(null,null,function*(){let s=0;for(;;)try{return yield e(t,i)}catch(a){if(n())throw a;s++;const e=r(s,a,t);if(null===e)throw a;if(console.error("Retrying failed fetch. Error:",a),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&(yield Pe(1e3*e)),n())throw a}});class se{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ae=null;const oe=()=>{var e;return null!==ae?ae:ae=!("undefined"===typeof navigator||!((null==(e=navigator.vendor)?void 0:e.match(/apple/i))||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)))};let le=null;const ce=()=>{var e;return null!==le?le:le="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let ue=null;const de=()=>{var e;return null!==ue?ue:ue=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))};let he=null;const fe=()=>{if(null!==he)return he;if("undefined"===typeof navigator)return null;const e=/\bChrome\/(\d+)/.exec(navigator.userAgent);return e?he=Number(e[1]):null},me=(e,t)=>-1!==e?e:t,pe=(e,t,i,r)=>e<=r&&i<=t,ge=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},ke=()=>{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},ye=e=>"number"===typeof e&&!Number.isNaN(e),be=(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 n=e.indexOf("/",r+3);i=-1===n?e+t:e.slice(0,n)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const n=i.indexOf("://");if(-1!==n){const e=i.indexOf("/",n+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),a=[];for(const o of s)".."===o?a.pop():"."!==o&&a.push(o);return r+a.join("/")},Te=(e,t)=>{let i=0;for(let r=0;r<e.length;r++)t(e[r])&&i++;return i},Se=(e,t)=>{let i=-1,r=1/0;for(let n=0;n<e.length;n++){const s=t(e[n]);s<r&&(r=s,i=n)}return i},ve=e=>{y(Number.isInteger(e.num)),y(Number.isInteger(e.den)),y(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}},we=(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.`)},Pe=e=>new Promise(t=>setTimeout(t,e));class Ie{constructor(){this._listeners=new Map}on(e,t,i){var r;this._listeners.has(e)||this._listeners.set(e,new Set);const n={fn:t,once:null!=(r=null==i?void 0:i.once)&&r};return this._listeners.get(e).add(n),()=>{var t;null==(t=this._listeners.get(e))||t.delete(n)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(n){console.error(n)}s.once&&r.delete(s)}}}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 Ce{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 Be={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Ee{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){var e;const t=Math.floor(this.pos/8),i=null!=(e=this.bytes[t])?e:0,r=7-(7&this.pos),n=(i&1<<r)>>r;return this.pos++,n}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 n=this.bytes[e];const s=7-(7&r);n&=~(1<<s),n|=(t&1<<i-r-1)>>i-r-1<<s,this.bytes[e]=n}this.pos=i}readAlignedByte(){var e;if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const t=this.pos/8,i=null!=(e=this.bytes[t])?e:0;return this.pos+=8,i}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new Ee(this.bytes);return e.pos=this.pos,e}}const _e=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],Ae=[-1,1,2,3,4,5,6,8],Fe=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Ee(e);let i=t.readBits(5);31===i&&(i=32+t.readBits(6));const r=t.readBits(4);let n=null;15===r?n=t.readBits(24):r<_e.length&&(n=_e[r]);const s=t.readBits(4);let a=null;return s>=1&&s<=7&&(a=Ae[s]),{objectType:i,frequencyIndex:r,sampleRate:n,channelConfiguration:s,numberOfChannels:a}},Re=["avc","hevc","vp9","av1","vp8"],De=["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"],Me=["aac","opus","mp3","vorbis","flac","ac3","eac3",...De],Ne=[{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}],Oe=[{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}],Le=".01.01.01.01.00",ze=".0.110.01.01.01.0",Ue=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o}=e;if("avc"===t){if(y(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${N(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}.${N(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=O(s.generalProfileCompatibilityFlags),n=s.generalTierFlag,a=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=P(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=O(s.getUint32(2)),n=l>>5&1,a=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let l="hev1.";for(l+=["","A","B","C"][e]+t,l+=".",l+=r.toString(16).toUpperCase(),l+=".",l+=0===n?"L":"H",l+=a;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(l+=".",l+=o.map(e=>e.toString(16).toUpperCase()).join(".")),l}if("vp8"===t)return"vp8";if("vp9"===t){if(!a){const t=e.width*e.height;let i=T(Oe).level;for(const e of Oe)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${a.profile.toString().padStart(2,"0")}.${a.level.toString().padStart(2,"0")}.${a.bitDepth.toString().padStart(2,"0")}.${a.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${a.colourPrimaries.toString().padStart(2,"0")}.${a.transferCharacteristics.toString().padStart(2,"0")}.${a.matrixCoefficients.toString().padStart(2,"0")}.${a.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Le)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=T(Oe).level;for(const e of Oe)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"),n=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),a=o.monochrome?"1":"0",l=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),c=(null==r?void 0:r.primaries)?C[r.primaries]:1,u=(null==r?void 0:r.transfer)?E[r.transfer]:1,d=(null==r?void 0:r.matrix)?A[r.matrix]:1,h=(null==r?void 0:r.fullRange)?1:0;let f=`av01.${t}.${i}${n}.${s}`;return f+=`.${a}.${l.toString().padStart(3,"0")}`,f+=`.${c.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${d.toString().padStart(2,"0")}`,f+=`.${h}`,f.endsWith(ze)&&(f=f.slice(0,-17)),f}throw new TypeError(`Unhandled codec '${t}'.`)},qe=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r}=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=Fe(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(t&&De.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},We=48e3,Ve=/^pcm-([usf])(\d+)+(be)?$/,He=e=>{if(y(De.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=Ve.exec(e);let i;y(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?o(2,7):0}},Ke=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":"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":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Ve.test(e)?e:"webvtt"===e?"webvtt":null,je=[44100,48e3,32e3],Xe=[-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],$e=1483304551,Qe=1231971951,Ge=(e,t)=>3===e?3===t?21:36:3===t?13:21,Ye=(e,t)=>{const i=e>>>24,r=e>>>16&255,n=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==n&&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 a=0,o=0;16&r?a=8&r?0:1:(a=1,o=1);const l=r>>3&3,c=r>>1&3,u=(n>>2&3)%3,d=s>>6&3,h=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Xe[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=je[u]>>a+o,b=((e,t,i,r,n)=>0===t?0:1===t?Math.floor(144*i/(r<<e))+n:2===t?Math.floor(144*i/r)+n:4*(Math.floor(12*i/r)+n))(a,c,k,y,n>>1&1);if(null!==t&&t<b)return{header:null,bytesAdvanced:1};let T;return T=3===l?3===c?384:1152:3===c?384:2===c?1152:576,{header:{totalSize:b,mpegVersionId:l,lowSamplingFrequency:a,layer:c,bitrate:k,frequencyIndex:u,sampleRate:y,channel:d,modeExtension:h,copyright:f,original:m,emphasis:p,audioSamplesInFrame:T},bytesAdvanced:1}},Je=e=>{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Ze,et;(et=Ze||(Ze={}))[et.FrameCount=1]="FrameCount",et[et.FileSize=2]="FileSize",et[et.Toc=4]="Toc";const tt=[48e3,44100,32e3],it=[24e3,22050,16e3];var rt,nt,st,at;(nt=rt||(rt={}))[nt.NON_IDR_SLICE=1]="NON_IDR_SLICE",nt[nt.SLICE_DPA=2]="SLICE_DPA",nt[nt.SLICE_DPB=3]="SLICE_DPB",nt[nt.SLICE_DPC=4]="SLICE_DPC",nt[nt.IDR=5]="IDR",nt[nt.SEI=6]="SEI",nt[nt.SPS=7]="SPS",nt[nt.PPS=8]="PPS",nt[nt.AUD=9]="AUD",nt[nt.SPS_EXT=13]="SPS_EXT",(at=st||(st={}))[at.RASL_N=8]="RASL_N",at[at.RASL_R=9]="RASL_R",at[at.BLA_W_LP=16]="BLA_W_LP",at[at.RSV_IRAP_VCL23=23]="RSV_IRAP_VCL23",at[at.VPS_NUT=32]="VPS_NUT",at[at.SPS_NUT=33]="SPS_NUT",at[at.PPS_NUT=34]="PPS_NUT",at[at.AUD_NUT=35]="AUD_NUT",at[at.PREFIX_SEI_NUT=39]="PREFIX_SEI_NUT",at[at.SUFFIX_SEI_NUT=40]="SUFFIX_SEI_NUT";const ot=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 n=0;t+3<e.length&&0===e[t+1]&&0===e[t+2]&&1===e[t+3]?n=4:0===e[t+1]&&1===e[t+2]&&(n=3),0!==n?(-1!==i&&t>i&&(yield{offset:i,length:t-i}),i=t+n,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=K(r,i,!1):(y(4===t),e=r.getUint32(i,!1)),i+=t,yield{offset:i,length:e},i+=e}},ct=(e,t)=>{if(t.description){const i=3&w(t.description)[4];return lt(e,i+1)}return ot(e)},ut=e=>31&e,dt=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)},ht=new Uint8Array([0,0,0,1]),ft=e=>{const t=e.reduce((e,t)=>e+ht.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(ht,r),r+=ht.byteLength,i.set(n,r),r+=n.byteLength;return i},mt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let n=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(n,s.byteLength);break;case 2:e.setUint16(n,s.byteLength,!1);break;case 3:j(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},pt=e=>{try{const t=[],i=[],r=[];for(const o of ot(e)){const n=e.subarray(o.offset,o.offset+o.length),s=ut(n[0]);s===rt.SPS?t.push(n):s===rt.PPS?i.push(n):s===rt.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=kt(n);y(null!==s);const a=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:a?s.chromaFormatIdc:null,bitDepthLumaMinus8:a?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:a?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:a?r:null}}catch(t){return console.error("Error building AVC Decoder Configuration Record:",t),null}},gt={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}},kt=e=>{var t;try{const i=new Ee(dt(e));i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),n=i.readAlignedByte(),s=i.readAlignedByte();S(i);let a=1,o=0,l=0,c=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){a=S(i),3===a&&(c=i.readBits(1)),o=S(i),l=S(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==a?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,n=8;for(let e=0;e<t;e++){if(0!==n){n=(r+v(i)+256)%256}r=0===n?r:n}}}}S(i);const u=S(i);if(0===u)S(i);else if(1===u){i.skipBits(1),v(i),v(i);const e=S(i);for(let t=0;t<e;t++)v(i)}S(i),i.skipBits(1);const d=S(i),h=S(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=S(i),t=S(i),r=S(i),n=S(i);let s,o;if(0===(0===c?a:0))s=1,o=2-k;else{s=3===a?1:2,o=(1===a?2:1)*(2-k)}p-=s*(e+t),g-=o*(r+n)}let b=2,w=2,P=2,I=0,x={num:1,den:1},C=null,B=null;if(i.readBits(1)){if(i.readBits(1)){const e=i.readBits(8);if(255===e)x={num:i.readBits(16),den:i.readBits(16)};else{const t=gt[e];t&&(x=t)}}i.readBits(1)&&i.skipBits(1);if(i.readBits(1)){i.skipBits(3),I=i.readBits(1);i.readBits(1)&&(b=i.readBits(8),w=i.readBits(8),P=i.readBits(8))}i.readBits(1)&&(S(i),S(i));i.readBits(1)&&(i.skipBits(32),i.skipBits(32),i.skipBits(1));const e=i.readBits(1);e&&yt(i);const t=i.readBits(1);t&&yt(i),(e||t)&&i.skipBits(1),i.skipBits(1);i.readBits(1)&&(i.skipBits(1),S(i),S(i),S(i),S(i),C=S(i),B=S(i))}if(null===C){y(null===B);if(44!==r&&86!==r&&100!==r&&110!==r&&122!==r&&244!==r||!(16&n)){const e=d+1,i=(2-k)*(h+1),r=null!=(t=Ne.find(e=>e.level>=s))?t:T(Ne),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);C=n,B=n}else C=0,B=0}return y(null!==B),{profileIdc:r,constraintFlags:n,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:a,bitDepthLumaMinus8:o,bitDepthChromaMinus8:l,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:x,colourPrimaries:b,matrixCoefficients:P,transferCharacteristics:w,fullRangeFlag:I,numReorderFrames:C,maxDecFrameBuffering:B}}catch(i){return console.error("Error parsing AVC SPS:",i),null}},yt=e=>{const t=S(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)S(e),S(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},bt=(e,t)=>{if(t.description){const i=3&w(t.description)[21];return lt(e,i+1)}return ot(e)},Tt=e=>e>>1&63,St=e=>{try{const t=new Ee(dt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:n,general_tier_flag:s,general_profile_idc:a,general_profile_compatibility_flags:o,general_constraint_indicator_flags:l,general_level_idc:c}=wt(t,i);S(t);const u=S(t);let d=0;3===u&&(d=t.readBits(1));const h=S(t),f=S(t);let m=h,p=f;if(t.readBits(1)){const e=S(t),i=S(t),r=S(t),n=S(t);let s=1,a=1;const o=0===d?u:0;1===o?(s=2,a=2):2===o&&(s=2,a=1),m-=(e+i)*s,p-=(r+n)*a}const g=S(t),k=S(t);S(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)S(t),b=S(t),S(t);S(t),S(t),S(t),S(t),S(t),S(t),t.readBits(1)&&t.readBits(1)&&Pt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),S(t),S(t),t.skipBits(1));const T=S(t);if(It(t,T),t.readBits(1)){const e=S(t);for(let i=0;i<e;i++)S(t),t.skipBits(1)}t.skipBits(1),t.skipBits(1);let v=2,w=2,P=2,I=0,x=0,C={num:1,den:1};if(t.readBits(1)){const e=Ct(t,i);C=e.pixelAspectRatio,v=e.colourPrimaries,w=e.transferCharacteristics,P=e.matrixCoefficients,I=e.fullRangeFlag,x=e.minSpatialSegmentationIdc}return{displayWidth:m,displayHeight:p,pixelAspectRatio:C,colourPrimaries:v,transferCharacteristics:w,matrixCoefficients:P,fullRangeFlag:I,maxDecFrameBuffering:b+1,spsMaxSubLayersMinus1:i,spsTemporalIdNestingFlag:r,generalProfileSpace:n,generalTierFlag:s,generalProfileIdc:a,generalProfileCompatibilityFlags:o,generalConstraintIndicatorFlags:l,generalLevelIdc:c,chromaFormatIdc:u,bitDepthLumaMinus8:g,bitDepthChromaMinus8:k,minSpatialSegmentationIdc:x}}catch(t){return console.error("Error parsing HEVC SPS:",t),null}},vt=e=>{try{const t=[],i=[],r=[],n=[];for(const l of ot(e)){const s=e.subarray(l.offset,l.offset+l.length),a=Tt(s[0]);a===st.VPS_NUT?t.push(s):a===st.SPS_NUT?i.push(s):a===st.PPS_NUT?r.push(s):a!==st.PREFIX_SEI_NUT&&a!==st.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=St(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Ee(dt(e));t.skipBits(16),S(t),S(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),S(t),S(t),v(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&S(t),v(t),v(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),n=t.readBits(1);a=i||n?i&&!n?2:!i&&n?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType:st.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:st.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:st.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:Tt(n[0][0]),nalUnits:n}]:[]];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:a,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 console.error("Error building HEVC Decoder Configuration Record:",t),null}},wt=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),n=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const a=new Uint8Array(6);for(let u=0;u<6;u++)a[u]=e.readBits(8);const o=e.readBits(8),l=[],c=[];for(let u=0;u<t;u++)l.push(e.readBits(1)),c.push(e.readBits(1));if(t>0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u<t;u++)l[u]&&e.skipBits(88),c[u]&&e.skipBits(8);return{general_profile_space:i,general_tier_flag:r,general_profile_idc:n,general_profile_compatibility_flags:s,general_constraint_indicator_flags:a,general_level_idc:o}},Pt=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&&v(e);for(let t=0;t<i;t++)v(e)}else S(e)}},It=(e,t)=>{const i=[];for(let r=0;r<t;r++)i[r]=xt(e,r,t,i)},xt=(e,t,i,r)=>{var n;let s=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){if(t===i){o=t-(S(e)+1)}else o=t-1;e.readBits(1),S(e);const a=null!=(n=r[o])?n:0;for(let t=0;t<=a;t++){e.readBits(1)||e.readBits(1)}s=r[o]}else{const t=S(e),i=S(e);for(let r=0;r<t;r++)S(e),e.readBits(1);for(let r=0;r<i;r++)S(e),e.readBits(1);s=t+i}return s},Ct=(e,t)=>{let i=2,r=2,n=2,s=0,a=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=gt[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),n=e.readBits(8))),e.readBits(1)&&(S(e),S(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(S(e),S(e),S(e),S(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&S(e),e.readBits(1)&&Bt(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=S(e),S(e),S(e),S(e),S(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},Bt=(e,t,i)=>{let r=!1,n=!1,s=!1;r=1===e.readBits(1),n=1===e.readBits(1),(r||n)&&(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 a=0;a<=i;a++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?S(e):i=1===e.readBits(1);let a=1;if(!i){a=S(e)+1}r&&Et(e,a,s),n&&Et(e,a,s)}},Et=(e,t,i)=>{for(let r=0;r<t;r++)S(e),S(e),i&&(S(e),S(e)),e.readBits(1)};var _t,At;(At=_t||(_t={}))[At.audAllowed=0]="audAllowed",At[At.beforeFirstVcl=1]="beforeFirstVcl",At[At.afterFirstVcl=2]="afterFirstVcl",At[At.eoBitstreamAllowed=3]="eoBitstreamAllowed",At[At.noMoreDataAllowed=4]="noMoreDataAllowed";const Ft=(e,t)=>{const i=new Set;let r=_t.audAllowed;for(const s of bt(e,t)){if(r===_t.noMoreDataAllowed){i.add(s.offset);continue}const t=Tt(e[s.offset]);if(r===_t.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>_t.audAllowed?n=!0:r=_t.beforeFirstVcl:t<=31?r>_t.afterFirstVcl?n=!0:r=_t.afterFirstVcl:36===t?r!==_t.afterFirstVcl?n=!0:r=_t.eoBitstreamAllowed:37===t?r<_t.afterFirstVcl?n=!0:r=_t.noMoreDataAllowed:32===t||33===t||34===t||39===t||t>=41&&t<=44||t>=48&&t<=55?r>_t.beforeFirstVcl?n=!0:r=_t.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r<_t.afterFirstVcl&&(n=!0),n&&i.add(s.offset)}if(0===i.size)return null;const n=[];for(const s of bt(e,t))i.has(s.offset)||n.push(e.subarray(s.offset,s.offset+s.length));return((e,t)=>{if(t.description){const i=3&w(t.description)[21];return mt(e,i+1)}return ft(e)})(n,t)},Rt=e=>{const t=new Ee(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 n=8;if(r>=2){n=t.readBits(1)?12:10}const s=t.readBits(3);let a=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);a=e||i?e&&!i?2:1:3,t.skipBits(1)}else a=1}else a=3,o=1;const l=(t.readBits(16)+1)*(t.readBits(16)+1);let c=T(Oe).level;for(const u of Oe)if(l<=u.maxPictureSize){c=u.level;break}return{profile:r,level:c,bitDepth:n,chromaSubsampling:a,videoFullRangeFlag:o,colourPrimaries:2===s?1:1===s?6:2,transferCharacteristics:2===s?1:1===s?6:2,matrixCoefficients:7===s?0:2===s?1:1===s?6:2}},Dt=function*(e){const t=new Ee(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e|=(127&r)<<7*i,!(128&r))break;if(7===i&&128&r)return null}return e>=o(2,32)-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),n=t.readBits(1),s=t.readBits(1);let a;if(t.skipBits(1),n&&t.skipBits(8),s){const e=i();if(null===e)return;a=e}else a=Math.floor(t.getBitsLeft()/8);y(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},Mt=e=>{for(const{type:t,data:i}of Dt(e)){if(1!==t)continue;const e=new Ee(i),r=e.readBits(3);e.readBits(1);const n=e.readBits(1);let s=0,a=0,o=0;if(n)s=e.readBits(5);else{if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1))return null}const t=e.readBits(1);t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5));const i=e.readBits(5);for(let r=0;r<=i;r++){e.skipBits(12);const i=e.readBits(5);if(0===r&&(s=i),i>7){const t=e.readBits(1);0===r&&(a=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}e.readBits(1)&&e.skipBits(4)}}const l=e.readBits(4),c=e.readBits(4),u=l+1;e.skipBits(u);const d=c+1;e.skipBits(d);let h=0;if(h=n?0:e.readBits(1),h&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!n){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=1,k=1,y=0;return p||(0===r?(g=1,k=1):1===r?(g=0,k=0):12===m&&(g=e.readBits(1),g&&(k=e.readBits(1))),g&&k&&(y=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:g,chromaSubsamplingY:k,chromaSamplePosition:y}}return null},Nt=[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],Ot=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 Ee(i);let n=0;for(;r.getBitsLeft()>97;)if(1===r.readBits(1)){n=r.pos;break}if(0===n)throw new Error("Invalid Setup header: framing bit not found.");let s=0,a=!1,o=0;for(;r.getBitsLeft()>=97;){const e=r.pos,t=r.readBits(8),i=r.readBits(16),n=r.readBits(16);if(t>63||0!==i||0!==n){r.pos=e;break}if(r.skipBits(1),s++,s>64)break;r.clone().readBits(6)+1===s&&(a=!0,o=s)}if(!a)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const l=o;r.pos=0,r.skipBits(n);const c=Array(l).fill(0);for(let u=l-1;u>=0;u--)r.skipBits(40),c[u]=r.readBits(1);return{modeBlockflags:c}},Lt=(e,t,i)=>{switch(e){case"avc":for(const e of ct(i,t)){const t=i[e.offset],r=ut(t);if(r>=rt.NON_IDR_SLICE&&r<=rt.SLICE_DPC)return"delta";if(r===rt.IDR)return"key";if(r===rt.SEI&&(!de()||fe()>=144)){const t=i.subarray(e.offset,e.offset+e.length),r=dt(t);let n=1;do{let e=0;for(;;){const t=r[n++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[n++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new Ee(r);e.pos=8*n;const t=S(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n<r.length-1)}}return"delta";case"hevc":for(const e of bt(i,t)){const t=Tt(i[e.offset]);if(t<st.BLA_W_LP)return"delta";if(t<=st.RSV_IRAP_VCL23)return"key"}return"delta";case"vp8":return 0===(1&i[0])?"key":"delta";case"vp9":{const e=new Ee(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 Dt(i))if(1===t){const t=new Ee(r);t.skipBits(4),e=!!t.readBits(1)}else if(3===t||6===t||7===t){if(e)return"key";const t=new Ee(r);if(t.readBits(1))return null;return 0===t.readBits(2)?"key":"delta"}return null}default:H(e),y(!1)}};var zt,Ut;(Ut=zt||(zt={}))[Ut.STREAMINFO=0]="STREAMINFO",Ut[Ut.VORBIS_COMMENT=4]="VORBIS_COMMENT",Ut[Ut.PICTURE=6]="PICTURE";const qt=(e,t)=>{var i,r;const n=P(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=I.decode(e.subarray(s,s+a));s+=a,a>0&&(null!=t.raw||(t.raw={}),null!=(i=t.raw).vendor||(i.vendor=o));const l=n.getUint32(s,!0);s+=4;for(let c=0;c<l;c++){const i=n.getUint32(s,!0);s+=4;const a=I.decode(e.subarray(s,s+i));s+=i;const o=a.indexOf("=");if(-1===o)continue;const l=a.slice(0,o).toUpperCase(),c=a.slice(o+1);switch(null!=t.raw||(t.raw={}),null!=(r=t.raw)[l]||(r[l]=c),l){case"TITLE":null!=t.title||(t.title=c);break;case"DESCRIPTION":null!=t.description||(t.description=c);break;case"ARTIST":null!=t.artist||(t.artist=c);break;case"ALBUM":null!=t.album||(t.album=c);break;case"ALBUMARTIST":null!=t.albumArtist||(t.albumArtist=c);break;case"COMMENT":null!=t.comment||(t.comment=c);break;case"LYRICS":null!=t.lyrics||(t.lyrics=c);break;case"TRACKNUMBER":{const e=c.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=t.trackNumber||(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=t.tracksTotal||(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(null!=t.tracksTotal||(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=c.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=t.discNumber||(t.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=t.discsTotal||(t.discsTotal=r))}break;case"DISCTOTAL":{const e=Number.parseInt(c,10);Number.isInteger(e)&&e>0&&(null!=t.discsTotal||(t.discsTotal=e))}break;case"DATE":{const e=new Date(c);Number.isNaN(e.getTime())||null!=t.date||(t.date=e)}break;case"GENRE":null!=t.genre||(t.genre=c);break;case"METADATA_BLOCK_PICTURE":{const e=ge(c),i=P(e),r=i.getUint32(0,!1),n=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+n)),a=i.getUint32(8+n,!1),o=I.decode(e.subarray(12+n,12+n+a)),l=i.getUint32(n+a+28),u=e.subarray(n+a+32,n+a+32+l);null!=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})}}}},Wt=[2,1,2,3,3,4,4,5],Vt=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ee(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),n=t.readBits(5);if(n>8)return null;const s=t.readBits(3),a=t.readBits(3);0!==(1&a)&&1!==a&&t.skipBits(2),0!==(4&a)&&t.skipBits(2),2===a&&t.skipBits(2);return{fscod:i,bsid:n,bsmod:s,acmod:a,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},Ht=[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],Kt=[1,2,3,6],jt=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Ee(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),n=t.readBits(2);let s,a=0;3===n?(a=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),l=t.readBits(1),c=t.readBits(5);if(c<11||c>16)return null;const u=Kt[s];let d;d=n<3?tt[n]/1e3:it[a]/1e3;return{dataRate:Math.round((r+1)*d/(16*u)),substreams:[{fscod:n,fscod2:a,bsid:c,bsmod:0,acmod:o,lfeon:l,numDepSub:0,chanLoc:0}]}},Xt=e=>{const t=e.substreams[0];return y(t),t.fscod<3?tt[t.fscod]:null!==t.fscod2&&t.fscod2<3?it[t.fscod2]:null},$t=e=>{const t=e.substreams[0];y(t);let i=Wt[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};class Qt{constructor(e){this.input=e}dispose(){}}const Gt=new Uint8Array(0);class Yt{constructor(e,t,i,r,n=-1,s,a){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=n,e===Gt&&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(n))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!==a&&("object"!==typeof a||!a))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==(null==a?void 0:a.alpha)&&!(a.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==(null==a?void 0:a.alphaByteLength)&&(!Number.isInteger(a.alphaByteLength)||a.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=null!=a?a:{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===Gt}get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("Your browser does not support EncodedVideoChunk.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("Your browser does not support EncodedAudioChunk.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){var i;if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const r=new Uint8Array(e.byteLength);return e.copyTo(r),new Yt(r,e.type,e.timestamp/1e6,(null!=(i=e.duration)?i:0)/1e6,void 0,void 0,t)}clone(e){var t,i,r,n,s,a;if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==(null==e?void 0:e.data)&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==(null==e?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!==(null==e?void 0:e.timestamp)&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==(null==e?void 0:e.duration)&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==(null==e?void 0:e.sequenceNumber)&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==(null==e?void 0:e.sideData)&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new Yt(null!=(t=null==e?void 0:e.data)?t:this.data,null!=(i=null==e?void 0:e.type)?i:this.type,null!=(r=null==e?void 0:e.timestamp)?r:this.timestamp,null!=(n=null==e?void 0:e.duration)?n:this.duration,null!=(s=null==e?void 0:e.sequenceNumber)?s:this.sequenceNumber,this.byteLength,null!=(a=null==e?void 0:e.sideData)?a:this.sideData)}}const Jt=e=>{const t=P(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=N(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(N(e.subarray(i,i+16))),i+=16}}const a=t.getUint32(i);return i+=4,{systemId:n,keyIds:s,data:e.slice(i,i+a)}},Zt=(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),ei=e=>{let t=Ra(e);const i=Wa(e,4);let r=8;1===t&&(t=Oa(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},ti=e=>Ma(e)/65536,ii=e=>Ma(e)/1073741824,ri=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=Ca(e);if(t|=127&i,0===(128&i))break}return t},ni=e=>{let t=Ea(e);return e.skip(2),t=Math.min(t,e.remainingLength),I.decode(xa(e,t))},si=e=>{const t=ei(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Ra(e);e.skip(4);const r=xa(e,t.contentSize-8);switch(i){case 1:return I.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}},ai=16,oi=new Uint32Array(256),li=new Uint32Array(256),ci=new Uint32Array(256),ui=new Uint32Array(256),di=new Uint32Array(256),hi=new Uint32Array(256),fi=new Uint32Array(10);let mi=!1;class pi{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(ai/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(ai),this.out=new Uint8Array(ai),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){y(16===e.byteLength),y(16===t.byteLength),mi||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,a=1;s<256;s++)i[s]=a,t[a]=s,a=a^a<<1^(128&a?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 n=r^r<<1^r<<2^r<<3^r<<4;n=n>>>8^255&n^99,e[s]=n}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);oi[s]=t<<24|t<<16|t<<8|t,hi[s]=i<<24|i<<16|i<<8|i;const n=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);li[s]=n,ci[s]=n>>>8|n<<24,ui[s]=n>>>16|n<<16,di[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)fi[s]=n<<24,n=n<<1^(128&n?283:0);mi=!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 n=4;n<44;n+=4){const e=this.roundkey[n-1];this.roundkey[n]=this.roundkey[n-4]^4278190080&oi[e>>>16&255]^16711680&oi[e>>>8&255]^65280&oi[e>>>0&255]^255&oi[e>>>24&255]^fi[n/4-1],this.roundkey[n+1]=this.roundkey[n-3]^this.roundkey[n],this.roundkey[n+2]=this.roundkey[n-2]^this.roundkey[n+1],this.roundkey[n+3]=this.roundkey[n-1]^this.roundkey[n+2]}for(let n=0,s=40;n<s;n+=4,s-=4)for(let e=0;e<4;e++){const t=this.roundkey[n+e];this.roundkey[n+e]=this.roundkey[s+e],this.roundkey[s+e]=t}for(let n=4;n<40;n+=4)for(let e=0;e<4;e++){const t=this.roundkey[n+e];this.roundkey[n+e]=li[255&oi[t>>>24&255]]^ci[255&oi[t>>>16&255]]^ui[255&oi[t>>>8&255]]^di[255&oi[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 n=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),a=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let l,c,u,d;for(let g=1;g<10;g++){const n=4*g;l=li[e>>>24]^ci[r>>>16&255]^ui[i>>>8&255]^di[255&t]^this.roundkey[n],c=li[t>>>24]^ci[e>>>16&255]^ui[r>>>8&255]^di[255&i]^this.roundkey[n+1],u=li[i>>>24]^ci[t>>>16&255]^ui[e>>>8&255]^di[255&r]^this.roundkey[n+2],d=li[r>>>24]^ci[i>>>16&255]^ui[t>>>8&255]^di[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&hi[e>>>24&255]^16711680&hi[r>>>16&255]^65280&hi[i>>>8&255]^255&hi[t>>>0&255]^this.roundkey[40],f=4278190080&hi[t>>>24&255]^16711680&hi[e>>>16&255]^65280&hi[r>>>8&255]^255&hi[i>>>0&255]^this.roundkey[41],m=4278190080&hi[i>>>24&255]^16711680&hi[t>>>16&255]^65280&hi[e>>>8&255]^255&hi[r>>>0&255]^this.roundkey[42],p=4278190080&hi[r>>>24&255]^16711680&hi[i>>>16&255]^65280&hi[t>>>8&255]^255&hi[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]=n,this.iv[1]=s,this.iv[2]=a,this.iv[3]=o}}class gi extends Qt{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}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t: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=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)}),hasAudio:this.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)}),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0,t=!1;for(;;){let i=this.reader.requestSliceRange(e,8,16);if(i instanceof Promise&&(i=yield i),!i)break;const r=e,n=ei(i);if(!n)break;if("ftyp"===n.name||"styp"===n.name){const e=Wa(i,4);this.isQuickTime="qt "===e}else{if("moov"===n.name){let e=this.reader.requestSlice(i.filePos,n.contentSize);if(e instanceof Promise&&(e=yield 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>r+n.totalSize;break}if("moof"===n.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.');const e=yield this.input._initInput._getDemuxer();if(e.constructor!==gi)throw new Error("Init input must match the input's format.");yield e.readMetadata(),this.movieTimescale=e.movieTimescale,this.movieDurationInTimescale=e.movieDurationInTimescale,this.metadataTags=e.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=e.fragmentTrackDefaults,this.psshBoxes=e.psshBoxes;for(const t of e.tracks){const e={id:t.id,demuxer:this,trackBacking:null,disposition:t.disposition,timescale:t.timescale,durationInMediaTimescale:t.durationInMediaTimescale,durationInMovieTimescale:t.durationInMovieTimescale,rotation:t.rotation,internalCodecId:t.internalCodecId,name:t.name,languageCode:t.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:t.editListPreviousSegmentDurations,editListOffset:t.editListOffset,encryptionInfo:t.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:t.info};if(t.trackBacking)if(y(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new yi(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new bi(t),this.tracks.push(e)}}t=!1;break}}e=r+n.totalSize}if(t){y(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);e instanceof Promise&&(e=yield e),y(e);const t=Ra(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(e instanceof Promise&&(e=yield e),e){const t=ei(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);i instanceof Promise&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}getSampleTableForTrack(e){var t,i;if(e.sampleTable)return e.sampleTable;const r={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=r,null===e.sampleTableByteOffset)return r;y(this.moovSlice);const n=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(n),this.currentTrack=null;if("audio"===(null==(t=e.info)?void 0:t.type)&&e.info.codec&&De.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){y("audio"===(null==(i=e.info)?void 0:i.type));const t=He(e.info.codec),n=[],s=[];for(let i=0;i<r.sampleToChunk.length;i++){const a=r.sampleToChunk[i],o=r.sampleToChunk[i+1],l=(o?o.startChunkIndex:r.chunkOffsets.length)-a.startChunkIndex;for(let i=0;i<l;i++){const o=a.startSampleIndex+i*a.samplesPerChunk,l=o+a.samplesPerChunk,c=z(r.sampleTimingEntries,o,e=>e.startIndex),u=r.sampleTimingEntries[c],d=z(r.sampleTimingEntries,l,e=>e.startIndex),h=r.sampleTimingEntries[d],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=h.startDecodeTimestamp+(l-h.startIndex)*h.delta-f,p=T(n);p&&p.delta===m?p.count++:n.push({startIndex:a.startChunkIndex+i,startDecodeTimestamp:f,count:1,delta:m});const g=a.samplesPerChunk*t.sampleSize*e.info.numberOfChannels;s.push(g)}a.startSampleIndex=a.startChunkIndex,a.samplesPerChunk=1}r.sampleTimingEntries=n,r.sampleSizes=s}if(r.sampleCompositionTimeOffsets.length>0){r.presentationTimestamps=[];for(const e of r.sampleTimingEntries)for(let t=0;t<e.count;t++)r.presentationTimestamps.push({presentationTimestamp:e.startDecodeTimestamp+t*e.delta,sampleIndex:e.startIndex+t});for(const e of r.sampleCompositionTimeOffsets)for(let t=0;t<e.count;t++){const i=e.startIndex+t,n=r.presentationTimestamps[i];n&&(n.presentationTimestamp+=e.offset)}r.presentationTimestamps.sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;e<r.presentationTimestamps.length;e++)r.presentationTimestampIndexMap[r.presentationTimestamps[e].sampleIndex]=e}return r}readFragment(e){return d(this,null,function*(){var t;if((null==(t=this.lastReadFragment)?void 0:t.moofOffset)===e)return this.lastReadFragment;let i=this.reader.requestSliceRange(e,8,16);i instanceof Promise&&(i=yield i),y(i);const r=ei(i);y("moof"===(null==r?void 0:r.name));let n=this.reader.requestSlice(e,r.totalSize);n instanceof Promise&&(n=yield n),y(n),this.traverseBox(n);const s=this.lastReadFragment;y(s&&s.moofOffset===e);for(const[,e]of s.trackData){const t=e.track,{fragmentPositionCache:i}=t;if(!e.startTimestampIsFinal){const r=t.fragmentLookupTable.find(e=>e.moofOffset===s.moofOffset);if(r)Pi(e,r.timestamp);else{const t=z(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];Pi(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=z(i,e.startTimestamp,e=>e.startTimestamp);if(-1!==r&&i[r].moofOffset===s.moofOffset||i.splice(r+1,0,{moofOffset:s.moofOffset,startTimestamp:e.startTimestamp,endTimestamp:e.endTimestamp}),e.encryptionAuxInfo&&t.encryptionInfo){const i=yield Bi(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t<Math.min(e.samples.length,i.length);t++){const r=i[t];e.samples[t].encryption=r}}}return s})}readContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){if(!this.traverseBox(e))break}}*iterateContiguousBoxes(e){const t=e.filePos;for(;e.filePos-t<=e.length-8;){const t=e.filePos,i=ei(e);if(!i)break;yield{boxInfo:i,slice:e},e.filePos=t+i.totalSize}}traverseBox(e){var t,i,r,n,s,a,o,l,d,h,f,m,p,g,k,S,v,w,x,C,E,A,R,D,M,O,L,z,U,q,W,V,H,K,j,X,$,G,Y,J,Z,te,ie,re,ne,se,ae,oe,le;const ce=e.filePos,ue=ei(e);if(!ue)return!1;const de=e.filePos,he=ce+ue.totalSize;switch(ue.name){case"mdia":case"minf":case"dinf":case"mfra":case"edts":case"sinf":case"schi":case"wave":this.readContiguousBoxes(e.slice(de,ue.contentSize));break;case"mvhd":{const t=Ca(e);e.skip(3),1===t?(e.skip(16),this.movieTimescale=Ra(e),this.movieDurationInTimescale=Oa(e)):(e.skip(8),this.movieTimescale=Ra(e),this.movieDurationInTimescale=Ra(e))}break;case"trak":{const t={id:-1,demuxer:this,trackBacking:null,disposition:u(c({},Be),{primary:!1}),info:null,timescale:-1,durationInMovieTimescale:-1,durationInMediaTimescale:-1,rotation:0,internalCodecId:null,name:null,languageCode:Q,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(de,ue.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 yi(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new bi(e),this.tracks.push(t)}this.currentTrack=null}break;case"tkhd":{const t=this.currentTrack;if(!t)break;const i=Ca(e),r=!!(1&_a(e));if(t.disposition.default=r,0===i)e.skip(8),t.id=Ra(e),e.skip(4),t.durationInMovieTimescale=Ra(e);else{if(1!==i)throw new Error(`Incorrect track header version ${i}.`);e.skip(16),t.id=Ra(e),e.skip(4),t.durationInMovieTimescale=Oa(e)}e.skip(16);const n=[ti(e),ti(e),ii(e),ti(e),ti(e),ii(e),ti(e),ti(e),ii(e)],s=b((fe=Ii(n),me=90,Math.round(fe/me)*me));y(0===s||90===s||180===s||270===s),t.rotation=s}break;case"elst":{const t=this.currentTrack;if(!t)break;const i=Ca(e);e.skip(3);let r=!1,n=0;const s=Ra(e);for(let a=0;a<s;a++){const s=1===i?Oa(e):Ra(e),a=1===i?La(e):Ma(e),o=ti(e);if(0!==s){if(r){console.warn("Unsupported edit list: multiple edits are not currently supported. Only using first edit.");break}if(-1!==a){if(1!==o){console.warn("Unsupported edit list entry: media rate must be 1.");break}t.editListPreviousSegmentDurations=n,t.editListOffset=a,r=!0}else n+=s}}}break;case"mdhd":{const t=this.currentTrack;if(!t)break;const i=Ca(e);e.skip(3),0===i?(e.skip(8),t.timescale=Ra(e),t.durationInMediaTimescale=Ra(e)):1===i&&(e.skip(16),t.timescale=Ra(e),t.durationInMediaTimescale=Oa(e));let r=Ea(e);if(r>0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;ee(t.languageCode)||(t.languageCode=Q)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Wa(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:null,avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=ce,this.readContiguousBoxes(e.slice(de,ue.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=Ca(e);e.skip(3);const r=Ra(e);for(let n=0;n<r;n++){const r=e.filePos,n=ei(e);if(!n)break;t.internalCodecId=n.name;const s=n.name.toLowerCase();if("video"===t.info.type){e.skip(24),t.info.width=Ea(e),t.info.height=Ea(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+n.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":null===i?console.warn("Unknown encrypted video codec due to missing frma box."):console.warn(`Unsupported video codec (sample entry type '${n.name}').`)}else{e.skip(8);const a=Ea(e);e.skip(6);let o=Ea(e),l=Ea(e);e.skip(4);let c=Ra(e)/65536,u=null;0===i&&a>0&&(1===a?(e.skip(4),l=8*Ra(e),e.skip(8)):2===a&&(e.skip(4),c=qa(e),o=Ra(e),e.skip(4),l=Ra(e),u=Ra(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=c,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+n.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=We;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("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(console.warn(`Unsupported sample size ${l} for codec 'twos'.`),t.info.codec=null);else if("sowt"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec="pcm-s16":(console.warn(`Unsupported sample size ${l} for codec 'sowt'.`),t.info.codec=null);else if("raw "===d)t.info.codec="pcm-u8";else if("in24"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===d)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===d){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":(console.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":(console.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":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(console.warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===d&&null!==u){const e=l+7>>3,i=Boolean(1&u),r=Boolean(2&u),n=4&u?-1:0;l>0&&l<=64&&(i?32===l&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):n&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&&console.warn("Unsupported PCM format.")}else null===d?console.warn("Unknown encrypted audio codec due to missing frma box."):console.warn(`Unsupported audio codec (sample entry type '${n.name}').`)}e.filePos=r+n.totalSize}}break;case"frma":{const t=this.currentTrack;if(!t)break;const i=Wa(e,4).toLowerCase();t.frmaCodecString=i}break;case"schm":{const t=this.currentTrack;if(!t)break;e.skip(4);const i=Wa(e,4);"cenc"===i||"cens"===i||"cbcs"===i?t.encryptionInfo={scheme:i,defaultKid:null,defaultIsProtected:null,defaultPerSampleIvSize:null,defaultConstantIv:null,defaultCryptByteBlock:null,defaultSkipByteBlock:null}:console.warn(`Unsupported encryption scheme '${i}'.`)}break;case"tenc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Ca(e);e.skip(3),e.skip(1);const r=Ca(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!==Ca(e),t.encryptionInfo.defaultPerSampleIvSize=Ca(e),t.encryptionInfo.defaultKid=N(xa(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=Ca(e),r=new Uint8Array(16);r.set(xa(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;y(t.info),t.info.codecDescription=xa(e,ue.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;y(t.info),t.info.codecDescription=xa(e,ue.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;y("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=Ca(e),n=Ca(e),s=Ca(e),a=s>>4,o=s>>1&7,l=1&s,c=Ca(e),u=Ca(e),d=Ca(e);i.info.vp9CodecInfo={profile:r,level:n,bitDepth:a,chromaSubsampling:o,videoFullRangeFlag:l,colourPrimaries:c,transferCharacteristics:u,matrixCoefficients:d}}break;case"av1C":{const t=this.currentTrack;if(!t)break;y("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const r=Ca(e),n=r>>5,s=31&r,a=Ca(e),o=a>>7,l=a>>6&1,c=a>>4&1,u=a>>3&1,d=a>>2&1,h=3&a,f=2===n&&l?a>>5&1?12:10:l?10:8;t.info.av1CodecInfo={profile:n,level:s,tier:o,bitDepth:f,monochrome:c,chromaSubsamplingX:u,chromaSubsamplingY:d,chromaSamplePosition:h}}break;case"colr":{const t=this.currentTrack;if(!t)break;y("video"===(null==(r=t.info)?void 0:r.type));if("nclx"!==Wa(e,4))break;const i=Ea(e),n=Ea(e),s=Ea(e),a=Boolean(128&Ca(e));t.info.colorSpace={primaries:B[i],transfer:_[n],matrix:F[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;y("video"===(null==(n=t.info)?void 0:n.type));const i=Ra(e),r=Ra(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)break;y("audio"===(null==(s=t.info)?void 0:s.type)),e.skip(4);y(3===Ca(e)),ri(e),e.skip(2);const i=Ca(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=Ca(e);e.skip(t)}n&&e.skip(2);y(4===Ca(e));const a=ri(e),o=e.filePos,l=Ca(e);if(64===l||103===l?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===l,objectType:null}):105===l||107===l?t.info.codec="mp3":221===l?t.info.codec="vorbis":console.warn(`Unsupported audio codec (objectTypeIndication ${l}) - discarding track.`),e.skip(12),a>e.filePos-o){y(5===Ca(e));const i=ri(e);if(t.info.codecDescription=xa(e,i),"aac"===t.info.codec){const e=Fe(t.info.codecDescription);null!==e.numberOfChannels&&(t.info.numberOfChannels=e.numberOfChannels),null!==e.sampleRate&&(t.info.sampleRate=e.sampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(a=t.info)?void 0:a.type)),t.info.pcmLittleEndian=!!(255&Ea(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(o=t.info)?void 0:o.type)),e.skip(4);const i=Ca(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=Ca(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(l=t.info)?void 0:l.type)),e.skip(1);const i=Ca(e),r=Ea(e),n=Ra(e),s=Aa(e),a=Ca(e);let o;o=0!==a?xa(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),u=new DataView(c.buffer);u.setUint32(0,1332770163,!1),u.setUint32(4,1214603620,!1),u.setUint8(8,1),u.setUint8(9,i),u.setUint16(10,r,!0),u.setUint32(12,n,!0),u.setInt16(16,s,!0),u.setUint8(18,a),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=127,r=128,n=e.filePos;for(;e.filePos<he;){const n=Ca(e),s=_a(e);if((n&i)===zt.STREAMINFO){e.skip(10);const i=Ra(e),r=i>>>12,n=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=n,e.skip(20)}else e.skip(s);if(n&r)break}const s=e.filePos;e.filePos=n;const a=xa(e,s-n),o=new Uint8Array(4+a.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(a,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(h=t.info)?void 0:h.type));const i=xa(e,3),r=new Ee(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=tt[n]),t.info.numberOfChannels=Wt[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;y("audio"===(null==(f=t.info)?void 0:f.type));const i=(e=>{if(e.length<2)return null;const t=new Ee(e),i=t.readBits(13),r=t.readBits(3),n=[];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),a=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let l=0;o>0?l=t.readBits(9):t.skipBits(1),n.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:a,numDepSub:o,chanLoc:l})}return 0===n.length?null:{dataRate:i,substreams:n}})(xa(e,ue.contentSize));if(!i){console.warn("Invalid dec3 box contents, ignoring.");break}const r=Xt(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=$t(i)}break;case"stts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=Ra(e);let r=0,n=0;for(let s=0;s<i;s++){const i=Ra(e),s=Ra(e);t.sampleTable.sampleTimingEntries.push({startIndex:r,startDecodeTimestamp:n,count:i,delta:s}),r+=i,n+=i*s}}break;case"ctts":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=Ra(e);let r=0;for(let n=0;n<i;n++){const i=Ra(e),n=Ma(e);t.sampleTable.sampleCompositionTimeOffsets.push({startIndex:r,count:i,offset:n}),r+=i}}break;case"stsz":{const t=this.currentTrack;if(!t)break;if(!t.sampleTable)break;e.skip(4);const i=Ra(e),r=Ra(e);if(0===i)for(let n=0;n<r;n++){const i=Ra(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=Ca(e),r=Ra(e),n=xa(e,Math.ceil(r*i/8)),s=new Ee(n);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=Ra(e);for(let r=0;r<i;r++){const i=Ra(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=Ra(e);for(let n=0;n<i;n++){const i=Ra(e)-1,r=Ra(e),n=Ra(e);t.sampleTable.sampleToChunk.push({startSampleIndex:-1,startChunkIndex:i,samplesPerChunk:r,sampleDescriptionIndex:n})}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=Ra(e);for(let r=0;r<i;r++){const i=Ra(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=Ra(e);for(let r=0;r<i;r++){const i=Oa(e);t.sampleTable.chunkOffsets.push(i)}}break;case"mvex":this.isFragmented=!0,this.readContiguousBoxes(e.slice(de,ue.contentSize));break;case"mehd":{const t=Ca(e);e.skip(3);const i=1===t?Oa(e):Ra(e);this.movieDurationInTimescale=i}break;case"trex":{e.skip(4);const t=Ra(e),i=Ra(e),r=Ra(e),n=Ra(e),s=Ra(e);this.fragmentTrackDefaults.push({trackId:t,defaultSampleDescriptionIndex:i,defaultSampleDuration:r,defaultSampleSize:n,defaultSampleFlags:s})}break;case"tfra":{const t=Ca(e);e.skip(3);const i=Ra(e),r=this.tracks.find(e=>e.id===i);if(!r)break;const n=Ra(e),s=(12&n)>>2,a=3&n,o=[Ca,Ea,_a,Ra],l=o[(48&n)>>4],c=o[s],u=o[a],d=Ra(e);for(let h=0;h<d;h++){const i=1===t?Oa(e):Ra(e),n=1===t?Oa(e):Ra(e);l(e),c(e),u(e),r.fragmentLookupTable.push({timestamp:i,moofOffset:n})}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:ce,moofSize:ue.totalSize,implicitBaseDataOffset:ce,trackData:new Map,psshBoxes:[]},this.readContiguousBoxes(e.slice(de,ue.contentSize)),this.lastReadFragment=this.currentFragment,this.currentFragment=null;break;case"traf":if(y(this.currentFragment),this.readContiguousBoxes(e.slice(de,ue.contentSize)),this.currentTrack){const e=this.currentFragment.trackData.get(this.currentTrack.id);if(e){this.currentFragment.implicitBaseDataOffset=e.currentOffset,e.presentationTimestamps=e.samples.map((e,t)=>({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let n=0;n<e.presentationTimestamps.length;n++){const t=e.presentationTimestamps[n],i=e.samples[t.sampleIndex];if(null===e.firstKeyFrameTimestamp&&i.isKeyFrame&&(e.firstKeyFrameTimestamp=i.presentationTimestamp),n<e.presentationTimestamps.length-1){const r=e.presentationTimestamps[n+1].presentationTimestamp-t.presentationTimestamp;i.duration=r}}const t=e.samples[e.presentationTimestamps[0].sampleIndex],i=e.samples[T(e.presentationTimestamps).sampleIndex];e.startTimestamp=t.presentationTimestamp,e.endTimestamp=i.presentationTimestamp+i.duration;const{currentFragmentState:r}=this.currentTrack;y(r),null!==r.startTimestamp&&(Pi(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(null==(m=this.input._formatOptions.isobmff)?void 0:m._suppressPsshParsing)break;const t=Jt(xa(e,ue.contentSize));this.currentFragment?this.currentFragment.psshBoxes.push(t):this.currentTrack||this.psshBoxes.push(t)}break;case"tfhd":{y(this.currentFragment),e.skip(1);const t=_a(e),i=Boolean(1&t),r=Boolean(2&t),n=Boolean(8&t),s=Boolean(16&t),a=Boolean(32&t),o=Boolean(65536&t),l=Boolean(131072&t),c=Ra(e),u=this.tracks.find(e=>e.id===c);if(!u)break;const d=this.fragmentTrackDefaults.find(e=>e.trackId===c);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:null!=(p=null==d?void 0:d.defaultSampleDescriptionIndex)?p:null,defaultSampleDuration:null!=(g=null==d?void 0:d.defaultSampleDuration)?g:null,defaultSampleSize:null!=(k=null==d?void 0:d.defaultSampleSize)?k:null,defaultSampleFlags:null!=(S=null==d?void 0:d.defaultSampleFlags)?S:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Oa(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Ra(e)),n&&(u.currentFragmentState.defaultSampleDuration=Ra(e)),s&&(u.currentFragmentState.defaultSampleSize=Ra(e)),a&&(u.currentFragmentState.defaultSampleFlags=Ra(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;y(t.currentFragmentState);const i=Ca(e);e.skip(3);const r=0===i?Ra(e):Oa(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;y(this.currentFragment),y(t.currentFragmentState);const i=Ca(e),r=_a(e),n=Boolean(1&r),s=Boolean(4&r),a=Boolean(256&r),o=Boolean(512&r),l=Boolean(1024&r),c=Boolean(2048&r),u=Ra(e);let d=null;n&&(d=Ma(e));let h,f=null;if(s&&(f=Ra(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+(null!=d?d:0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,h)),0===u){this.currentFragment.implicitBaseDataOffset=h.currentOffset;break}for(let m=0;m<u;m++){let r,n,s;a?r=Ra(e):(y(null!==t.currentFragmentState.defaultSampleDuration),r=t.currentFragmentState.defaultSampleDuration),o?n=Ra(e):(y(null!==t.currentFragmentState.defaultSampleSize),n=t.currentFragmentState.defaultSampleSize),l?s=Ra(e):(y(null!==t.currentFragmentState.defaultSampleFlags),s=t.currentFragmentState.defaultSampleFlags),0===m&&null!==f&&(s=f);let u=0;c&&(u=0===i?Ra(e):Ma(e));const d=!(65536&s);h.samples.push({presentationTimestamp:h.currentTimestamp+u,duration:r,byteOffset:h.currentOffset,byteSize:n,isKeyFrame:d,encryption:null}),h.currentOffset+=n,h.currentTimestamp+=r}}break;case"saiz":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;e.skip(1);if(1&_a(e)){const i=Wa(e,4),r=Ra(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const i=Ca(e),r=Ra(e);let n=null;0===i&&r>0&&(n=xa(e,r));const s=Ci(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=Ca(e);if(1&_a(e)){const i=Wa(e,4),r=Ra(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Ra(e);if(0===r)break;r>1&&console.warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Ra(e):Number(Oa(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);Ci(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;y(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=_a(e),n=Boolean(2&r),s=Ra(e),a=t.encryptionInfo.defaultPerSampleIvSize;y(null!==a);for(let o=0;o<Math.min(s,i.samples.length);o++){const r=new Uint8Array(16);a>0?r.set(xa(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Ea(e);s=[];for(let i=0;i<t;i++){const t=Ea(e),i=Ra(e);s.push({clearLen:t,protectedLen:i})}}i.samples[o].encryption={iv:r,subsamples:s}}}break;case"udta":{const t=this.iterateContiguousBoxes(e.slice(de,ue.contentSize));for(const{boxInfo:e,slice:i}of t){if("meta"!==e.name&&!this.currentTrack){const t=i.filePos;null!=(v=this.metadataTags).raw||(v.raw={}),"\xa9"===e.name[0]?null!=(w=this.metadataTags.raw)[x=e.name]||(w[x]=ni(i)):null!=(C=this.metadataTags.raw)[E=e.name]||(C[E]=xa(i,e.contentSize)),i.filePos=t}switch(e.name){case"meta":i.skip(-e.headerSize),this.traverseBox(i);break;case"\xa9nam":case"name":this.currentTrack?this.currentTrack.name=I.decode(xa(i,e.contentSize)):null!=(A=this.metadataTags).title||(A.title=ni(i));break;case"\xa9des":this.currentTrack||null!=(R=this.metadataTags).description||(R.description=ni(i));break;case"\xa9ART":this.currentTrack||null!=(D=this.metadataTags).artist||(D.artist=ni(i));break;case"\xa9alb":this.currentTrack||null!=(M=this.metadataTags).album||(M.album=ni(i));break;case"albr":this.currentTrack||null!=(O=this.metadataTags).albumArtist||(O.albumArtist=ni(i));break;case"\xa9gen":this.currentTrack||null!=(L=this.metadataTags).genre||(L.genre=ni(i));break;case"\xa9day":if(!this.currentTrack){const e=new Date(ni(i));Number.isNaN(e.getTime())||null!=(z=this.metadataTags).date||(z.date=e)}break;case"\xa9cmt":this.currentTrack||null!=(U=this.metadataTags).comment||(U.comment=ni(i));break;case"\xa9lyr":this.currentTrack||null!=(q=this.metadataTags).lyrics||(q.lyrics=ni(i))}}}break;case"meta":{if(this.currentTrack)break;const t=0!==Ra(e);this.currentMetadataKeys=new Map,t?this.readContiguousBoxes(e.slice(de,ue.contentSize)):this.readContiguousBoxes(e.slice(de+4,ue.contentSize-4)),this.currentMetadataKeys=null}break;case"keys":{if(!this.currentMetadataKeys)break;e.skip(4);const t=Ra(e);for(let i=0;i<t;i++){const t=Ra(e);e.skip(4);const r=I.decode(xa(e,t-8));this.currentMetadataKeys.set(i+1,r)}}break;case"ilst":{if(!this.currentMetadataKeys)break;const t=this.iterateContiguousBoxes(e.slice(de,ue.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 n=si(i);switch(null!=(W=this.metadataTags).raw||(W.raw={}),null!=(V=this.metadataTags.raw)[t]||(V[t]=n),t){case"\xa9nam":case"titl":case"com.apple.quicktime.title":case"title":"string"===typeof n&&(null!=(H=this.metadataTags).title||(H.title=n));break;case"\xa9des":case"desc":case"dscp":case"com.apple.quicktime.description":case"description":"string"===typeof n&&(null!=(K=this.metadataTags).description||(K.description=n));break;case"\xa9ART":case"com.apple.quicktime.artist":case"artist":"string"===typeof n&&(null!=(j=this.metadataTags).artist||(j.artist=n));break;case"\xa9alb":case"albm":case"com.apple.quicktime.album":case"album":"string"===typeof n&&(null!=(X=this.metadataTags).album||(X.album=n));break;case"aART":case"album_artist":"string"===typeof n&&(null!=($=this.metadataTags).albumArtist||($.albumArtist=n));break;case"\xa9cmt":case"com.apple.quicktime.comment":case"comment":"string"===typeof n&&(null!=(G=this.metadataTags).comment||(G.comment=n));break;case"\xa9gen":case"gnre":case"com.apple.quicktime.genre":case"genre":"string"===typeof n&&(null!=(Y=this.metadataTags).genre||(Y.genre=n));break;case"\xa9lyr":case"lyrics":"string"===typeof n&&(null!=(J=this.metadataTags).lyrics||(J.lyrics=n));break;case"\xa9day":case"rldt":case"com.apple.quicktime.creationdate":case"date":if("string"===typeof n){const e=new Date(n);Number.isNaN(e.getTime())||null!=(Z=this.metadataTags).date||(Z.date=e)}break;case"covr":case"com.apple.quicktime.artwork":n instanceof xe?(null!=(te=this.metadataTags).images||(te.images=[]),this.metadataTags.images.push({data:n.data,kind:"coverFront",mimeType:n.mimeType})):n instanceof Uint8Array&&(null!=(ie=this.metadataTags).images||(ie.images=[]),this.metadataTags.images.push({data:n,kind:"coverFront",mimeType:"image/*"}));break;case"track":if("string"===typeof n){const e=n.split("/"),t=Number.parseInt(e[0],10),i=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=(re=this.metadataTags).trackNumber||(re.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(ne=this.metadataTags).tracksTotal||(ne.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=P(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(se=this.metadataTags).trackNumber||(se.trackNumber=t)),i>0&&(null!=(ae=this.metadataTags).tracksTotal||(ae.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=P(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(oe=this.metadataTags).discNumber||(oe.discNumber=t)),i>0&&(null!=(le=this.metadataTags).discsTotal||(le.discsTotal=i))}}}}}var fe,me;return e.filePos=he,!0}}class ki{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}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;y(t.trackBacking);const i=yield t.trackBacking.getFirstPacket({metadataOnly:!0});return(null!=(e=null==i?void 0:i.timestamp)?e:0)+t.durationInMediaTimescale/t.timescale})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){const t=yield 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 G(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return d(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Ti(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return xi(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})}getNextPacket(e,t){return d(this,null,function*(){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)})}getKeyPacket(e,t){return d(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Si(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return xi(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=V(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})}getNextKeyPacket(e,t){return d(this,null,function*(){const i=this.packetToSampleIndex.get(e);if(void 0!==i){const e=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=wi(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 y(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=vi(i,e);if(!r)return null;let n;if(t.metadataOnly)n=Gt;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(t instanceof Promise&&(t=yield t),!t)return null;if(n=xa(t,r.sampleSize),this.internalTrack.encryptionAuxInfo){y(this.internalTrack.encryptionInfo);const t=yield Bi(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);e<t.length&&(n=yield Ei(this.internalTrack,t[e],n,null))}}const s=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=r.duration/this.internalTrack.timescale,o=new Yt(n,r.isKeyFrame?"key":"delta",s,a,e,r.sampleSize);return this.packetToSampleIndex.set(o,e),o})}fetchPacketInFragment(e,t,i){return d(this,null,function*(){if(-1===t)return null;const r=e.trackData.get(this.internalTrack.id).samples[t];let n;if(y(r),i.metadataOnly)n=Gt;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.byteOffset,r.byteSize);if(t instanceof Promise&&(t=yield t),!t)return null;n=xa(t,r.byteSize),r.encryption&&(n=yield Ei(this.internalTrack,r.encryption,n,e))}const s=(r.presentationTimestamp-this.internalTrack.editListOffset)/this.internalTrack.timescale,a=r.duration/this.internalTrack.timescale,o=new Yt(n,r.isKeyFrame?"key":"delta",s,a,e.moofOffset+t,r.byteSize);return this.packetToFragmentLocation.set(o,{fragment:e,sampleIndex:t}),o})}performFragmentedLookup(e,t,i,r,n){return d(this,null,function*(){var s,a,o;const l=this.internalTrack.demuxer;let c=null,u=null,d=-1;if(e){const{sampleIndex:i,correctSampleFound:r}=t(e);if(r)return this.fetchPacketInFragment(e,i,n);-1!==i&&(u=e,d=i)}const h=z(this.internalTrack.fragmentLookupTable,i,e=>e.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=z(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),p=-1!==m?this.internalTrack.fragmentPositionCache[m]:null,g=Math.max(null!=(s=null==f?void 0:f.moofOffset)?s:0,null!=(a=null==p?void 0:p.moofOffset)?a:0)||null;let k;for(e?null===g||e.moofOffset>=g?(k=e.moofOffset+e.moofSize,c=e):k=g:k=null!=g?g:0;;){if(c){const e=c.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=l.reader.requestSliceRange(k,8,16);if(e instanceof Promise&&(e=yield e),!e)break;const i=k,s=ei(e);if(!s)break;if("moof"===s.name){c=yield l.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(c);if(r)return this.fetchPacketInFragment(c,e,n);-1!==e&&(u=c,d=e)}k=i+s.totalSize}if(f&&(!u||u.moofOffset<f.moofOffset)){const e=this.internalTrack.fragmentLookupTable[h-1];y(!e||e.timestamp<f.timestamp);const i=null!=(o=null==e?void 0:e.timestamp)?o:-1/0;return this.performFragmentedLookup(null,t,i,r,n)}return u?this.fetchPacketInFragment(u,d,n):null})}}class yi extends ki{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}getColorSpace(){return d(this,null,function*(){var e,t,i,r;return{primaries:null==(e=this.internalTrack.info.colorSpace)?void 0:e.primaries,transfer:null==(t=this.internalTrack.info.colorSpace)?void 0:t.transfer,matrix:null==(i=this.internalTrack.info.colorSpace)?void 0:i.matrix,fullRange:null==(r=this.internalTrack.info.colorSpace)?void 0:r.fullRange}})}canBeTransparent(){return d(this,null,function*(){return!1})}getDecoderConfig(){return d(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>d(this,null,function*(){var e,t;if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo){if("av1"===this.internalTrack.info.codec&&!this.internalTrack.info.av1CodecInfo){const e=yield this.getFirstPacket({});this.internalTrack.info.av1CodecInfo=e&&Mt(e.data)}}else{const e=yield this.getFirstPacket({});this.internalTrack.info.vp9CodecInfo=e&&Rt(e.data)}const i={codec:Ue(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0,colorSpace:null!=(t=this.internalTrack.info.colorSpace)?t:void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(i.displayAspectWidth=this.internalTrack.info.squarePixelWidth,i.displayAspectHeight=this.internalTrack.info.squarePixelHeight),i}))():null})}}class bi extends ki{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:qe(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}:null})}}const Ti=(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)}},Si=(e,t)=>{var i;if(!e.keySampleIndices)return Ti(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!==L(e.keySampleIndices,i,e=>e))return i}return-1}{const r=Ti(e,t),n=z(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},vi=(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 n=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=z(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndex<a.count&&(n+=a.offset);const o=e.sampleSizes[Math.min(t,e.sampleSizes.length-1)],l=z(e.sampleToChunk,t,e=>e.startSampleIndex),c=e.sampleToChunk[l];y(c);const u=c.startChunkIndex+Math.floor((t-c.startSampleIndex)/c.samplesPerChunk),d=e.chunkOffsets[u],h=c.startSampleIndex+(u-c.startChunkIndex)*c.samplesPerChunk;let f=0,m=d;if(1===e.sampleSizes.length)m+=o*(t-h),f+=o*c.samplesPerChunk;else for(let g=h;g<h+c.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(y(void 0!==i),i<e.presentationTimestamps.length-1){p=e.presentationTimestamps[i+1].presentationTimestamp-n}}return{presentationTimestamp:n,duration:p,sampleOffset:m,sampleSize:o,chunkOffset:d,chunkSize:f,isKeyFrame:!e.keySampleIndices||-1!==L(e.keySampleIndices,t,e=>e)}},wi=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=z(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},Pi=(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},Ii=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},xi=e=>0===e.sampleSizes.length,Ci=e=>{var t,i,r;return e.currentFragmentState?null!=(i=(t=e.currentFragmentState).encryptionAuxInfo)?i:t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}:null!=(r=e.encryptionAuxInfo)?r:e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}},Bi=(e,t,i)=>d(null,null,function*(){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{y(i.sampleSizes);for(let e=0;e<i.sampleCount;e++)r+=i.sampleSizes[e]}let n=e.requestSlice(i.offset,r);if(n instanceof Promise&&(n=yield n),!n)throw new Error("Failed to read auxiliary encryption info.");const s=t.defaultPerSampleIvSize;y(null!==s);const a=[];for(let e=0;e<i.sampleCount;e++){const r=i.defaultSampleInfoSize>0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(xa(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Ea(n);l=[];for(let t=0;t<e;t++){const e=Ea(n),t=Ra(n);l.push({clearLen:e,protectedLen:t})}}a.push({iv:o,subsamples:l})}return i.resolved=a,a}),Ei=(e,t,i,r)=>d(null,null,function*(){var n;y(e.encryptionInfo);const s=e.encryptionInfo;y(null!==s.defaultKid);const a=s.defaultKid;let o;const l=e.demuxer.decryptionKeyCache.get(a);if(l)o=yield l;else{if(!(null==(n=e.demuxer.input._formatOptions.isobmff)?void 0:n.resolveKeyId))throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=d(null,null,function*(){let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(a));for(let e=0;e<t.length-1;e++)for(let i=e+1;i<t.length;i++)Zt(t[e],t[i])&&(t.splice(i,1),i--)}const i=yield e.demuxer.input._formatOptions.isobmff.resolveKeyId({keyId:a,psshBoxes:t});if(!("string"===typeof i&&32===i.length&&M.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=>{y(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(a,t),o=yield t}return"cenc"===s.scheme||"cens"===s.scheme?_i(o,s,t,i):Ai(o,s,t,i)}),_i=(e,t,i,r)=>d(null,null,function*(){const n=new Uint8Array(16);n.set(i.iv,0);const s=yield crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),a=e=>d(null,null,function*(){const t=yield crypto.subtle.decrypt({name:"AES-CTR",counter:n,length:64},s,e);return new Uint8Array(t)});if(!i.subsamples)return a(r);y(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Fi(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let l=0;for(const e of o)for(const t of e.perSubsample)l+=t.length;const c=new Uint8Array(l);let u=0;for(const e of o)for(const t of e.perSubsample)c.set(r.subarray(t.offset,t.offset+t.length),u),u+=t.length;const h=yield a(c),f=new Uint8Array(r);let m=0;for(const e of o)for(const t of e.perSubsample)f.set(h.subarray(m,m+t.length),t.offset),m+=t.length;return f}),Ai=(e,t,i,r)=>{const n=new pi;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(y(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i<t;i++){const t=16*i;n.in.set(r.subarray(t,t+16)),n.decrypt(),e.set(n.out,t)}return e}if(0===s&&0===a)throw new Error("cbcs with subsamples requires pattern encryption.");const o=new Uint8Array(r),l=Fi(i.subsamples,s,a),c=new DataView(i.iv.buffer,i.iv.byteOffset,16);for(const u of l){n.iv[0]=c.getUint32(0,!1),n.iv[1]=c.getUint32(4,!1),n.iv[2]=c.getUint32(8,!1),n.iv[3]=c.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;n.in.set(r.subarray(t,t+16)),n.decrypt(),o.set(n.out,t)}}}return o},Fi=(e,t,i)=>{const r=[],n=0!==t||0!==i;let s=0;for(const a of e){s+=a.clearLen;const e=[];if(n){let r=a.protectedLen,n=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:n,length:s}),n+=s,r-=s;const a=Math.min(16*i,r);n+=a,r-=a}s+=a.protectedLen}else a.protectedLen>0&&e.push({offset:s,length:a.protectedLen}),s+=a.protectedLen;r.push({perSubsample:e})}return r};var Ri,Di;(Di=Ri||(Ri={}))[Di.EBML=440786851]="EBML",Di[Di.EBMLVersion=17030]="EBMLVersion",Di[Di.EBMLReadVersion=17143]="EBMLReadVersion",Di[Di.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Di[Di.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Di[Di.DocType=17026]="DocType",Di[Di.DocTypeVersion=17031]="DocTypeVersion",Di[Di.DocTypeReadVersion=17029]="DocTypeReadVersion",Di[Di.Void=236]="Void",Di[Di.Segment=408125543]="Segment",Di[Di.SeekHead=290298740]="SeekHead",Di[Di.Seek=19899]="Seek",Di[Di.SeekID=21419]="SeekID",Di[Di.SeekPosition=21420]="SeekPosition",Di[Di.Duration=17545]="Duration",Di[Di.Info=357149030]="Info",Di[Di.TimestampScale=2807729]="TimestampScale",Di[Di.MuxingApp=19840]="MuxingApp",Di[Di.WritingApp=22337]="WritingApp",Di[Di.Tracks=374648427]="Tracks",Di[Di.TrackEntry=174]="TrackEntry",Di[Di.TrackNumber=215]="TrackNumber",Di[Di.TrackUID=29637]="TrackUID",Di[Di.TrackType=131]="TrackType",Di[Di.FlagEnabled=185]="FlagEnabled",Di[Di.FlagDefault=136]="FlagDefault",Di[Di.FlagForced=21930]="FlagForced",Di[Di.FlagOriginal=21934]="FlagOriginal",Di[Di.FlagHearingImpaired=21931]="FlagHearingImpaired",Di[Di.FlagVisualImpaired=21932]="FlagVisualImpaired",Di[Di.FlagCommentary=21935]="FlagCommentary",Di[Di.FlagLacing=156]="FlagLacing",Di[Di.Name=21358]="Name",Di[Di.Language=2274716]="Language",Di[Di.LanguageBCP47=2274717]="LanguageBCP47",Di[Di.CodecID=134]="CodecID",Di[Di.CodecPrivate=25506]="CodecPrivate",Di[Di.CodecDelay=22186]="CodecDelay",Di[Di.SeekPreRoll=22203]="SeekPreRoll",Di[Di.DefaultDuration=2352003]="DefaultDuration",Di[Di.Video=224]="Video",Di[Di.PixelWidth=176]="PixelWidth",Di[Di.PixelHeight=186]="PixelHeight",Di[Di.DisplayWidth=21680]="DisplayWidth",Di[Di.DisplayHeight=21690]="DisplayHeight",Di[Di.DisplayUnit=21682]="DisplayUnit",Di[Di.AlphaMode=21440]="AlphaMode",Di[Di.Audio=225]="Audio",Di[Di.SamplingFrequency=181]="SamplingFrequency",Di[Di.Channels=159]="Channels",Di[Di.BitDepth=25188]="BitDepth",Di[Di.SimpleBlock=163]="SimpleBlock",Di[Di.BlockGroup=160]="BlockGroup",Di[Di.Block=161]="Block",Di[Di.BlockAdditions=30113]="BlockAdditions",Di[Di.BlockMore=166]="BlockMore",Di[Di.BlockAdditional=165]="BlockAdditional",Di[Di.BlockAddID=238]="BlockAddID",Di[Di.BlockDuration=155]="BlockDuration",Di[Di.ReferenceBlock=251]="ReferenceBlock",Di[Di.Cluster=524531317]="Cluster",Di[Di.Timestamp=231]="Timestamp",Di[Di.Cues=475249515]="Cues",Di[Di.CuePoint=187]="CuePoint",Di[Di.CueTime=179]="CueTime",Di[Di.CueTrackPositions=183]="CueTrackPositions",Di[Di.CueTrack=247]="CueTrack",Di[Di.CueClusterPosition=241]="CueClusterPosition",Di[Di.Colour=21936]="Colour",Di[Di.MatrixCoefficients=21937]="MatrixCoefficients",Di[Di.TransferCharacteristics=21946]="TransferCharacteristics",Di[Di.Primaries=21947]="Primaries",Di[Di.Range=21945]="Range",Di[Di.Projection=30320]="Projection",Di[Di.ProjectionType=30321]="ProjectionType",Di[Di.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Di[Di.Attachments=423732329]="Attachments",Di[Di.AttachedFile=24999]="AttachedFile",Di[Di.FileDescription=18046]="FileDescription",Di[Di.FileName=18030]="FileName",Di[Di.FileMediaType=18016]="FileMediaType",Di[Di.FileData=18012]="FileData",Di[Di.FileUID=18094]="FileUID",Di[Di.Chapters=272869232]="Chapters",Di[Di.Tags=307544935]="Tags",Di[Di.Tag=29555]="Tag",Di[Di.Targets=25536]="Targets",Di[Di.TargetTypeValue=26826]="TargetTypeValue",Di[Di.TargetType=25546]="TargetType",Di[Di.TagTrackUID=25541]="TagTrackUID",Di[Di.TagEditionUID=25545]="TagEditionUID",Di[Di.TagChapterUID=25540]="TagChapterUID",Di[Di.TagAttachmentUID=25542]="TagAttachmentUID",Di[Di.SimpleTag=26568]="SimpleTag",Di[Di.TagName=17827]="TagName",Di[Di.TagLanguage=17530]="TagLanguage",Di[Di.TagString=17543]="TagString",Di[Di.TagBinary=17541]="TagBinary",Di[Di.ContentEncodings=28032]="ContentEncodings",Di[Di.ContentEncoding=25152]="ContentEncoding",Di[Di.ContentEncodingOrder=20529]="ContentEncodingOrder",Di[Di.ContentEncodingScope=20530]="ContentEncodingScope",Di[Di.ContentCompression=20532]="ContentCompression",Di[Di.ContentCompAlgo=16980]="ContentCompAlgo",Di[Di.ContentCompSettings=16981]="ContentCompSettings",Di[Di.ContentEncryption=20533]="ContentEncryption";const Mi=[Ri.EBML,Ri.Segment],Ni=[Ri.SeekHead,Ri.Info,Ri.Cluster,Ri.Tracks,Ri.Cues,Ri.Attachments,Ri.Chapters,Ri.Tags],Oi=[...Mi,...Ni],Li=16,zi=e=>{if(e.remainingLength<1)return null;const t=Ca(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},Ui=e=>{if(e.remainingLength<1)return null;const t=Ca(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 n=t&r-1;for(let s=1;s<i;s++)n*=256,n+=Ca(e);return n},qi=(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+=Ca(e);return i},Wi=e=>{const t=zi(e);if(null===t)return null;if(e.remainingLength<t)return null;return qi(e,t)},Vi=e=>{if(e.remainingLength<1)return null;if(255===Ca(e))return;e.skip(-1);const t=Ui(e);return null===t?null:72057594037927940!==t?t:void 0},Hi=e=>{y(e.remainingLength>=2);const t=Wi(e);if(null===t)return null;const i=Vi(e);return null===i?null:{id:t,size:i}},Ki=(e,t)=>{const i=xa(e,t);let r=0;for(;r<t&&0!==i[r];)r+=1;return String.fromCharCode(...i.subarray(0,r))},ji=(e,t)=>{const i=xa(e,t);let r=0;for(;r<t&&0!==i[r];)r+=1;return I.decode(i.subarray(0,r))},Xi=(e,t)=>{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Ua(e):qa(e)},$i=(e,t,i,r)=>d(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||s<r;){let t=e.requestSliceRange(s,2,Li);if(t instanceof Promise&&(t=yield t),!t)break;const i=Hi(t);if(!i)break;if(n.has(i.id))return{pos:s,found:!0};lr(i.size),s=t.filePos+i.size}return{pos:null!==r&&r>s?r:s,found:!1}}),Qi=(e,t,i,r)=>d(null,null,function*(){const n=o(2,16),s=new Set(i);let a=t;for(;a<r;){let t=e.requestSliceRange(a,0,Math.min(n,r-a));if(t instanceof Promise&&(t=yield t),!t)break;if(t.length<8)break;for(let e=0;e<t.length-8;e++){t.filePos=a;const e=Wi(t);if(null!==e&&s.has(e))return a;a++}}return null}),Gi="V_MPEG4/ISO/AVC",Yi="V_MPEGH/ISO/HEVC",Ji="V_VP8",Zi="V_VP9",er="V_AV1",tr="A_AAC",ir="A_MPEG/L3",rr="A_OPUS",nr="A_VORBIS",sr="A_FLAC",ar="A_AC3",or="A_EAC3";function lr(e){if(void 0===e)throw new Error("Undefined element size is used in a place where it is not supported.")}var cr,ur,dr,hr,fr,mr;(ur=cr||(cr={}))[ur.None=0]="None",ur[ur.Xiph=1]="Xiph",ur[ur.FixedSize=2]="FixedSize",ur[ur.Ebml=3]="Ebml",(hr=dr||(dr={}))[hr.Block=1]="Block",hr[hr.Private=2]="Private",hr[hr.Next=4]="Next",(mr=fr||(fr={}))[mr.Zlib=0]="Zlib",mr[mr.Bzlib=1]="Bzlib",mr[mr.lzo1x=2]="lzo1x",mr[mr.HeaderStripping=3]="HeaderStripping";const pr=[{id:Ri.SeekHead,flag:"seekHeadSeen"},{id:Ri.Info,flag:"infoSeen"},{id:Ri.Tracks,flag:"tracksSeen"},{id:Ri.Cues,flag:"cuesSeen"}],gr=10*o(2,20);class kr extends Qt{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}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.segments.flatMap(e=>e.tracks.map(e=>e.trackBacking))})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();const e=yield this.getTrackBackings(),t=yield Promise.all(e.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t: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=>{var t;return"video"===(null==(t=e.info)?void 0:t.type)})),hasAudio:this.segments.some(e=>e.tracks.some(e=>{var t;return"audio"===(null==(t=e.info)?void 0:t.type)})),codecStrings:t.filter(Boolean)})})}getMetadataTags(){return d(this,null,function*(){yield this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&(yield this.loadSegmentMetadata(t)),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e=c(c({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,Li);if(t instanceof Promise&&(t=yield t),!t)break;const i=Hi(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===Ri.EBML){lr(n);let e=this.reader.requestSlice(s,n);if(e instanceof Promise&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===Ri.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===Ri.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield $i(this.reader,s,Oi,this.reader.fileSize)).pos-s}const e=T(this.segments);e&&(e.elementEndPos=s+n)}lr(n),e=s+n}}))()}readSegment(e,t){return d(this,null,function*(){var i;this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let r=e;for(;null===this.currentSegment.elementEndPos||r<this.currentSegment.elementEndPos;){let e=this.reader.requestSliceRange(r,2,Li);if(e instanceof Promise&&(e=yield e),!e)break;const t=r,n=Hi(e);if(!n||!Ni.includes(n.id)&&n.id!==Ri.Void){const e=yield Qi(this.reader,t,Ni,Math.min(null!=(i=this.currentSegment.elementEndPos)?i:1/0,t+gr));if(e){r=e;continue}break}const{id:s,size:a}=n,o=e.filePos,l=pr.findIndex(e=>e.id===s);if(-1!==l){const e=pr[l].flag;this.currentSegment[e]=!0,lr(a);let t=this.reader.requestSlice(o,a);t instanceof Promise&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===Ri.Tags||s===Ri.Attachments){s===Ri.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,lr(a);let e=this.reader.requestSlice(o,a);e instanceof Promise&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===Ri.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===a)break;r=o+a}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const t of this.currentSegment.seekEntries){const i=pr.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,Li);if(r instanceof Promise&&(r=yield r),!r)continue;const n=Hi(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;lr(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);o instanceof Promise&&(o=yield o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const e of this.currentSegment.tracks)null!==e.defaultDurationNs&&(e.defaultDuration=this.currentSegment.timestampFactor*e.defaultDurationNs/1e9);const n=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const e of this.currentSegment.cuePoints){const t=n.get(e.trackId);t&&t.cuePoints.push(e)}for(const e of this.currentSegment.tracks){e.cuePoints.sort((e,t)=>e.time-t.time);for(let t=0;t<e.cuePoints.length-1;t++){const i=e.cuePoints[t],r=e.cuePoints[t+1];i.time===r.time&&(e.cuePoints.splice(t+1,1),t--)}}let s=null,a=-1/0;for(const e of this.currentSegment.tracks)e.cuePoints.length>a&&(a=e.cuePoints.length,s=e);for(const e of this.currentSegment.tracks)0===e.cuePoints.length&&(e.cuePoints=s.cuePoints);this.currentSegment=null})}readCluster(e,t){return d(this,null,function*(){var i;if((null==(i=t.lastReadCluster)?void 0:i.elementStartPos)===e)return t.lastReadCluster;let r=this.reader.requestSliceRange(e,2,Li);r instanceof Promise&&(r=yield r),y(r);const n=e,s=Hi(r);y(s);y(s.id===Ri.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield $i(this.reader,o,Oi,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);l instanceof Promise&&(l=yield l);const c={segment:t,elementStartPos:n,elementEndPos:o+a,dataStartPos:o,timestamp:-1,trackData:new Map};if(this.currentCluster=c,l){const e=this.readContiguousElements(l,Oi);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;y(e.blocks.length>0);let i=!1;for(let n=0;n<e.blocks.length;n++){const t=e.blocks[n];t.timestamp+=c.timestamp,i||(i=t.lacing!==cr.None)}e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n<e.presentationTimestamps.length;n++){const i=e.presentationTimestamps[n],r=e.blocks[i.blockIndex];if(null===e.firstKeyFrameTimestamp&&r.isKeyFrame&&(e.firstKeyFrameTimestamp=r.timestamp),n<e.presentationTimestamps.length-1){const t=e.presentationTimestamps[n+1];r.duration=t.timestamp-r.timestamp}else 0===r.duration&&null!=t.defaultDuration&&r.lacing===cr.None&&(r.duration=t.defaultDuration)}i&&(this.expandLacedBlocks(e.blocks,t),e.presentationTimestamps=e.blocks.map((e,t)=>({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[T(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=z(t.clusterPositionCache,e.startTimestamp,e=>e.startTimestamp);-1!==a&&t.clusterPositionCache[a].elementStartPos===n||t.clusterPositionCache.splice(a+1,0,{elementStartPos:c.elementStartPos,startTimestamp:e.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){var i;for(let r=0;r<e.length;r++){const n=e[r];if(n.lacing===cr.None)continue;n.decoded||(n.data=this.decodeBlockData(t,n.data),n.decoded=!0);const s=Pa.tempFromBytes(n.data),a=[],o=Ca(s)+1;switch(n.lacing){case cr.Xiph:{let e=0;for(let t=0;t<o-1;t++){let t=0;for(;s.bufferPos<s.length;){const i=Ca(s);if(t+=i,i<255){a.push(t),e+=t;break}}}a.push(s.length-(s.bufferPos+e))}break;case cr.FixedSize:{const e=s.length-1,t=Math.floor(e/o);for(let i=0;i<o;i++)a.push(t)}break;case cr.Ebml:{const e=Ui(s);y(null!==e);let t=e;a.push(t);let i=t;for(let r=1;r<o-1;r++){const e=s.bufferPos,r=Ui(s);y(null!==r);t+=r-((1<<7*(s.bufferPos-e)-1)-1),a.push(t),i+=t}a.push(s.length-(s.bufferPos+i))}break;default:y(!1)}y(a.length===o),e.splice(r,1);const l=n.duration||o*(null!=(i=t.defaultDuration)?i:0);for(let t=0;t<o;t++){const i=a[t],c=xa(s,i),u=n.timestamp+l*t/o,d=l/o;e.splice(r+t,0,{timestamp:u,duration:d,isKeyFrame:n.isKeyFrame,data:c,lacing:cr.None,decoded:!0,mainAdditional:n.mainAdditional})}r+=o,r--}}loadSegmentMetadata(e){return d(this,null,function*(){for(const t of e.seekEntries){if(t.id!==Ri.Tags||e.tagsSeen){if(t.id!==Ri.Attachments||e.attachmentsSeen)continue}else;let i=this.reader.requestSliceRange(e.dataStartPos+t.segmentPosition,2,Li);if(i instanceof Promise&&(i=yield i),!i)continue;const r=Hi(i);if(!r||r.id!==t.id)continue;const{size:n}=r;lr(n),y(!this.currentSegment),this.currentSegment=e;let s=this.reader.requestSlice(i.filePos,n);s instanceof Promise&&(s=yield s),s&&this.readContiguousElements(s),this.currentSegment=null,t.id===Ri.Tags?e.tagsSeen=!0:t.id===Ri.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){var i,r,n,s,a,o,l,d,h,f,m,p,g,k,T,S,v,w,P,I,x,C,E,A,R,D,M,N,O,L,z,U,q,W,V,H,K,j,X,$,G,Y,J,Z,te,ie,re,ne,se,ae,oe,le,ce,ue;const de=Hi(e);if(!de)return!1;if(t&&t.includes(de.id))return!1;const{id:he,size:fe}=de,me=e.filePos;switch(lr(fe),he){case Ri.DocType:this.isWebM="webm"===Ki(e,fe);break;case Ri.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(me,fe)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case Ri.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=qi(e,fe)}break;case Ri.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=qi(e,fe)}break;case Ri.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=qi(e,fe),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case Ri.Duration:if(!this.currentSegment)break;this.currentSegment.duration=Xi(e,fe);break;case Ri.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:u(c({},Be),{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(me,fe)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==dr.Block||e.data.algorithm!==fr.HeaderStripping})&&(console.warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){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))}this.currentTrack.codecId===Gi?(this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):this.currentTrack.codecId===Yi?(this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Ji?this.currentTrack.info.codec="vp8":t===Zi?this.currentTrack.info.codec="vp9":t===er&&(this.currentTrack.info.codec="av1");const e=this.currentTrack;this.currentTrack.trackBacking=new br(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===tr?(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===ir?this.currentTrack.info.codec="mp3":t===rr?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=We):t===nr?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===sr?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ar?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===or?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Tr(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case Ri.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=qi(e,fe);break;case Ri.TrackType:{if(!this.currentTrack)break;const t=qi(e,fe);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:null,alphaMode:!1}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null})}break;case Ri.FlagEnabled:if(!this.currentTrack)break;qi(e,fe)||(this.currentTrack=null);break;case Ri.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!qi(e,fe);break;case Ri.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!qi(e,fe);break;case Ri.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!qi(e,fe);break;case Ri.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!qi(e,fe);break;case Ri.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!qi(e,fe);break;case Ri.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!qi(e,fe);break;case Ri.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Ki(e,fe);break;case Ri.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=xa(e,fe);break;case Ri.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=qi(e,fe);break;case Ri.Name:if(!this.currentTrack)break;this.currentTrack.name=ji(e,fe);break;case Ri.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Ki(e,fe),ee(this.currentTrack.languageCode)||(this.currentTrack.languageCode=Q);break;case Ri.LanguageBCP47:{if(!this.currentTrack)break;const t=Ki(e,fe).split("-")[0];this.currentTrack.languageCode=t||Q,this.currentTrack.hasLanguageBcp47=!0}break;case Ri.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=qi(e,fe);break;case Ri.PixelHeight:if("video"!==(null==(d=null==(l=this.currentTrack)?void 0:l.info)?void 0:d.type))break;this.currentTrack.info.height=qi(e,fe);break;case Ri.DisplayWidth:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayWidth=qi(e,fe);break;case Ri.DisplayHeight:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayHeight=qi(e,fe);break;case Ri.DisplayUnit:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.displayUnit=qi(e,fe);break;case Ri.AlphaMode:if("video"!==(null==(S=null==(T=this.currentTrack)?void 0:T.info)?void 0:S.type))break;this.currentTrack.info.alphaMode=1===qi(e,fe);break;case Ri.Colour:if("video"!==(null==(w=null==(v=this.currentTrack)?void 0:v.info)?void 0:w.type))break;this.currentTrack.info.colorSpace={},this.readContiguousElements(e.slice(me,fe));break;case Ri.MatrixCoefficients:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(x=F[t])?x:null;this.currentTrack.info.colorSpace.matrix=i}break;case Ri.Range:if("video"!==(null==(E=null==(C=this.currentTrack)?void 0:C.info)?void 0:E.type)||!this.currentTrack.info.colorSpace)break;this.currentTrack.info.colorSpace.fullRange=2===qi(e,fe);break;case Ri.TransferCharacteristics:{if("video"!==(null==(R=null==(A=this.currentTrack)?void 0:A.info)?void 0:R.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(D=_[t])?D:null;this.currentTrack.info.colorSpace.transfer=i}break;case Ri.Primaries:{if("video"!==(null==(N=null==(M=this.currentTrack)?void 0:M.info)?void 0:N.type)||!this.currentTrack.info.colorSpace)break;const t=qi(e,fe),i=null!=(O=B[t])?O:null;this.currentTrack.info.colorSpace.primaries=i}break;case Ri.Projection:if("video"!==(null==(z=null==(L=this.currentTrack)?void 0:L.info)?void 0:z.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.ProjectionPoseRoll:{if("video"!==(null==(q=null==(U=this.currentTrack)?void 0:U.info)?void 0:q.type))break;const t=-Xi(e,fe);try{this.currentTrack.info.rotation=b(t)}catch(pe){}}break;case Ri.Audio:if("audio"!==(null==(V=null==(W=this.currentTrack)?void 0:W.info)?void 0:V.type))break;this.readContiguousElements(e.slice(me,fe));break;case Ri.SamplingFrequency:if("audio"!==(null==(K=null==(H=this.currentTrack)?void 0:H.info)?void 0:K.type))break;this.currentTrack.info.sampleRate=Xi(e,fe);break;case Ri.Channels:if("audio"!==(null==(X=null==(j=this.currentTrack)?void 0:j.info)?void 0:X.type))break;this.currentTrack.info.numberOfChannels=qi(e,fe);break;case Ri.BitDepth:if("audio"!==(null==(G=null==($=this.currentTrack)?void 0:$.info)?void 0:G.type))break;this.currentTrack.info.bitDepth=qi(e,fe);break;case Ri.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(me,fe)),this.currentCueTime=null;break;case Ri.CueTime:this.currentCueTime=qi(e,fe);break;case Ri.CueTrackPositions:{if(null===this.currentCueTime)break;y(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(me,fe)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case Ri.CueTrack:{const t=null==(Y=this.currentSegment)?void 0:Y.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=qi(e,fe)}break;case Ri.CueClusterPosition:{const t=null==(J=this.currentSegment)?void 0:J.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;y(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+qi(e,fe)}break;case Ri.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=qi(e,fe);break;case Ri.SimpleBlock:{if(!this.currentCluster)break;const t=Ui(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Aa(e),n=Ca(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(Z=i.track.info)?void 0:Z.type)&&i.track.info.codec&&(a=!0);const o=xa(e,fe-(e.filePos-me)),l=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,mainAdditional:null})}break;case Ri.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(me,fe)),this.currentBlock=null;break;case Ri.Block:{if(!this.currentCluster)break;const t=Ui(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Aa(e),n=Ca(e)>>1&3,s=xa(e,fe-(e.filePos-me)),a=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case Ri.BlockAdditions:this.readContiguousElements(e.slice(me,fe));break;case Ri.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(me,fe)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case Ri.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=xa(e,fe);break;case Ri.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=qi(e,fe);break;case Ri.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=qi(e,fe);break;case Ri.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case Ri.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(me,fe));break;case Ri.Targets:this.readContiguousElements(e.slice(me,fe));break;case Ri.TargetTypeValue:50!==qi(e,fe)&&(this.currentTagTargetIsMovie=!1);break;case Ri.TagTrackUID:case Ri.TagEditionUID:case Ri.TagChapterUID:case Ri.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case Ri.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(me,fe));break;case Ri.TagName:this.currentSimpleTagName=ji(e,fe);break;case Ri.TagString:{if(!this.currentSimpleTagName)break;const t=ji(e,fe);this.processTagValue(this.currentSimpleTagName,t)}break;case Ri.TagBinary:{if(!this.currentSimpleTagName)break;const t=xa(e,fe);this.processTagValue(this.currentSimpleTagName,t)}break;case Ri.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(me,fe));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new Ce(this.currentAttachedFile.fileData,null!=(te=this.currentAttachedFile.fileMediaType)?te:void 0,null!=(ie=this.currentAttachedFile.fileName)?ie:void 0,null!=(re=this.currentAttachedFile.fileDescription)?re:void 0)),(null==(ne=this.currentAttachedFile.fileMediaType)?void 0:ne.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")}null!=t.images||(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:null!=(se=this.currentAttachedFile.fileName)?se:void 0,description:null!=(ae=this.currentAttachedFile.fileDescription)?ae:void 0})}this.currentAttachedFile=null}break;case Ri.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=BigInt("0");for(let r=0;r<t;r++)i<<=BigInt("8"),i+=BigInt(Ca(e));return i})(e,fe);break;case Ri.FileName:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileName=ji(e,fe);break;case Ri.FileMediaType:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileMediaType=Ki(e,fe);break;case Ri.FileData:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileData=xa(e,fe);break;case Ri.FileDescription:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileDescription=ji(e,fe);break;case Ri.ContentEncodings:if(!this.currentTrack)break;this.readContiguousElements(e.slice(me,fe)),this.currentTrack.decodingInstructions.sort((e,t)=>t.order-e.order);break;case Ri.ContentEncoding:this.currentDecodingInstruction={order:0,scope:dr.Block,data:null},this.readContiguousElements(e.slice(me,fe)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case Ri.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=qi(e,fe);break;case Ri.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=qi(e,fe);break;case Ri.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:fr.Zlib,settings:null},this.readContiguousElements(e.slice(me,fe));break;case Ri.ContentCompAlgo:if("decompress"!==(null==(le=null==(oe=this.currentDecodingInstruction)?void 0:oe.data)?void 0:le.type))break;this.currentDecodingInstruction.data.algorithm=qi(e,fe);break;case Ri.ContentCompSettings:if("decompress"!==(null==(ue=null==(ce=this.currentDecodingInstruction)?void 0:ce.data)?void 0:ue.type))break;this.currentDecodingInstruction.data.settings=xa(e,fe);break;case Ri.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=me+fe,!0}decodeBlockData(e,t){y(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(y(r.data),"decompress"===r.data.type)if(r.data.algorithm===fr.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,r;if(!(null==(i=this.currentSegment)?void 0:i.metadataTags))return;const n=this.currentSegment.metadataTags;if(null!=n.raw||(n.raw={}),null!=(r=n.raw)[e]||(r[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":null!=n.title||(n.title=t);break;case"description":null!=n.description||(n.description=t);break;case"artist":null!=n.artist||(n.artist=t);break;case"album":null!=n.album||(n.album=t);break;case"album_artist":null!=n.albumArtist||(n.albumArtist=t);break;case"genre":null!=n.genre||(n.genre=t);break;case"comment":null!=n.comment||(n.comment=t);break;case"lyrics":null!=n.lyrics||(n.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||null!=n.date||(n.date=e)}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=n.trackNumber||(n.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=n.tracksTotal||(n.tracksTotal=r))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(null!=n.discNumber||(n.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(null!=n.discsTotal||(n.discsTotal=r))}}}}class yr{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}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){var e;const t=this.internalTrack.segment;if(t.duration<=0)return null;let i=t.duration/t.timestampFactor;const r=yield this.getFirstPacket({metadataOnly:!0});return i+=null!=(e=null==r?void 0:r.timestamp)?e:0,i})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getFirstPacket(e){return d(this,null,function*(){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 G(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return d(this,null,function*(){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)})}getNextPacket(e,t){return d(this,null,function*(){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)})}getKeyPacket(e,t){return d(this,null,function*(){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=V(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)})}getNextKeyPacket(e,t){return d(this,null,function*(){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 y(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return d(this,null,function*(){var r;if(-1===t)return null;const n=e.trackData.get(this.internalTrack.id).blocks[t];y(n),n.decoded||(n.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,n.data),n.decoded=!0);const s=i.metadataOnly?Gt:n.data,a=n.timestamp/this.internalTrack.segment.timestampFactor,o=n.duration/this.internalTrack.segment.timestampFactor,l={};n.mainAdditional&&"video"===(null==(r=this.internalTrack.info)?void 0:r.type)&&this.internalTrack.info.alphaMode&&(l.alpha=i.metadataOnly?Gt:n.mainAdditional,l.alphaByteLength=n.mainAdditional.byteLength);const c=new Yt(s,n.isKeyFrame?"key":"delta",a,o,e.dataStartPos+t,n.data.byteLength,l);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c})}performClusterLookup(e,t,i,r,n){return d(this,null,function*(){var s,a,o,l;const{demuxer:c,segment:u}=this.internalTrack;let d=null,h=null,f=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,n);-1!==i&&(h=e,f=i)}const m=z(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=z(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,b=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let T;for(e?null===b||e.elementStartPos>=b?(T=e.elementEndPos,d=e):T=b:T=null!=b?b:u.clusterSeekStartPos;null===u.elementEndPos||T<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(T,2,Li);if(e instanceof Promise&&(e=yield e),!e)break;const i=T,s=Hi(e);if(!s||!Ni.includes(s.id)&&s.id!==Ri.Void){const e=yield Qi(c.reader,i,Ni,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+gr));if(e){T=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===Ri.Cluster){d=yield c.readCluster(i,u),l=d.elementEndPos-m;const{blockIndex:e,correctBlockFound:r}=t(d);if(r)return this.fetchPacketInCluster(d,e,n);-1!==e&&(h=d,f=e)}if(void 0===l){y(a!==Ri.Cluster);l=(yield $i(c.reader,m,Oi,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,Li);if(e instanceof Promise&&(e=yield e),!e)break;if(Wi(e)===Ri.Segment){u.elementEndPos=p;break}}T=p}if(p&&(!h||h.elementStartPos<p.clusterPosition)){const e=this.internalTrack.cuePoints[m-1];y(!e||e.time<p.time);const i=null!=(l=null==e?void 0:e.time)?l:-1/0;return this.performClusterLookup(null,t,i,r,n)}return h?this.fetchPacketInCluster(h,f,n):null})}}class br extends yr{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}getColorSpace(){return d(this,null,function*(){var e,t,i,r;return{primaries:null==(e=this.internalTrack.info.colorSpace)?void 0:e.primaries,transfer:null==(t=this.internalTrack.info.colorSpace)?void 0:t.transfer,matrix:null==(i=this.internalTrack.info.colorSpace)?void 0:i.matrix,fullRange:null==(r=this.internalTrack.info.colorSpace)?void 0:r.fullRange}})}canBeTransparent(){return d(this,null,function*(){return this.internalTrack.info.alphaMode})}getDecoderConfig(){return d(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>d(this,null,function*(){var e,t;let i=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(i=yield this.getFirstPacket({}));const r={codec:Ue({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&&i?pt(i.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&i?vt(i.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&i?Rt(i.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&i?Mt(i.data):null}),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0,colorSpace:null!=(t=this.internalTrack.info.colorSpace)?t:void 0};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(r.displayAspectWidth=this.internalTrack.info.squarePixelWidth,r.displayAspectHeight=this.internalTrack.info.squarePixelHeight),r}))():null})}}class Tr extends yr{constructor(e){super(e),this.decoderConfig=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){var e,t;return this.internalTrack.info.codec?null!=(t=this.decoderConfig)?t:this.decoderConfig={codec:qe({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}:null})}}const Sr=(e,t,i)=>d(null,null,function*(){const r=o(2,16);let n=t;for(;null===i||n<i;){const t=null!==i?Math.min(r,i-n):r;let s=e.requestSliceRange(n,4,t);if(s instanceof Promise&&(s=yield s),!s||s.length<4)break;for(;s.remainingLength>=4;){const t=s.filePos,i=Ra(s),r=null!==e.fileSize?e.fileSize-n:null,a=Ye(i,r);if(a.header)return{header:a.header,startPos:n};s.filePos=t+a.bytesAdvanced,n=s.filePos}}return null});class vr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new wr(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Qa);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Za(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield Sr(this.reader,this.lastLoadedPos,this.reader.fileSize);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Ge(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(r instanceof Promise&&(r=yield r),r){const t=Ra(r);if(t===$e||t===Qe){if(!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(t instanceof Promise&&(t=yield t),t){const e=xa(t,12),i=P(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Ze.FrameCount?i.getUint32(4,!1):null,fileSize:r&Ze.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos),t.sampleRate!==this.firstFrameHeader.sampleRate&&console.warn(`MP3 changed sample rate mid-file: ${this.firstFrameHeader.sampleRate} Hz to ${t.sampleRate} Hz. Might be a bug, so please report this file.`);const n=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:n,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame})}getMimeType(){return d(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(n instanceof Promise&&(n=yield n),!n)break;eo(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=$a){let e=this.reader.requestSlice(this.reader.fileSize-$a,$a);e instanceof Promise&&(e=yield e),y(e);"TAG"===Wa(e,3)&&Ya(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class wr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){const e=this.demuxer;if(y(null!==e.firstFrameHeader),y(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,n=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(n<<t):2===i?144*r/n:12*r/n*4),a=(e.reader.fileSize-e.firstFrameHeaderPos)/s;return Math.round(a)*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}var t,i,r,n;return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Q}getCodec(){return"mp3"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.firstFrameHeader),3===this.demuxer.firstFrameHeader.channel?1:2}getSampleRate(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate}getDisposition(){return c({},Be)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.firstFrameHeader),{codec:"mp3",numberOfChannels:3===this.demuxer.firstFrameHeader.channel?1:2,sampleRate:this.demuxer.firstFrameHeader.sampleRate}})}getPacketAtIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Gt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=yield e),!e)return null;r=xa(e,i.dataSize)}return new Yt(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=L(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;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield 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);yield this.demuxer.advanceReader()}}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Pr=1399285583,Ir=new Uint32Array(256);for(let ho=0;ho<256;ho++){let e=ho<<24;for(let t=0;t<8;t++)e=2147483648&e?e<<1^79764919:e<<1;Ir[ho]=e>>>0&4294967295}const xr=e=>{const t=P(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n<e.length;n++){const t=e[n];r=(r<<8^Ir[r>>>24^t])>>>0}return t.setUint32(22,i,!0),r},Cr=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){y(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,a=(e[0]&s)>>1;if(a>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const l=t.vorbisInfo.modeBlockflags[a];if(n=t.vorbisInfo.blocksizes[l],1===l){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+n>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3;return{durationInSamples:Nt[t]}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},Br=27,Er=282,_r=e=>{const t=e.filePos;if(Da(e)!==Pr)return null;e.skip(1);const i=Ca(e),r=za(e),n=Da(e),s=Da(e),a=Da(e),o=Ca(e),l=new Uint8Array(o);for(let d=0;d<o;d++)l[d]=Ca(e);const c=27+o,u=l.reduce((e,t)=>e+t,0);return{headerStartPos:t,totalSize:c+u,dataStartPos:t+c,dataSize:u,headerType:i,granulePosition:r,serialNumber:n,sequenceNumber:s,checksum:a,lacingValues:l}},Ar=(e,t)=>{for(;e.filePos<t-3;){const t=Da(e),i=79;if((255&t)===i||(t>>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Pr)return!0;e.skip(1)}}return!1};class Fr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,Br,Er);if(t instanceof Promise&&(t=yield t),!t)break;const i=_r(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=yield 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]?yield 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]&&(yield this.readOpusMetadata(e,t)),null!==t.codecInfo.codec&&this.trackBackings.push(new Rr(t,this)))}}))()})}readVorbisMetadata(e,t){return d(this,null,function*(){let i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=yield this.findNextPacketStart(r),!i)return;const n=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!n)return;if(3!==r.data[0]||5!==n.data[0])return;const s=[],a=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};a(e.data.length),a(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+n.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(n.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=n;const l=P(e.data);t.numberOfChannels=l.getUint8(11),t.sampleRate=l.getUint32(12,!0);const c=l.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&c),1<<(c>>4)],modeBlockflags:Ot(n.data).modeBlockflags},qt(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return d(this,null,function*(){const i=yield this.findNextPacketStart(e);if(!i)return;const r=yield this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const n=(e=>{const t=P(e),i=t.getUint8(9),r=t.getUint16(10,!0),n=t.getUint32(12,!0),s=t.getInt16(16,!0),a=t.getUint8(18);let o=null;return a&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:n,outputGain:s,channelMappingFamily:a,channelMappingTable:o}})(e.data);t.numberOfChannels=n.outputChannelCount,t.sampleRate=We,t.codecInfo.opusInfo={preSkip:n.preSkip},qt(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return d(this,null,function*(){y(t<e.lacingValues.length);let i=0;for(let u=0;u<t;u++)i+=e.lacingValues[u];let r=e,n=i,s=t;const a=[];e:for(;;){let t=this.reader.requestSlice(r.dataStartPos,r.dataSize);t instanceof Promise&&(t=yield t),y(t);const o=xa(t,r.dataSize);for(;;){if(s===r.lacingValues.length){a.push(o.subarray(i,n));break}const e=r.lacingValues[s];if(n+=e,e<255){a.push(o.subarray(i,n));break e}s++}let l=r.headerStartPos+r.totalSize;for(;;){let t=this.reader.requestSliceRange(l,Br,Er);if(t instanceof Promise&&(t=yield t),!t)return null;const i=_r(t);if(!i)return null;if(r=i,r.serialNumber===e.serialNumber)break;l=r.headerStartPos+r.totalSize}i=0,n=0,s=0}const o=a.reduce((e,t)=>e+t.length,0);if(0===o)return null;const l=new Uint8Array(o);let c=0;for(let e=0;e<a.length;e++){const t=a[e];l.set(t,c),c+=t.length}return{data:l,endPage:r,endSegmentIndex:s}})}findNextPacketStart(e){return d(this,null,function*(){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,Br,Er);if(i instanceof Promise&&(i=yield i),!i)return null;const r=_r(i);if(!r)return null;if(r.serialNumber===e.endPage.serialNumber)return{startPage:r,startSegmentIndex:0};t=r.headerStartPos+r.totalSize}})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();return(e=>{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(yield Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null})))).filter(Boolean)})})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class Rr{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new D,this.internalSampleRate="opus"===e.codecInfo.codec?We:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return y(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return d(this,null,function*(){var e;return y(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:null!=(e=this.bitstream.description)?e:void 0}})}getName(){return null}getLanguageCode(){return Q}getDisposition(){return u(c({},Be),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(y(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=Cr(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Yt(i.metadataOnly?Gt: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:n}),s}getFirstPacket(e){return d(this,null,function*(){y(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(y(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=yield this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)})}getNextPacket(e,t){return d(this,null,function*(){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=yield this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const n=i.timestampInSamples+i.durationInSamples,s=yield this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:n,vorbisLastBlocksize:i.vorbisBlockSize},t)})}getPacket(e,t){return d(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=G(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;y(this.bitstream.lastMetadataPacket);const s=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!s)return null;let a=s.startPage,o=this.demuxer.reader.fileSize;const l=[a];e:for(;a.headerStartPos+a.totalSize<o;){const e=a.headerStartPos,t=Math.floor((e+o)/2);let i=t;for(;;){const e=Math.min(i+65307,o-Br);let r=this.demuxer.reader.requestSlice(i,e-i);r instanceof Promise&&(r=yield r),y(r);if(!Ar(r,e)){o=t+Br;continue e}let s=this.demuxer.reader.requestSliceRange(r.filePos,Br,Er);s instanceof Promise&&(s=yield s),y(s);const c=_r(s);y(c);let u=!1;if(c.serialNumber===this.bitstream.serialNumber)u=!0;else{let e=this.demuxer.reader.requestSlice(c.headerStartPos,c.totalSize);e instanceof Promise&&(e=yield e),y(e);const t=xa(e,c.totalSize);u=xr(t)===c.checksum}if(!u){i=c.headerStartPos+4;continue}if(u&&c.serialNumber!==this.bitstream.serialNumber){i=c.headerStartPos+c.totalSize;continue}if(!(-1===c.granulePosition)){this.granulePositionToTimestampInSamples(c.granulePosition)>n?o=c.headerStartPos:(a=c,l.push(c));continue e}i=c.headerStartPos+c.totalSize}}let c=s.startPage;for(const e of l){if(e.granulePosition===a.granulePosition)break;(!c||e.headerStartPos>c.headerStartPos)&&(c=e)}let u=c;const d=[u];for(;u.serialNumber!==this.bitstream.serialNumber||u.granulePosition!==a.granulePosition;){const e=u.headerStartPos+u.totalSize;let t=this.demuxer.reader.requestSliceRange(e,Br,Er);t instanceof Promise&&(t=yield t),y(t);const i=_r(t);y(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}y(-1!==u.granulePosition);let h,f,m=null,p=u,g=0;if(u.headerStartPos===s.startPage.headerStartPos)h=this.granulePositionToTimestampInSamples(0),f=!0,m=0;else{h=0,f=!1;for(let t=u.lacingValues.length-1;t>=0;t--){if(u.lacingValues[t]<255){m=t+1;break}}if(null===m)throw new Error("Invalid page with granule position: no packets end on this page.");g=m-1;const e={data:Gt,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=Mr(d,u,m);y(e);const t=Dr(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=Mr(d,u,m);if(!e)break;const t=Dr(d,e.page,e.segmentIndex);if(!t)break;if(u=t.page,m=t.segmentIndex,e.page.headerStartPos!==p.headerStartPos){p=e.page,g=e.segmentIndex;break}}}let k=null,b=null;for(;null!==u;){y(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&m<s.startSegmentIndex)){let s=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:h,vorbisLastBlocksize:null!=(i=null==b?void 0:b.vorbisBlockSize)?i:null},t);y(s);let a=this.encodedPacketToMetadata.get(s);if(y(a),f||e.endPage.headerStartPos!==p.headerStartPos||e.endSegmentIndex!==g?h+=a.durationInSamples:(h=this.granulePositionToTimestampInSamples(u.granulePosition),f=!0,s=this.createEncodedPacketFromOggPacket(e,{timestampInSamples:h-a.durationInSamples,vorbisLastBlocksize:null!=(r=null==b?void 0:b.vorbisBlockSize)?r:null},t),y(s),a=this.encodedPacketToMetadata.get(s),y(a)),k=s,b=a,f&&(Math.max(h,0)>n||Math.max(a.timestampInSamples,0)===n))break}const a=yield this.demuxer.findNextPacketStart(e);if(!a)break;u=a.startPage,m=a.startSegmentIndex}return k})}getPacketSequential(e,t){return d(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=G(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=z(this.sequentialScanCache,i,e=>e.timestampInSamples);let n;if(-1!==r){const e=this.sequentialScanCache[r];n=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else n=yield this.getFirstPacket(t);let s=0;for(;n&&n.timestamp<e;){const i=yield this.getNextPacket(n,t);if(!i||i.timestamp>e)break;if(n=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);y(e),this.sequentialScanCache.length>0&&y(T(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return n}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Dr=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}y(-1===n);if(!(1&r.headerType)){n=0;break}const t=W(e,e=>e.headerStartPos<r.headerStartPos);if(!t)return null;r=t,n=r.lacingValues.length}if(y(-1!==n),n===r.lacingValues.length){const t=e[e.indexOf(r)+1];y(t),r=t,n=0}return{page:r,segmentIndex:n}},Mr=(e,t,i)=>{if(i>0)return{page:t,segmentIndex:i-1};const r=W(e,e=>e.headerStartPos<t.headerStartPos);return r?{page:r,segmentIndex:r.lacingValues.length-1}:null};var Nr,Or;(Or=Nr||(Nr={}))[Or.PCM=1]="PCM",Or[Or.IEEE_FLOAT=3]="IEEE_FLOAT",Or[Or.ALAW=6]="ALAW",Or[Or.MULAW=7]="MULAW",Or[Or.EXTENSIBLE=65534]="EXTENSIBLE";class Lr extends Qt{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}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);i instanceof Promise&&(i=yield i),y(i);const r=Wa(i,4),n="RIFX"!==r,s="RF64"===r,a=Fa(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Wa(i,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=i.filePos;for(;null===o||u<o;){let e=this.reader.requestSlice(u,8);if(e instanceof Promise&&(e=yield e),!e)break;const i=Wa(e,4),r=Fa(e,n),a=e.filePos;if(s&&0===l&&"ds64"!==i)throw new Error('Invalid RF64 file: First chunk must be "ds64".');if("fmt "===i)yield this.parseFmtChunk(a,r,n);else if("data"===i){if(null!=c||(c=r),this.dataStart=e.filePos,this.dataSize=Math.min(c,(null!=o?o:1/0)-this.dataStart),null===this.reader.fileSize)break}else if("ds64"===i){let e=this.reader.requestSlice(a,r);if(e instanceof Promise&&(e=yield e),!e)break;const i=Na(e,n);c=Na(e,n),o=Math.min(i+8,null!=(t=this.reader.fileSize)?t:1/0)}else"LIST"===i?yield this.parseListChunk(a,r,n):"ID3 "!==i&&"id3 "!==i||(yield this.parseId3Chunk(a,r));u=a+r+(1&r),l++}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 d=this.audioInfo.blockSizeInBytes;this.dataSize=Math.floor(this.dataSize/d)*d,this.trackBackings.push(new Ur(this))}))()})}parseFmtChunk(e,t,i){return d(this,null,function*(){let r=this.reader.requestSlice(e,t);if(r instanceof Promise&&(r=yield r),!r)return;let n=Ba(r,i);const s=Ba(r,i),a=Fa(r,i);r.skip(4);const o=Ba(r,i);let l;if(l=14===t?8:Ba(r,i),t>=18&&357!==n){const e=Ba(r,i),s=t-18;if(Math.min(s,e)>=22&&n===Nr.EXTENSIBLE){r.skip(6);const e=xa(r,16);n=e[0]|e[1]<<8}}n!==Nr.MULAW&&n!==Nr.ALAW||(l=8),this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(m instanceof Promise&&(m=yield m),!m)return;const p=Wa(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Wa(m,4),t=Fa(m,i),p=xa(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(null!=(r=this.metadataTags).raw||(r.raw={}),this.metadataTags.raw[e]=y,e){case"INAM":case"TITL":null!=(n=this.metadataTags).title||(n.title=y);break;case"TIT3":null!=(s=this.metadataTags).description||(s.description=y);break;case"IART":null!=(a=this.metadataTags).artist||(a.artist=y);break;case"IPRD":null!=(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&&(null!=(l=this.metadataTags).trackNumber||(l.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(c=this.metadataTags).tracksTotal||(c.tracksTotal=i))}break;case"ICRD":case"IDIT":{const e=new Date(y);Number.isNaN(e.getTime())||null!=(u=this.metadataTags).date||(u.date=e)}break;case"YEAR":{const e=Number.parseInt(y,10);Number.isInteger(e)&&e>0&&(null!=(d=this.metadataTags).date||(d.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":null!=(h=this.metadataTags).genre||(h.genre=y);break;case"ICMT":case"CMNT":case"COMM":null!=(f=this.metadataTags).comment||(f.comment=y)}g+=8+t+(1&t)}})}parseId3Chunk(e,t){return d(this,null,function*(){let i=this.reader.requestSlice(e,t);if(i instanceof Promise&&(i=yield i),!i)return;const r=Za(i);if(r){const n=t-Qa;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+Qa,r.size);eo(t,r,this.metadataTags)}}})}getCodec(){if(y(this.audioInfo),this.audioInfo.format===Nr.MULAW)return"ulaw";if(this.audioInfo.format===Nr.ALAW)return"alaw";if(this.audioInfo.format===Nr.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}return this.audioInfo.format===Nr.IEEE_FLOAT&&4===this.audioInfo.sampleSizeInBytes?"pcm-f32":null}getMimeType(){return d(this,null,function*(){return"audio/wav"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const zr=2048;class Ur{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return d(this,null,function*(){const e=this.demuxer.getCodec();return e?(y(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Q}getDisposition(){return c({},Be)}getPacketAtIndex(e,t){return d(this,null,function*(){y(e>=0),y(this.demuxer.audioInfo);const i=e*zr*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(zr*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(e instanceof Promise&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=Gt;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);e instanceof Promise&&(e=yield e),y(e),n=xa(e,r)}const s=e*zr/this.demuxer.audioInfo.sampleRate,a=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new Yt(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return d(this,null,function*(){y(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/zr,(this.demuxer.dataSize-1)/(zr*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=yield this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;y(null===this.demuxer.reader.fileSize);let n=yield this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;n;){const e=yield this.getNextPacket(n,t);if(!e)break;n=e}return n})}getNextPacket(e,t){y(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/zr);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const qr=e=>{const t=e.filePos,i=xa(e,9),r=new Ee(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const n=r.readBits(1),s=r.readBits(2)+1,a=r.readBits(4);if(15===a)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 l=r.readBits(13);r.skipBits(11);const c=r.readBits(2)+1;if(1!==c)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===n?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:a,channelConfiguration:o,frameLength:l,numberOfAacFrames:c,crcCheck:u,startPos:t}},Wr=1024;class Vr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new D,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();y(this.firstFrameHeader),this.trackBackings=[new Hr(this)]}))()})}advanceReader(){return d(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Qa);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Za(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(e instanceof Promise&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=qr(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=_e[t.samplingFrequencyIndex];y(void 0!==i);const r=Wr/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=Wr,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return d(this,null,function*(){return"audio/aac"})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return d(this,null,function*(){const e=yield this.readingMutex.acquire();try{if(yield this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,Qa);if(t instanceof Promise&&(t=yield t),!t)break;const i=Za(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(r instanceof Promise&&(r=yield r),!r)break;eo(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class Hr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Wr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return Q}getCodec(){return"aac"}getInternalCodecId(){return y(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){y(this.demuxer.firstFrameHeader);const e=Ae[this.demuxer.firstFrameHeader.channelConfiguration];return y(void 0!==e),e}getSampleRate(){y(this.demuxer.firstFrameHeader);const e=_e[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return y(void 0!==e),e}getDisposition(){return c({},Be)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return d(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Gt;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(e instanceof Promise&&(e=yield e),!e)return null;r=xa(e,i.dataSize)}return new Yt(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return d(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=L(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;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}})}getPacket(e,t){return d(this,null,function*(){const i=yield 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);yield this.demuxer.advanceReader()}}finally{i()}})}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}class Kr extends Qt{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 D,this.lastSampleLoaded=!1,this.reader=e._reader}getMetadataTags(){return d(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),y(this.trackBacking),[this.trackBacking]})}getMimeType(){return d(this,null,function*(){return"audio/flac"})}readMetadata(){return d(this,null,function*(){var e;let t=4;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){for(var e;null===this.reader.fileSize||t<this.reader.fileSize;){let i=this.reader.requestSlice(t,4);if(i instanceof Promise&&(i=yield i),t+=4,null===i)throw new Error(`Metadata block at position ${t} is too small! Corrupted file.`);y(i);const r=Ca(i),n=_a(i),s=0!==(128&r);switch(127&r){case zt.STREAMINFO:{let e=this.reader.requestSlice(t,n);if(e instanceof Promise&&(e=yield e),y(e),null===e)throw new Error(`StreamInfo block at position ${t} is too small! Corrupted file.`);const i=xa(e,34),r=new Ee(i),s=r.readBits(16),a=r.readBits(16),o=r.readBits(24),l=r.readBits(24),c=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:c,totalSamples:d,minimumBlockSize:s,maximumBlockSize:a,minimumFrameSize:o,maximumFrameSize:l,description:h},this.trackBacking=new jr(this);break}case zt.VORBIS_COMMENT:{let e=this.reader.requestSlice(t,n);e instanceof Promise&&(e=yield e),y(e),qt(xa(e,n),this.metadataTags);break}case zt.PICTURE:{let i=this.reader.requestSlice(t,n);i instanceof Promise&&(i=yield i),y(i);const r=Ra(i),s=Ra(i),a=I.decode(xa(i,s)),o=Ra(i),l=I.decode(xa(i,o));i.skip(16);const c=Ra(i),u=xa(i,c);null!=(e=this.metadataTags).images||(e.images=[]),this.metadataTags.images.push({data:u,mimeType:a,kind:3===r?"coverFront":4===r?"coverBack":"unknown",description:l});break}}if(t+=n,s){this.lastLoadedPos=t;break}}if(!this.audioInfo)throw new Error("Missing STREAMINFO metadata block! Corrupted FLAC file.")}))()})}readNextFlacFrame(e){return d(this,arguments,function*({startPos:e,isFirstPacket:t}){y(this.audioInfo);const i=this.audioInfo.maximumBlockSize*this.audioInfo.numberOfChannels*4+16+2,r=this.audioInfo.minimumFrameSize||10,n=(this.audioInfo.maximumFrameSize||i)+16,s=yield this.reader.requestSliceRange(e,16,n);if(!s)return null;const a=this.readFlacFrameHeader({slice:s,isFirstPacket:t});if(!a)return null;for(s.filePos=e+r;;){if(s.filePos>s.end-6)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(255===Ca(s)){const t=s.filePos;if(Ca(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-a.num!==1){s.filePos=t;continue}}else if(r.num-a.num!==a.blockSize){s.filePos=t;continue}return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:i,isLastFrame:!1}}}})}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=xa(e,4),n=new Ee(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){y(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){y(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");y(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*o(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?o(2,e):null)(n.readBits(4));if(!s)return null;y(this.audioInfo);const a=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(n.readBits(4),this.audioInfo.sampleRate);if(!a)return null;n.readBits(4),n.readBits(3);if(0!==n.readBits(1))return null;const l=(e=>{let t=0;const i=new Ee(xa(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Ee(xa(e,n)),a=8-t-1;for(let o=0;o<a;o++)r.unshift(i.readBits(1));for(let o=0;o<n;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?Ea(e)+1:"uncommon-u8"===t?Ca(e)+1:"number"===typeof t?t:(H(t),void y(!1)))(e,s),u=((e,t)=>"uncommon-u16"===t?Ea(e):"uncommon-u16-10"===t?10*Ea(e):"uncommon-u8"===t?Ca(e):"number"===typeof t?t:null)(e,a);if(null===u)return null;if(u!==this.audioInfo.sampleRate)return null;const d=e.filePos-i,h=Ca(e);e.skip(-d),e.skip(-1);const f=(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})(xa(e,d));return h!==f?null:{num:l,blockSize:c,sampleRate:u}}advanceReader(){return d(this,null,function*(){yield this.readMetadata(),y(null!==this.lastLoadedPos),y(this.audioInfo);const e=this.lastLoadedPos,t=yield 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 jr{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return Q}getTimeResolution(){return y(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return y(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}getDisposition(){return c({},Be)}getDecoderConfig(){return d(this,null,function*(){return y(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return d(this,null,function*(){if(y(this.demuxer.audioInfo),e<0)throw new Error("Timestamp cannot be negative");const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=z(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){yield this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],n=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(n+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);yield this.demuxer.advanceReader()}}finally{i()}})}getNextPacket(e,t){return d(this,null,function*(){const i=yield 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;)yield 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)}getPacketAtIndex(e,t){return d(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=Gt;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(e instanceof Promise&&(e=yield e),!e)return null;r=xa(e,i.byteSize)}y(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Yt(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return d(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Xr=9e4,$r=188,Qr="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.",Gr=new Set;class Yr extends Qt{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.reader=e._reader}readMetadata(){return d(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){let e=this.reader.requestSlice(0,205);e instanceof Promise&&(e=yield e),y(e);const t=xa(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=$r;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,n=!1,s=!1;for(;;){const e=yield this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}const t=yield this.readSection(i,!0,!s);if(!t)break;const a=3,o=32;let l=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new Ee(t.payload),i=e.readAlignedByte();e.skipBits(8*i);l=2===e.readBits(8)}}if(0!==t.pid||n)if(t.pid!==r&&!l||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=Zr(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=(yield 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 sn(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,yield 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=pt(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];y(t);const i=kt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const n=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;n>0&&s>0&&(n>s?(e.info.squarePixelWidth=Math.round(e.info.width*n/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/n))),e.info.colorSpace={primaries:B[i.colourPrimaries],transfer:_[i.transferCharacteristics],matrix:F[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=vt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===st.SPS_NUT).nalUnits[0];y(t);const i=St(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:B[i.colourPrimaries],transfer:_[i.transferCharacteristics],matrix:F[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:Ue({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}),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(yield 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=Pa.tempFromBytes(r.suppliedPacket.data),i=qr(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=Ae[i.channelConfiguration],e.info.sampleRate=_e[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Ra(Pa.tempFromBytes(r.suppliedPacket.data)),i=Ye(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=3===i.header.channel?1:2,e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Vt(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=Wt[t.acmod]+t.lfeon,e.info.sampleRate=tt[t.fscod]}else{if("eac3"!==e.info.codec)throw new Error("Unhandled.");{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=Xt(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=$t(t),e.info.sampleRate=i}}e.info.decoderConfig={codec:qe({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Ee(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 n=e.readBits(10);for(e.skipBits(8*n);8*(r+a)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),n=e.pos+8*r;let s=!1,a=!1;for(;e.pos<n;){const t=e.readBits(8),i=e.readBits(8);106===t?s=!0:122!==t&&204!==t||(a=!0),e.skipBits(8*i)}let o=null;switch(t){case 27:case 36:o={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:{let e;if(3===t||4===t)e="mp3";else if(15===t)e="aac";else if(129===t)e="ac3";else{if(135!==t)throw new Error("Unreachable.");e="eac3"}o={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:a?o={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1}:s&&(o={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,numberOfChannels:-1,sampleRate:-1});break;default:Gr.has(t)||(console.warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Gr.add(t))}o&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:o,referencePesPackets:[]})}s=!0}else{const e=new Ee(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+a)-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.");n=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!n)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const a of this.elementaryStreams)"video"===a.info.type?this.trackBackingEntries.push(new tn(a)):this.trackBackingEntries.push(new rn(a))}))()})}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){yield this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(yield Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null}))))})}readSection(e,t,i=!1){return d(this,null,function*(){let r=e,n=e;const s=[];let a,o=0,l=null,c=!0,u=0;for(;;){const e=yield this.readPacket(n);if(n+=this.packetStride,!e)break;if(l){if(e.pid!==l.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;l=e}const a=!!(2&e.adaptationFieldControl),d=!!(1&e.adaptationFieldControl);let h=0;if(a&&(h=1+e.body[0],e===l&&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=n,!t&&o>=64){c=!1;break}if(-1!==L(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=z(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!l)return null;if(1===s.length)a=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);a=new Uint8Array(e);let t=0;for(const i of s)a.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:l.pid,payload:a,randomAccessIndicator:u}})}readPacketHeader(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,4);if(t instanceof Promise&&(t=yield t),!t)return null;if(71!==Ca(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Ea(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:Ca(t)>>4&3}})}readPacket(e){return d(this,null,function*(){let t=this.reader.requestSlice(e,$r);if(t instanceof Promise&&(t=yield t),!t)return null;const i=xa(t,$r);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)}})}}const Jr=(e,t)=>{if(e.payload.byteLength<3)return null;const i=new Ee(e.payload);if(1!==i.readBits(24))return null;const r=i.readBits(8);if(i.skipBits(16),188===r||190===r||191===r||240===r||241===r||255===r||242===r||248===r)return null;i.skipBits(8);const n=i.readBits(2);i.skipBits(14);let s=null;if(2===n||3===n)s=0,i.skipBits(4),s+=i.readBits(3)*(1<<30),i.skipBits(1),s+=32768*i.readBits(15),i.skipBits(1),s+=i.readBits(15);else if(t)throw new Error(Qr);return{sectionStartPos:e.startPos,sectionEndPos:e.endPos,pts:s,randomAccessIndicator:e.randomAccessIndicator}},Zr=(e,t)=>{y(null!==e.endPos);const i=Jr(e,t);if(!i)return null;const r=new Ee(e.payload);r.skipBits(32);const n=r.readBits(16);r.skipBits(16);const s=r.readBits(8),a=r.pos+8*s;r.pos=a;const o=a/8;y(Number.isInteger(o));const l=e.payload.subarray(o,n>0?6+n:e.payload.byteLength);return u(c({},i),{data:l})};class en{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++,y(r instanceof en),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 Q}getDisposition(){return u(c({},Be),{primary:!1})}getTimeResolution(){return Xr}isRelativeToUnixEpoch(){return!1}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return d(this,null,function*(){return null})}getLiveRefreshInterval(){return d(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Yt(i.metadataOnly?Gt:e.data,r,e.pts/Xr,Math.max(t/Xr,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return d(this,null,function*(){const t=this.elementaryStream.firstSection;y(t);const i=Zr(t,!0);y(i);const r=new sn(this.elementaryStream,i),n=new an(this,r),s=yield n.readNext();if(!s)return null;const a=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(a,n),this.packetSectionStarts.set(a,s.packet.sectionStartPos),a})}getNextPacket(e,t){return d(this,null,function*(){let i=this.packetBuffers.get(e);if(i){const r=yield i.readNext();if(!r)return null;this.packetBuffers.delete(e);const n=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(n,i),this.packetSectionStarts.set(n,r.packet.sectionStartPos),n}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const n=this.elementaryStream.demuxer,s=yield n.readSection(r,!0);y(s);const a=Zr(s,!0);y(a);const o=new sn(this.elementaryStream,a);i=new an(this,o);const l=e.sequenceNumber;for(;;){const e=yield i.readNext();if(!e)return null;if(e.packet.sequenceNumber>l){const r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}})}getNextKeyPacket(e,t){return d(this,null,function*(){let i=e;for(;;){if(i=yield 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)}doPacketLookup(e,t,i){return d(this,null,function*(){var r,n,s,a,o,l;const c=G(e*Xr),u=this.elementaryStream.demuxer,{reader:h,seekChunkSize:f}=u,m=this.elementaryStream.pid,p=(e,t,i)=>d(this,null,function*(){let r=e;for(;r<t;){const e=yield u.readPacketHeader(r);if(!e)return null;if(e.pid===m&&1===e.payloadUnitStartIndicator){const e=yield u.readSection(r,i);if(!e)return null;const t=Jr(e,!1);if(t&&null!==t.pts)return{pesPacketHeader:t,section:e}}r+=u.packetStride}return null}),g=this.elementaryStream.firstSection;y(g);const k=Jr(g,!0);if(y(k),c<k.pts)return null;let b;const S=this.elementaryStream.referencePesPackets,v=z(S,c,e=>e.pts),w=-1!==v?S[v]:null;if(w&&c-w.pts<45e3)b=w.sectionStartPos;else{let e=0;if(null!==h.fileSize){const t=Math.ceil(h.fileSize/f);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=J(t*f,u.packetStride)+k.sectionStartPos,s=n+f,a=yield p(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}b=J(e*f,u.packetStride)+k.sectionStartPos}const P=yield p(b,null!=(r=h.fileSize)?r:1/0,!1);let I=null!=(n=null==P?void 0:P.pesPacketHeader)?n:null;I||(I=k);const x=this.getReorderSize(),C=(e,t)=>d(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);y(s);const a=Zr(s,!0);y(a);const o=new sn(this.elementaryStream,a),l=new an(this,o);for(;;){if((null!=(n=null==(r=T(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=V(l.presentationOrderPackets,t);if(-1===d)return null;const h=l.presentationOrderPackets[d],f=0===d?0:h.pts-l.presentationOrderPackets[d-1].pts;for(;l.decodeOrderPackets[0]!==h;)l.decodeOrderPackets.shift();l.lastDuration=f;const m=yield l.readNext();y(m);const p=this.createEncodedPacket(m.packet,m.duration,i);return this.packetBuffers.set(p,l),this.packetSectionStarts.set(p,m.packet.sectionStartPos),p});if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=I.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;I=e,nn(this.elementaryStream,I);break}}}e+=u.packetStride}}e:for(let e=0;e<x+1;e++){let e=I.sectionStartPos-u.packetStride;for(;e>=u.packetOffset;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){I=e;break}}}e-=u.packetStride}}return C(I.sectionStartPos,e=>e.pts<=c)}{let e=b,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=k.sectionStartPos;let d,b=null;if(n)d=k,b=g;else{const t=yield p(e,null!=(s=h.fileSize)?s:1/0,i);d=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,b=null!=(o=null==t?void 0:t.section)?o:null}let T=!1,S=0;e:for(;d&&!(null!==t&&d.sectionStartPos>=t);){if(d.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===d.randomAccessIndicator;else{y(b);const t=Zr(b,!0);y(t);const i=new sn(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=d)}if(d.pts>c&&(T=!0),T&&(S++,S>x))break;let e=d.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===m&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Jr(t,!1);if(e&&null!==e.pts){d=e,b=t,nn(this.elementaryStream,d);break}}}e+=u.packetStride}}if(r){let e=r;if(0===S)e:for(let r=0;r<x;r++){let t=e.sectionStartPos-u.packetStride;for(;t>=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===m&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Jr(r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield C(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return y(t),t}if(n)return null;t=e,e=Math.max(J(e-k.sectionStartPos-f,u.packetStride)+k.sectionStartPos,k.sectionStartPos)}}})}}class tn extends en{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}getColorSpace(){return d(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return d(this,null,function*(){return!1})}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class rn extends en{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return d(this,null,function*(){return y(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const nn=(e,t)=>{const i=e.referencePesPackets,r=z(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const n=i[r];if(t.pts<=n.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-n.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 sn{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 y(e),e}bufferData(e){return d(this,null,function*(){const t=this.endPos+e;for(;this.endPos<t;){let e;if(0===this.pesPackets.length)e=this.startingPesPacket;else{let t=T(this.pesPackets).sectionEndPos;for(y(null!==t);;){const i=yield this.demuxer.readPacketHeader(t);if(!i)return;if(i.pid===this.pid){const i=yield this.demuxer.readSection(t,!0);if(!i)return;const r=Zr(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 n=new Uint8Array(e);n.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){n.set(t.data.subarray(0,i),s);break}n.set(t.data,s),s+=t.data.byteLength}return n}readU8(){let e=this.getCurrentPesPacket();const t=this.currentPos-this.currentPesPacketPos;return this.currentPos++,t<e.data.byteLength?e.data[t]:(this.advanceCurrentPacket(),e=this.getCurrentPesPacket(),e.data[0])}seekTo(e){if(e!==this.currentPos){if(e<this.currentPos)for(;e<this.currentPesPacketPos;){this.currentPesPacketIndex--;const 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++}markNextPacket(){return d(this,null,function*(){y(!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.");let r=null;for(;;){let e=this.ensureBuffered(i);if(e instanceof Promise&&(e=yield e),0===e)break;const n=this.currentPos,s=this.readBytes(e),a=s.byteLength;let o=0;for(;o<a;){const e=s.indexOf(0,o);if(-1===e||e>=a)break;o=e;const i=n+o;if(o+4>=a){this.seekTo(i);break}const l=s[o+1],c=s[o+2],u=s[o+3];let d=0,h=null;if(0===l&&0===c&&1===u?(d=4,h=s[o+4]):0===l&&1===c&&(d=3,h=u),0===d){o++;continue}const f=i;if(null!==r){if(null!==h){const e="avc"===t?ut(h):Tt(h);if("avc"===t?e===rt.AUD:e===st.AUD_NUT){const e=f-r;return this.seekTo(r),this.supplyPacket(e,0)}}o+=d}else r=f,o+=d}if(e<i)break}if(null!==r){const e=this.endPos-r;return this.seekTo(r),this.supplyPacket(e,0)}}else{const t=e.info.codec,i=128;for(;;){let r=this.ensureBuffered(i);r instanceof Promise&&(r=yield r);const n=this.currentPos;for(;this.currentPos-n<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(r instanceof Promise&&(r=yield r),r<9)return;const n=this.readBytes(9),s=qr(Pa.tempFromBytes(n));if(s){this.seekTo(t);let i=this.ensureBuffered(s.frameLength);return i instanceof Promise&&(i=yield 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(r instanceof Promise&&(r=yield r),r<5)return;const n=this.readBytes(5);if(11!==n[0]||119!==n[1]){this.seekTo(t+1);continue}const s=n[4]>>6,a=63&n[4];if(3===s||a>37){this.seekTo(t+1);continue}const o=Ht[3*a+s];y(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),r instanceof Promise&&(r=yield r);const l=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,l)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(r instanceof Promise&&(r=yield r),r<5)return;const n=this.readBytes(5);if(11!==n[0]||119!==n[1]){this.seekTo(t+1);continue}const s=2*(((7&n[2])<<8|n[3])+1),a=3===n[4]>>6?3:n[4]>>4&3,o=Kt[a];this.seekTo(t),r=this.ensureBuffered(s),r instanceof Promise&&(r=yield r);const l=256*o,c=Math.round(l*Xr/e.info.sampleRate);return this.supplyPacket(r,c)}throw new Error("Unhandled.")}{if(255!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(4);if(r instanceof Promise&&(r=yield r),r<4)return;const n=this.readBytes(4),s=P(n).getUint32(0),a=Ye(s,null);if(a.header){this.seekTo(t);let i=this.ensureBuffered(a.header.totalSize);i instanceof Promise&&(i=yield i);const r=a.header.audioSamplesInFrame*Xr/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)y(null!==this.nextPts),r=this.nextPts;else{if(null===i.pts)throw new Error(Qr);r=i.pts,nn(this.elementaryStream,i)}this.lastSuppliedPesPacket=i,this.nextPts=r+t;const n=i.sectionStartPos,s=n+(this.currentPos-this.currentPesPacketPos),a=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"===Lt(this.elementaryStream.info.codec,this.elementaryStream.info.decoderConfig,a);o=Number(e)}this.suppliedPacket={pts:r,data:a,sequenceNumber:s,sectionStartPos:n,randomAccessIndicator:o},this.pesPackets.splice(0,this.currentPesPacketIndex),this.currentPesPacketIndex=0}}class an{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(),y(this.reorderSize>=0)}readNext(){return d(this,null,function*(){if(0===this.decodeOrderPackets.length){if(!(yield this.readNextPacket()))return null}yield this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(y(-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}})}readNextPacket(){return d(this,null,function*(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||(yield 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)})}ensureCurrentPacketHasNext(){return d(this,null,function*(){const e=this.decodeOrderPackets[0];for(y(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(yield 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 on="application/vnd.apple.mpegurl",ln="#EXT-X-STREAM-INF:",cn="#EXT-X-I-FRAME-STREAM-INF:",un="#EXT-X-MEDIA:",dn="#EXTINF:",hn="#EXT-X-MAP:",fn="#EXT-X-KEY:",mn="#EXT-X-MEDIA-SEQUENCE:",pn="#EXT-X-BYTERANGE:",gn="#EXT-X-PROGRAM-DATE-TIME:",kn="#EXT-X-TARGETDURATION:",yn="#EXT-X-PLAYLIST-TYPE:",bn=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Tn{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;s<e.length;s++){const a=e[s];'"'===a?n=!n:"="!==a||r||n?","!==a||n?r?i+=a:t+=a:(t&&(this._attributes[t.trim().toLowerCase()]=i),t="",i="",r=!1):r=!0}t&&(this._attributes[t.trim().toLowerCase()]=i)}get(e){var t;return null!=(t=this._attributes[e.toLowerCase()])?t: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 Sn{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}getDurationFromMetadata(e){return d(this,null,function*(){const t=yield this.getSegmentAt(1/0,{skipLiveWait:e.skipLiveWait});return t?t.timestamp+t.duration:null})}getTrackBackings(){return d(this,null,function*(){var e;return null!=(e=this.trackBackingsPromise)?e:this.trackBackingsPromise=(()=>d(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=Te(e,e=>"video"===e.getType())+1;e.push(new wn(this,t,i))}else if("audio"===t.type){const i=Te(e,e=>"audio"===e.getType())+1;e.push(new Pn(this,t,i))}}else{if(this.firstSegment=yield this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=yield t.getTracks();for(const r of i)if("video"===r.type){const t=Te(e,e=>"video"===e.getType())+1;e.push(new wn(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=Te(e,e=>"audio"===e.getType())+1;e.push(new Pn(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return d(this,null,function*(){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=yield e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i})}getMediaOffset(e,t){return d(this,null,function*(){var i;const r=null!=(i=e.firstSegment)?i:e;let n;if(this.firstSegmentFirstTimestamps.has(r))n=this.firstSegmentFirstTimestamps.get(r);else{const e=this.getInputForSegment(r);n=yield this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(r,n)}if(r===e)return r.timestamp-n;const s=yield this.getFirstTimestampForInput(t),a=e.timestamp-r.timestamp,o=s-n-a;return Math.abs(o)<=Math.min(.25,a)?r.timestamp-n:e.timestamp-s})}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class vn{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){var e;if(null!=(e=this.segmentedInput).firstSegment||(e.firstSegment=yield this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");const t=this.segmentedInput.getInputForSegment(this.segmentedInput.firstSegment),i=(yield t.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number);if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i}))()}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}getHasOnlyKeyPackets(){return this.delegate(()=>{var e,t,i;return null!=(i=null==(t=(e=this.firstInputTrack._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:null})}getPairingMask(){return BigInt("1")}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())}isRelativeToUnixEpoch(){return d(this,null,function*(){return yield this.hydrate(),y(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.relativeToUnixEpoch})}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return d(this,null,function*(){y(e.sequenceNumber>=0),y(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:Y(e.timestamp+r,yield i.getTimeResolution()),sequenceNumber:Math.floor(1e8*n)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s})}getFirstPacket(e){return d(this,null,function*(){yield this.hydrate(),y(this.segmentedInput.firstSegment),y(this.firstInputTrack);const t=yield this.firstInputTrack._backing.getFirstPacket(e);return t?this.createAdjustedPacket(t,this.segmentedInput.firstSegment,this.firstInputTrack):null})}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}_getNextInternal(e,t,i){return d(this,null,function*(){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const n=i?yield r.track._backing.getNextKeyPacket(r.sourcePacket,t):yield r.track._backing.getNextPacket(r.sourcePacket,t);if(n)return this.createAdjustedPacket(n,r.segment,r.track);let s=r.segment;for(;;){const e=yield this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),n=(yield i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!n){s=e;continue}const a=yield n._backing.getFirstPacket(t);return a?this.createAdjustedPacket(a,e,n):null}})}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}_getPacketInternal(e,t,i){return d(this,null,function*(){let r=yield this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(yield this.hydrate();r;){const n=this.segmentedInput.getInputForSegment(r),s=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const a=yield this.segmentedInput.getMediaOffset(r,n),o=e-a,l=i?yield s._backing.getKeyPacket(o,t):yield s._backing.getPacket(o,t);if(l)return this.createAdjustedPacket(l,r,s);r=yield this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null})}}class wn extends vn{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())}getColorSpace(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class Pn extends vn{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())}getDecoderConfig(){return d(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}ke();const In=1/0;class xn extends Ie{constructor(){super(...arguments),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._sizePromise=null,this.onread=null}getSizeOrNull(){return d(this,null,function*(){var e;if(this._disposed)throw new va;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>d(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,In),e=this._getFileSize(),y(void 0!==e)),e}))()})}getSize(){return d(this,null,function*(){if(this._disposed)throw new va;const e=yield 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 zn(this,e,t)}_dispatchRead(e,t){var i;null==(i=this.onread)||i.call(this,e,t),this._emit("read",{start:e,end:t})}ref(){return new Cn(this)}}class Cn{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._refCount++,this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;y(e._refCount>0),e._refCount--,0===e._refCount&&(e._dispose(),e._disposed=!0),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class Bn extends xn{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 xn||e instanceof Cn))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof xn?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return t instanceof Promise?t.then(i):i(t)}}const En=(e,t)=>e.path===t.path;class _n extends Bn{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 xn?e.ref():e;return this._root=t,this._rootRequest=null,t};e instanceof Promise?this._rootRequest=e.then(t):(t(e),y(this._root))}if(this._rootRequest)return this._rootRequest.then(n=>n.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}class An extends xn{constructor(e,t={}){var i;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&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._readers=new WeakMap,this._blob=e,this._orchestrator=new Ln({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*o(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),prefetchProfile:On.fileSystem}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return d(this,null,function*(){y(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!oe()){t=this._blob.slice(e.currentPos).stream().getReader()}else t=null;this._readers.set(e,t)}for(;e.currentPos<e.targetPos&&!e.aborted;)if(t){const{done:i,value:r}=yield 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=yield 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&&(yield null==t?void 0:t.cancel())})}_dispose(){this._orchestrator.dispose()}}const Fn=.5*o(2,20),Rn=(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"))){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(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return console.warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(o(2,e-2),16)},Dn=new Set;class Mn extends Bn{constructor(e,t={}){var i,r,n;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&&(!ye(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.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new Mn(e.path,this._options)),this._fileSizeDetermined=!1,this._url=e,this._options=t,this._getRetryDelay=null!=(i=t.getRetryDelay)?i:Rn;this._orchestrator=new Ln({maxCacheSize:null!=(r=t.maxCacheSize)?r:64*o(2,20),maxWorkerCount:null!=(n=t.parallelism)?n:2,runWorker:this._runWorker.bind(this),prefetchProfile:On.network})}_getFileSize(){return this._fileSizeDetermined?this._orchestrator.fileSize:void 0}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return d(this,null,function*(){for(var t,i;;){const n=new AbortController,s=yield ne(null!=(t=this._options.fetchFn)?t:fetch,this._url,ie(null!=(i=this._options.requestInit)?i:{},{headers:{Range:`bytes=${e.currentPos}-`},signal:n.signal}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);e:if(null===this._orchestrator.fileSize){const t=s.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=s.headers.get("Content-Length");i&&this._orchestrator.supplyFileSize(e.currentPos+Number(i))}if(this._fileSizeDetermined=!0,206!==s.status){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")||Dn.has(e.origin)||(console.log(this._usedForHls,this._url,e.pathname),console.warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the entire resource will now be downloaded. To enable efficient media file streaming across a network, please make sure your server supports range requests.`),Dn.add(e.origin))}e.currentPos=0,this._orchestrator.options.maxCacheSize=1/0,null!==this._orchestrator.fileSize?e.targetPos=this._orchestrator.fileSize:(e.targetPos=1/0,e.strictTarget=!1),this._orchestrator.consolidateEverythingIntoOneWorker(e)}if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");const a=s.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return n.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let t;try{t=yield a.read()}catch(r){if(this._disposed)throw r;const e=this._getRetryDelay(1,r,this._url);if(null!==e){console.error("Error while reading response stream. Attempting to resume.",r),yield Pe(1e3*e);break}throw r}if(e.aborted)continue;const{done:i,value:s}=t;if(i){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+s.length),this._orchestrator.supplyWorkerData(e,s)}}})}_dispose(){this._orchestrator.dispose()}}class Nn extends xn{constructor(e,t={}){var i;if(!(e instanceof ReadableStream))throw new TypeError("stream must be a ReadableStream.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!ye(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");super(),this._reader=null,this._cache=[],this._pendingSlices=[],this._currentIndex=0,this._targetIndex=0,this._maxRequestedIndex=0,this._endIndex=null,this._pulling=!1,this._stream=e,this._maxCacheSize=null!=(i=t.maxCacheSize)?i:16*o(2,20)}_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 n=e;const s=new Uint8Array(t-e);if(-1!==i)for(let c=i;c<this._cache.length;c++){const i=this._cache[c];if(i.start>=t)break;const r=Math.max(e,i.start);r>n&&this._throwDueToCacheMiss();const a=Math.min(t,i.end);r<a&&(s.set(i.bytes.subarray(r-i.start,a-i.start),r-e),n=a)}if(n===t)return{bytes:s,view:P(s),offset:e};this._currentIndex>n&&this._throwDueToCacheMiss();const{promise:a,resolve:o,reject:l}=q();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:l}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,!(this._pendingSlices.length>0))throw e;this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0})),a}_throwDueToCacheMiss(){throw new Error("Read is before the cached region. With ReadableStreamSource, you must access the data more sequentially or increase the size of its cache.")}_pull(){return d(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._currentIndex<this._targetIndex&&!this._disposed;){const{done:e,value:t}=yield 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;for(let n=0;n<this._pendingSlices.length;n++){const e=this._pendingSlices[n],s=Math.max(i,e.start),a=Math.min(r,e.end);s<a&&(e.bytes.set(t.subarray(s-i,a-i),s-e.start),a===e.end&&(e.resolve({bytes:e.bytes,view:P(e.bytes),offset:e.start}),this._pendingSlices.splice(n,1),n--))}for(this._cache.push({start:i,end:r,bytes:t,view:P(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(){var e;this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const On={fileSystem:(e,t)=>{const i=o(2,16);return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=o(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*o(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(pe(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=o(2,Math.ceil(Math.log2(e+1))),a=Math.min(s,r);t=Math.max(t,n.startPos+a)}}return{start:e,end:t=Math.max(t,e+Fn)}}};class Ln{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){var n;y(!this.disposed);const s=this.options.prefetchProfile(e,t,this.workers),a=Math.max(s.start,i),o=Math.min(s.end,null!=(n=this.fileSize)?n:1/0,r);y(a<=e&&t<=o);let l=null;const c=z(this.cache,e,e=>e.start),u=-1!==c?this.cache[c]:null;u&&u.start<=e&&t<=u.end&&(u.age=this.nextAge++,l={bytes:u.bytes,view:u.view,offset:u.start});const d=z(this.cache,a,e=>e.start),h=l?null:new Uint8Array(t-e);let f=0,m=a;const p=[];if(-1!==d){for(let i=d;i<this.cache.length;i++){const r=this.cache[i];if(r.start>=o)break;if(r.end<=a)continue;const n=Math.max(a,r.start),s=Math.min(o,r.end);if(y(n<=s),m<n&&p.push({start:m,end:n}),m=s,h){const i=Math.max(e,r.start),n=Math.min(t,r.end);if(i<n){const t=i-e;h.set(r.bytes.subarray(i-r.start,n-r.start),t),t===f&&(f=n-e)}}r.age=this.nextAge++}m<o&&p.push({start:m,end:o})}else p.push({start:a,end:o});if(h&&f>=h.length&&(l={bytes:h,view:P(h),offset:e}),0===p.length)return y(l),l;const{promise:g,resolve:k,reject:b}=q(),T=[];for(const y of p){const i=Math.max(e,y.start),r=Math.min(t,y.end);i===y.start&&r===y.end?T.push(y):i<r&&T.push({start:i,end:r})}const S=h&&{start:e,bytes:h,holes:T,resolve:k,reject:b};e:for(const y of p){for(const i of this.workers){if(this.checkHoleAgainstWorker(i,y,S?[S]:[])){this.checkQueuedReadsAgainstWorker(i);continue e}}const e=y.end<o||null!==this.fileSize,t=this.createWorker(y.start,y.end,e);if(t)S&&(t.pendingSlices=[S]),this.runWorker(t);else{let t=z(this.queuedReads,y.start,e=>e.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&y.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,y.end),i.strictTarget&&(i.strictTarget=e),S&&i.pendingSlices.push(S)):(t++,i={hole:{start:y.start,end:y.end},strictTarget:e,pendingSlices:S?[S]:[],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 l||(y(h),l=g.then(t=>t&&{bytes:t,view:P(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=o(2,17);if(pe(t.start-r,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;y(null!==t),y(0===e.pendingSlices.length),this.workers.splice(t,1)}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){y(!e.running),y(e.currentPos<e.targetPos),e.running=!0,e.age=this.nextAge++,this.options.runWorker(e).catch(t=>{if(e.running=!1,!(e.pendingSlices.length>0))throw t;e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0}).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];this.queuedReads.splice(e,1);const i=this.createWorker(t.hole.start,t.hole.end,t.strictTarget);y(i),i.pendingSlices=t.pendingSlices,this.runWorker(i)}})}consolidateEverythingIntoOneWorker(e){const t=new Set(e.pendingSlices);for(let i=0;i<this.workers.length;i++){const r=this.workers[i];if(r!==e){for(const e of r.pendingSlices)t.add(e);r.aborted=!0,r.pendingSlices.length=0,this.workers.splice(i,1),i--}}for(let i=0;i<this.queuedReads.length;i++){const e=this.queuedReads[i];for(const i of e.pendingSlices)t.add(i)}e.pendingSlices=[...t],this.queuedReads.length=0}supplyWorkerData(e,t){y(!e.aborted);const i=e.currentPos,r=i+t.length;this.insertIntoCache({start:i,end:r,bytes:t,view:P(t),age:this.nextAge++}),e.currentPos+=t.length,e.currentPos>e.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let n=0;n<e.pendingSlices.length;n++){const s=e.pendingSlices[n],a=Math.max(i,s.start),o=Math.min(r,s.start+s.bytes.length);a<o&&s.bytes.set(t.subarray(a-i,o-i),a-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(n,1),n--)}for(let n=0;n<this.workers.length;n++){const t=this.workers[n];e===t||t.running||pe(i,r,t.currentPos,t.targetPos)&&(this.workers.splice(n,1),n--)}}supplyFileSize(e){y(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 n of r.holes)if(n.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.pendingSlices.length=0}onWorkerFinished(e){const t=this.workers.indexOf(e);y(-1!==t),e.running=!1,this.workers.splice(t,1),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=P(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=P(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)e.aborted=!0;this.workers.length=0,this.cache.length=0,this.disposed=!0}}class zn extends xn{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=null!=i?i:null}_getFileSize(){var e;const t=this._baseSource._getFileSize();return void 0===t?null!==this._length?this._length:void 0:null===t?null!==this._length?this._length:null:$(t-this._offset,0,null!=(e=this._length)?e:1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r);return n instanceof Promise?n.then(e=>e?(e.offset-=this._offset,e):null):n?(n.offset-=this._offset,n):null}_dispose(){var e;null==(e=this._ref)||e.free()}ref(){return null!=this._ref||(this._ref=this._baseSource.ref()),super.ref()}}var Un=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,n;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&&(n=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");n&&(r=function(){try{n.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},qn=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,n=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===n)return n=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return n|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else n|=1}catch(a){i(a)}if(1===n)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 Wn=/^0[xX][0-9a-fA-F]+$/,Vn=/^data:.*;base64,/i;class Hn extends Sn{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.demuxer=e,this.nextLines=r}runUpdateSegments(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>d(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Pe(e)),this.lastSegmentUpdateTime=performance.now(),yield 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}updateSegments(){return d(this,null,function*(){var e,t,i,r,n,s,a;let l=this.nextLines;if(this.nextLines=null,!l){const e={stack:[],error:void 0,hasError:!1};try{const t=Un(e,yield this.demuxer.input._getSourceUncached({path:this.path,isRoot:!1}),!1),i=new wa(t.source),r=yield i.requestEntireFile();y(r),l=Va(r,r.length,{ignore:bn})}catch(E){e.error=E,e.hasError=!0}finally{qn(e)}}let d=!1,h=0,f=null,m=null,p=0,g=null,k=null,b=null,S=null,v=null,w=null,I=!1,x=null!=(e=T(this.segments))?e:null;const C=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}},B=e=>{p=e,x&&(y(null!==x.sequenceNumber),x.sequenceNumber<e&&(h=x.timestamp+x.duration,g=x.firstSegment,k=x.initSegment,v=x.lastProgramDateTimeSeconds,x=null))};for(let y=0;y<l.length;y++){const e=l[y];if(d){if(!e.startsWith("#")){if(!x){if(null===f)throw new Error("Invalid M3U8 file; a segment must be preceded by an #EXTINF tag.");let r=m;if(r&&"AES-128"===r.method&&!r.iv){const e=new Uint8Array(ai),t=P(e);t.setUint32(8,Math.floor(p/o(2,32))),t.setUint32(12,p),r=u(c({},r),{iv:e})}const n={path:be(this.path,e),offset:null!=(t=null==S?void 0:S.offset)?t:0,length:null!=(i=null==S?void 0:S.length)?i:null},s={timestamp:h,relativeToUnixEpoch:null!==v,firstSegment:g,sequenceNumber:p,location:n,duration:f,encryption:r,initSegment:k,lastProgramDateTimeSeconds:v};null!=g||(g=s),h+=f,this.segments.push(s)}f=null,null===S?b=null:S=null,B(p+1)}if(e.startsWith(dn)){if(x){I=!0;continue}I||(null===v&&p>0&&null!==w&&(h=p*w),I=!0);const t=e.slice(8),i=t.indexOf(","),r=-1===i?t:t.slice(0,i),n=Number(r);if(!Number.isFinite(n)||n<0)throw new Error(`Invalid #EXTINF tag duration '${r}'.`);f=n}else if(e.startsWith(hn)){const t=new Tn(e.slice(11)),i=t.get("uri");if(!i)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const s=t.get("byterange");let a=null;if(null!==s&&(a=C(s)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!x){const e={path:be(this.path,i),offset:null!=(r=null==a?void 0:a.offset)?r:0,length:null!=(n=null==a?void 0:a.length)?n:null};if("AES-128"===(null==m?void 0:m.method)&&!m.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");k={timestamp:h,relativeToUnixEpoch:null!==v,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:m,initSegment:null,lastProgramDateTimeSeconds:v}}f=null,null===S?b=null:S=null}else if(e.startsWith(fn)){const t=new Tn(e.slice(11)),i=t.get("method");if("NONE"===i)m=null;else if("AES-128"===i){const e=t.get("uri");if(!e)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=t.get("iv");if(r){if(!Wn.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(ai);for(let t=0;t<ai;t++){const r=-32+t;i[t]=parseInt(e.slice(r,r+2),16)}}const n=null!=(s=t.get("keyformat"))?s:"identity";if("identity"!==n)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.");m={method:"AES-128",keyUri:be(this.path,e),iv:i,keyFormat:n}}else{if("SAMPLE-AES"!==i&&"SAMPLE-AES-CTR"!==i)throw new Error(`Unsupported encryption method '${i}'. If you think this method should be supported, please raise an issue.`);{const e=t.get("uri");if(!e)throw new Error(`Invalid #EXT-X-KEY: ${i} requires a URI attribute.`);if("identity"===(null!=(a=t.get("keyformat"))?a:"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(Vn.test(e)){const t=e.indexOf(","),i=ge(e.slice(t+1));if(i.length>=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=P(i).getUint32(0);r=Jt(i.subarray(8,Math.min(e,i.length)))}}m={method:i,psshBox:r}}}}else if(e.startsWith(mn)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);B(i)}else if(e.startsWith(pn)){const t=C(e.slice(17));if(null===t.offset){if(null===b)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=b}S=t,b=t.offset+t.length}else if(e.startsWith(gn)){if(x)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(v===r)continue;if(null===v&&this.segments.length>0){const e=T(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.timestamp+=t,i.relativeToUnixEpoch=!0;h+=t}v=r,h=r}else if("#EXT-X-DISCONTINUITY"===e)g=null;else if(e.startsWith(kn)){const t=e.slice(22),i=Number(t);if(!Number.isFinite(i)||i<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${t}'.`);this.refreshInterval=i,w=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(yn)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");d=!0}}if(!d)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return d(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return d(this,null,function*(){0===this.segments.length&&(yield 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 n=this.segments[r];if(e<n.timestamp+n.duration)return n;yield this.runUpdateSegments(),t.skipLiveWait&&(i=!0)}})}getNextSegment(e,t){return d(this,null,function*(){const i=this.segments.indexOf(e);y(-1!==i);const r=i+1;let n=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){if(r<this.segments.length)return this.segments[r];if(this.streamHasEnded||n)return null;yield this.runUpdateSegments(),t.skipLiveWait&&(n=!0)}})}getPreviousSegment(e){return d(this,null,function*(){var t;const i=this.segments.indexOf(e);return y(-1!==i),null!=(t=this.segments[i-1])?t:null})}getInputForSegment(e){var t,i;const r=e,n=this.inputCache.find(e=>e.segment===r);if(n)return n.age=this.nextInputCacheAge++,n.input;let s=null;(r.initSegment||r.firstSegment)&&(s=this.getInputForSegment(null!=(t=r.initSegment)?t:r.firstSegment));const a=u(c({},this.input._formatOptions),{isobmff:u(c({},this.input._formatOptions.isobmff),{resolveKeyId:(null==(i=this.input._formatOptions.isobmff)?void 0:i.resolveKeyId)&&(e=>{if(!r.encryption||"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method||!r.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let t=e.psshBoxes;const{psshBox:i}=r.encryption;return null!==i.keyIds&&!i.keyIds.includes(e.keyId)||t.some(e=>Zt(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(u(c({},e),{psshBoxes:t}))})})}),l=new Ta({source:new _n(r.location.path,e=>d(this,null,function*(){var t,i;y(e.isRoot);const n=u(c({},e),{isRoot:!1});let s;const a=r.location.offset>0||null!==r.location.length;if(r.encryption&&"SAMPLE-AES"!==r.encryption.method&&"SAMPLE-AES-CTR"!==r.encryption.method)if("AES-128"===r.encryption.method){const e=r.encryption;y(e.iv);let t=yield this.input._getSourceCached(n);if(a){const e=t.source.slice(r.location.offset,null!=(i=r.location.length)?i:void 0).ref();t.free(),t=e}const l=((e,t,i)=>{let r=!1,n=0;const s=o(2,16),a=new pi;return new ReadableStream({pull:o=>d(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(c instanceof Promise&&(c=yield c),!c||0===c.length)throw new Error("Invalid ciphertext.");const u=c.length;if(u%16!==0)throw new Error("Invalid ciphertext.");const d=u===l?u-16:u,h=xa(c,d),f=new Uint8Array(d);for(let e=0;e<d;e+=16)a.in.set(h.subarray(e,e+16)),a.decrypt(),f.set(a.out,e);if(d<u)o.enqueue(f),n+=d;else{const e=f[d-1];if(0===e||e>16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=f.subarray(0,d-e);o.enqueue(t),o.close(),i()}}),cancel:()=>{i()}})})(new wa(t.source),()=>d(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=Un(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},ya),!1),r=new wa(i.source),n=yield r.requestSlice(0,ai);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:xa(n,ai),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{qn(t)}}),()=>{t.free()});s=new Nn(l).ref()}else y(!1);else if(s=yield this.input._getSourceCached(n),a){const e=s.source.slice(r.location.offset,null!=(t=r.location.length)?t:void 0).ref();s.free(),s=e}return s})),formats:this.input._formats.filter(e=>!(e instanceof us)),initInput:null!=s?s:void 0,formatOptions:a});l._onFormatDetermined=e=>{var t,i;if(("SAMPLE-AES"===(null==(t=r.encryption)?void 0:t.method)||"SAMPLE-AES-CTR"===(null==(i=r.encryption)?void 0:i.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:r,input:l,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=Se(this.inputCache,e=>e.age);y(-1!==e),this.inputCache.splice(e,1)}return l}getLiveRefreshInterval(){return d(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class Kn extends Qt{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>d(this,null,function*(){y(this.input._rootSource instanceof Bn);const{rootPath:e}=this.input._rootSource,t=yield this.input._reader.requestEntireFile();y(t);const i=Va(t,t.length,{ignore:bn}),r=[],n=[];for(let u=1;u<i.length;u++){const t=i[u];if(t.startsWith(ln)){const n=u,s=i[++u];if(void 0===s)throw new Error("Incorrect M3U8 file; a line must follow the #EXT-X-STREAM-INF tag.");const a=be(e,s),o=new Tn(t.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:a,attributes:o,lineNumber:n,hasOnlyKeyPackets:!1})}else if(t.startsWith(cn)){const i=new Tn(t.slice(26)),n=i.get("uri");if(null===n)throw new Error("Invalid M3U8 file; #EXT-X-I-FRAME-STREAM-INF tag requires a URI attribute.");if(null===i.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=be(e,n);r.push({fullPath:s,attributes:i,lineNumber:u,hasOnlyKeyPackets:!0})}else if(t.startsWith(un)){const i=new Tn(t.slice(13));if(null===i.get("type"))throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a TYPE attribute.");if(null===i.get("group-id"))throw new Error("Invalid M3U8 file; #EXT-X-MEDIA tag requires a GROUP-ID attribute.");let r=null;const s=i.get("uri");null!==s&&(r=be(e,s)),n.push({fullPath:r,attributes:i,lineNumber:u})}else if("#EXT-X-I-FRAMES-ONLY"===t);else if(t.startsWith(dn)){const t=new Hn(this,e,null,i);return this.segmentedInputs=[t],this.hasMasterPlaylist=!1,void(this.trackBackings=yield t.getTrackBackings())}}const s=[...new Set(n.filter(e=>"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],a=[...new Set(n.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=yield Promise.all(r.map((t,i)=>d(this,null,function*(){var r,o,l,c;const u=[],h=t.attributes.get("codecs");let f;if(h)f=h.split(",").map(e=>e.trim());else{const e=this.getSegmentedInputForPath(t.fullPath),i=yield e.getTrackBackings(),r=yield Promise.all(i.map(e=>d(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));f=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const m=t.attributes.get("video"),p=t.attributes.get("audio"),g=f.some(e=>Re.includes(Ke(e))),k=f.some(e=>Me.includes(Ke(e)));if(null!==m&&!g){if(!s.includes(m))throw new Error(`Invalid M3U8 file; variant stream references video group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const t=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"video"===i.toLowerCase()});e:if(t){const i=t.attributes.get("uri");if(null===i)break e;const r=be(e,i),n=this.getSegmentedInputForPath(r),s=(yield n.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===(yield s.getCodec()))break e;const a=yield s.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null});y(null!==a),f.push(a)}}if(null!==p&&!k){if(!a.includes(p))throw new Error(`Invalid M3U8 file; variant stream references audio group "${p}" which is not defined in any #EXT-X-MEDIA tags.`);const t=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===p&&"audio"===i.toLowerCase()});e:if(t){const i=t.attributes.get("uri");if(null===i)break e;const r=be(e,i),n=this.getSegmentedInputForPath(r),s=(yield n.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===(yield s.getCodec()))break e;const a=yield s.getDecoderConfig().then(e=>{var t;return null!=(t=null==e?void 0:e.codec)?t:null});y(null!==a),f.push(a)}}f=[...new Set(f)];let b=null,T=null;const S=t.attributes.getAsNumber("bandwidth");y(null!==S);const v=t.attributes.getAsNumber("average-bandwidth"),w=t.attributes.get("name");for(const e of f){const d=Ke(e);if(null!==d)if(Re.includes(d)){if(null!==b)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");b=e;const a=t.attributes.get("video");if(null===a){const e=t.attributes.get("resolution");let r=null,n=null;if(e){const t=e.match(/^(\d+)x(\d+)$/);t&&(r=Number(t[1]),n=Number(t[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Q,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:b,pairingMask:BigInt("1")<<BigInt(i),peakBitrate:S,averageBitrate:v,name:w,hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"video",width:r,height:n}})}else{if(!s.includes(a))throw new Error(`Invalid M3U8 file; variant stream references video group "${a}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of n){const n=e.attributes.get("group-id"),s=e.attributes.get("type");if(n!==a||"video"!==s.toLowerCase())continue;const l=null!=(r=e.attributes.get("resolution"))?r:t.attributes.get("resolution");let c=null,d=null;if(l){const e=l.match(/^(\d+)x(\d+)$/);e&&(c=Number(e[1]),d=Number(e[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:Qn(e.attributes),autoselect:Qn(e.attributes)||Gn(e.attributes),languageCode:Yn(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:null!=(o=e.fullPath)?o:t.fullPath,fullCodecString:b,pairingMask:BigInt("1")<<BigInt(i),peakBitrate:null,averageBitrate:null,name:e.attributes.get("name"),hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"video",width:c,height:d}})}}}else if(Me.includes(d)){if(null!==T)throw new Error("Unsupported M3U8 file; multiple audio codecs found in the CODECS attribute of a variant stream.");T=e;const r=t.attributes.get("audio");if(null===r){const e=t.attributes.get("channels"),r=null!==e?Number(e.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:Q,lineNumber:t.lineNumber,fullPath:t.fullPath,fullCodecString:T,pairingMask:BigInt("1")<<BigInt(i),peakBitrate:S,averageBitrate:v,name:w,hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==r&&Number.isInteger(r)&&r>0?r:null}})}else{if(!a.includes(r))throw new Error(`Invalid M3U8 file; variant stream references audio group "${r}" which is not defined in any #EXT-X-MEDIA tags.`);for(const e of n){const n=e.attributes.get("group-id"),s=e.attributes.get("type");if(n!==r||"audio"!==s.toLowerCase())continue;const a=null!=(l=e.attributes.get("channels"))?l:t.attributes.get("channels"),o=null!==a?Number(a.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:Qn(e.attributes),autoselect:Qn(e.attributes)||Gn(e.attributes),languageCode:Yn(e.attributes.get("language")),lineNumber:e.lineNumber,fullPath:null!=(c=e.fullPath)?c:t.fullPath,fullCodecString:T,pairingMask:BigInt("1")<<BigInt(i),peakBitrate:null,averageBitrate:null,name:e.attributes.get("name"),hasOnlyKeyPackets:t.hasOnlyKeyPackets,info:{type:"audio",numberOfChannels:null!==o&&Number.isInteger(o)&&o>0?o:null}})}}}}return u}))),l=[],c=e=>{var t,i;const r=l.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);r?(r.pairingMask|=e.pairingMask,r.default||(r.default=e.default),r.autoselect||(r.autoselect=e.autoselect),r.lineNumber=Math.min(r.lineNumber,e.lineNumber),null!==e.peakBitrate&&(r.peakBitrate=Math.max(null!=(t=r.peakBitrate)?t:-1/0,e.peakBitrate)),null!==e.averageBitrate&&(r.averageBitrate=Math.max(null!=(i=r.averageBitrate)?i:-1/0,e.averageBitrate)),r.languageCode===Q&&(r.languageCode=e.languageCode)):(e.id=l.length+1,l.push(e))};for(const u of o)for(const e of u)c(e);l.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of l)"video"===u.info.type?this.trackBackings.push(new Xn(u)):this.trackBackings.push(new $n(u));this.internalTracks=l}))()}getTrackBackings(){return d(this,null,function*(){return yield this.readMetadata(),y(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 Hn(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return d(this,null,function*(){return{}})}getMimeType(){return d(this,null,function*(){return on})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class jn{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>d(this,null,function*(){const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(yield e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof Xn){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{y(this instanceof $n);for(const e of i)if((yield 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 u(c({},Be),{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(){y(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())}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return d(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Xn extends jn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return Ke(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())}getColorSpace(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class $n extends jn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return Ke(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}getDecoderConfig(){return d(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const Qn=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}".`)},Gn=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}".`)},Yn=e=>{if(null===e)return Q;const t=e.split("-")[0];return t||Q};class Jn{constructor(){this._isIsobmff=!1}}class Zn extends Jn{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return null;t.skip(4);const i=Wa(t,4);return"ftyp"!==i&&"styp"!==i?null:Wa(t,4)})}_createDemuxer(e){return new gi(e)}}class es extends Zn{_canReadInput(e){return d(this,null,function*(){const t=yield this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=e._reader.requestSlice(4,4);return i instanceof Promise&&(i=yield i),!!i&&"moof"===Wa(i,4)})}get name(){return"MP4"}get mimeType(){return"video/mp4"}}class ts extends Zn{_canReadInput(e){return d(this,null,function*(){return"qt "===(yield this._getMajorBrand(e))})}get name(){return"QuickTime File Format"}get mimeType(){return"video/quicktime"}}class is extends Jn{isSupportedEBMLOfDocType(e,t){return d(this,null,function*(){let i=e._reader.requestSlice(0,Li);if(i instanceof Promise&&(i=yield i),!i)return!1;const r=zi(i);if(null===r)return!1;if(r<1||r>8)return!1;if(qi(i,r)!==Ri.EBML)return!1;const n=Vi(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(s instanceof Promise&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=Hi(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case Ri.EBMLVersion:if(1!==qi(s,r))return!1;break;case Ri.EBMLReadVersion:if(1!==qi(s,r))return!1;break;case Ri.DocType:if(Ki(s,r)!==t)return!1;break;case Ri.DocTypeVersion:if(qi(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new kr(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class rs extends is{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class ns extends Jn{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=i.filePos+r.size}const i=yield Sr(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=Ge(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(s instanceof Promise&&(s=yield s),!s)return!1;const a=Ra(s);if(a===$e||a===Qe)return!0;t=i.startPos+i.header.totalSize;const o=yield Sr(e._reader,t,t+4);if(!o)return!1;const l=o.header;return r.channel===l.channel&&r.sampleRate===l.sampleRate})}_createDemuxer(e){return new vr(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class ss extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,12);if(t instanceof Promise&&(t=yield t),!t)return!1;const i=Wa(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Wa(t,4)})}_createDemuxer(e){return new Lr(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class as extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"OggS"===Wa(t,4)})}_createDemuxer(e){return new Fr(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class os extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,4);return t instanceof Promise&&(t=yield t),!!t&&"fLaC"===Wa(t,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new Kr(e)}}class ls extends Jn{_canReadInput(e){return d(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Qa);if(i instanceof Promise&&(i=yield i),!i)break;const r=Za(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(i instanceof Promise&&(i=yield i),!i)return!1;const r=qr(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),i instanceof Promise&&(i=yield i),!i)return!1;const n=qr(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new Vr(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class cs extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,205);if(t instanceof Promise&&(t=yield t),!t)return!1;const i=xa(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 Yr(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class us extends Jn{_canReadInput(e){return d(this,null,function*(){let t=e._reader.requestSlice(0,7);if(t instanceof Promise&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Wa(t,7)))return!1;if(!(e._rootSource instanceof Bn))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 Kn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return on}}const ds=new es,hs=new ts,fs=new is,ms=new rs,ps=new ns,gs=new ss,ks=new as,ys=new ls,bs=new os,Ts=new cs,Ss=new us,vs=[Ss,ds,hs,fs,ms,gs,ks,bs,ps,ys,Ts],ws=[Ss,ds,hs,ps,ys,Ts];ke();let Ps=-1/0,Is=-1/0,xs=null;"undefined"!==typeof FinalizationRegistry&&(xs=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-Ps>=1e3&&(console.error("A VideoSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your VideoSamples as soon as you're done using them."),Ps=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Is>=1e3&&(console.error("An AudioSample was garbage collected without first being closed. For proper resource management, make sure to call close() on all your AudioSamples as soon as you're done using them."),Is=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));const Cs=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Bs=new Set(Cs);class Es{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(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){var i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,b,T,S,v,P,I,x,C,B,E;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||!Bs.has(t.format))throw new TypeError("init.format must be one of: "+Cs.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&&we(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._data=w(e).slice(),this._layout=null!=(i=t.layout)?i:Ms(t.format,t.codedWidth,t.codedHeight),this.format=t.format,this.rotation=null!=(r=t.rotation)?r:0,this.timestamp=t.timestamp,this.duration=null!=(n=t.duration)?n:0,this.colorSpace=new _s(t.colorSpace),this.visibleRect={left:null!=(a=null==(s=t.visibleRect)?void 0:s.left)?a:0,top:null!=(l=null==(o=t.visibleRect)?void 0:o.top)?l:0,width:null!=(u=null==(c=t.visibleRect)?void 0:c.width)?u:t.codedWidth,height:null!=(h=null==(d=t.visibleRect)?void 0:d.height)?h: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.codedWidth,this.squarePixelHeight=this.codedHeight)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==(null==t?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!==(null==t?void 0:t.timestamp)&&!Number.isFinite(null==t?void 0:t.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==(null==t?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!==(null==t?void 0:t.visibleRect)&&we(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:null!=(m=null==(f=e.visibleRect)?void 0:f.x)?m:0,top:null!=(g=null==(p=e.visibleRect)?void 0:p.y)?g:0,width:null!=(b=null==(k=e.visibleRect)?void 0:k.width)?b:e.codedWidth,height:null!=(S=null==(T=e.visibleRect)?void 0:T.height)?S:e.codedHeight},this.rotation=null!=(v=null==t?void 0:t.rotation)?v:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(P=null==t?void 0:t.timestamp)?P:e.timestamp/1e6,this.duration=null!=(x=null==t?void 0:t.duration)?x:(null!=(I=e.duration)?I:0)/1e6,this.colorSpace=new _s(e.colorSpace)}else{if(!("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas))throw new TypeError("Invalid data type: Must be a BufferSource or CanvasImageSource.");{if(!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("undefined"!==typeof VideoFrame)return new Es(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*te),duration:Math.trunc((null!=(C=t.duration)?C:0)*te)||void 0}),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 n=new OffscreenCanvas(i,r),s=n.getContext("2d",{alpha:ce(),willReadFrequently:!0});y(s),s.drawImage(e,0,0),this._data=n,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:i,height:r},this.squarePixelWidth=i,this.squarePixelHeight=r,this.rotation=null!=(B=t.rotation)?B:0,this.timestamp=t.timestamp,this.duration=null!=(E=t.duration)?E:0,this.colorSpace=new _s({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}}this.pixelAspectRatio=ve({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==xs||xs.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),As(this._data)?new Es(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation}):this._data instanceof Uint8Array?(y(this._layout),new Es(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})):new Es(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight})}close(){this._closed||(null==xs||xs.unregister(this),As(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(Ds(e),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot get allocation size when format is null. Sorry!");if(y(null!==this._data),!As(this._data)&&(e.colorSpace||e.format&&e.format!==this.format||e.layout||e.rect)){const t=this.toVideoFrame(),i=t.allocationSize(e);return t.close(),i}return As(this._data)?this._data.allocationSize(e):this._data instanceof Uint8Array?this._data.byteLength:this.codedWidth*this.codedHeight*4}copyTo(e){return d(this,arguments,function*(e,t={}){if(!R(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(Ds(t),this._closed)throw new Error("VideoSample is closed.");if(null===this.format)throw new Error("Cannot copy video sample data when format is null. Sorry!");if(y(null!==this._data),!As(this._data)&&(t.colorSpace||t.format&&t.format!==this.format||t.layout||t.rect)){const i=this.toVideoFrame(),r=yield i.copyTo(e,t);return i.close(),r}if(As(this._data))return this._data.copyTo(e,t);if(this._data instanceof Uint8Array){y(this._layout);return w(e).set(this._data),this._layout}{const t=this._data.getContext("2d");y(t);const i=t.getImageData(0,0,this.codedWidth,this.codedHeight);return w(e).set(i.data),[{offset:0,stride:4*this.codedWidth}]}})}toVideoFrame(){if(this._closed)throw new Error("VideoSample is closed.");return y(null!==this._data),As(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace}):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,n,s,a,o,l){let c=0,u=0,d=this.displayWidth,h=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(c=t,u=i,d=r,h=n,f=s,m=a,void 0!==o?(p=o,g=l):(p=d,g=h)):(f=t,m=i,void 0!==r&&(p=r,g=n)),!("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(c))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:c,sy:u,sWidth:d,sHeight:h}=this._rotateSourceRegion(c,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 T=this.rotation%180===0?1:p/g;e.scale(1/T,T),e.drawImage(k,c,u,d,h,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){var i,r,n,s,a,o,l,c,u;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&&Rs(t.crop,"options.");const d=e.canvas.width,h=e.canvas.height,f=null!=(i=t.rotation)?i:this.rotation,[m,p]=f%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let g,k,y,b;t.crop&&Fs(t.crop,m,p);const{sx:T,sy:S,sWidth:v,sHeight:w}=this._rotateSourceRegion(null!=(n=null==(r=t.crop)?void 0:r.left)?n:0,null!=(a=null==(s=t.crop)?void 0:s.top)?a:0,null!=(l=null==(o=t.crop)?void 0:o.width)?l:m,null!=(u=null==(c=t.crop)?void 0:c.height)?u:p,f);if("fill"===t.fit)g=0,k=0,y=d,b=h;else{const[e,i]=t.crop?[t.crop.width,t.crop.height]:[m,p],r="contain"===t.fit?Math.min(d/e,h/i):Math.max(d/e,h/i);y=e*r,b=i*r,g=(d-y)/2,k=(h-b)/2}e.save();const P=f%180===0?1:y/b;e.translate(d/2,h/2),e.rotate(f*Math.PI/180),e.scale(1/P,P),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),T,S,v,w,g,k,y,b),e.restore()}_rotateSourceRegion(e,t,i,r,n){return 90===n?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===n?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===n&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(y(null!==this._data),this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}[Symbol.dispose](){this.close()}}class _s{constructor(e){var t,i,r,n;if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(C);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(E);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(A);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=null!=(t=null==e?void 0:e.primaries)?t:null,this.transfer=null!=(i=null==e?void 0:e.transfer)?i:null,this.matrix=null!=(r=null==e?void 0:e.matrix)?r:null,this.fullRange=null!=(n=null==e?void 0:e.fullRange)?n:null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const As=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Fs=(e,t,i)=>{const r=Math.min(e.left,t),n=Math.min(e.top,i),s=Math.min(e.width,t-r),a=Math.min(e.height,i-n);return y(s>=0),y(a>=0),{left:r,top:n,width:s,height:a}},Rs=(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.")},Ds=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.")}},Ms=(e,t,i)=>{const r=Ns(e),n=[];let s=0;for(const a of r){const e=Math.ceil(t/a.widthDivisor),r=Math.ceil(i/a.heightDivisor),o=e*a.sampleBytes,l=o*r;n.push({offset:s,stride:o}),s+=l}return n},Ns=e=>{const t=(e,t,i,r,n)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return n&&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:H(e),y(!1)}},Os=new Set(["f32","f32-planar","s16","s16-planar","s32","s32-planar","u8","u8-planar"]);class Ls{get microsecondTimestamp(){return Math.trunc(te*this.timestamp)}get microsecondDuration(){return Math.trunc(te*this.duration)}constructor(e){if(this._closed=!1,Vs(e)){if(null===e.format)throw new TypeError("AudioData with null format is not supported.");this._data=e,this.format=e.format,this.sampleRate=e.sampleRate,this.numberOfFrames=e.numberOfFrames,this.numberOfChannels=e.numberOfChannels,this.timestamp=e.timestamp/1e6,this.duration=e.numberOfFrames/e.sampleRate}else{if(!e||"object"!==typeof e)throw new TypeError("Invalid AudioDataInit: must be an object.");if(!Os.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(null==e?void 0:e.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(zs(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*zs(this.format);if(i.byteLength<r)throw new TypeError("Invalid AudioDataInit: insufficient data size.");this._data=i}null==xs||xs.register(this,{type:"audio",data:this._data},this)}allocationSize(e){var t,i;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&&!Os.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 r=null!=(t=e.format)?t:this.format,n=null!=(i=e.frameOffset)?i:0;if(n>=this.numberOfFrames)throw new RangeError("frameOffset out of range");const s=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-n;if(s>this.numberOfFrames-n)throw new RangeError("frameCount out of range");const a=zs(r),o=Us(r);if(o&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!o&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(o?s:s*this.numberOfChannels)*a}copyTo(e,t){if(!R(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&&!Os.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{planeIndex:i,format:r,frameCount:n,frameOffset:s}=t,a=this.format,o=null!=r?r:this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,u=null!=s?s:0;if(u>=l)throw new RangeError("frameOffset out of range");const d=void 0!==n?n:l-u;if(d>l-u)throw new RangeError("frameCount out of range");const h=zs(o),f=Us(o);if(f&&i>=c)throw new RangeError("planeIndex out of range");if(!f&&0!==i)throw new RangeError("planeIndex out of range");const m=(f?d:d*c)*h;if(e.byteLength<m)throw new RangeError("Destination buffer is too small");const p=P(e),g=Ws(o);if(Vs(this._data))oe()&&c>2&&o!==a?Hs(this._data,p,a,o,c,i,u,d):this._data.copyTo(e,{planeIndex:i,frameOffset:u,frameCount:d,format:o});else{const e=this._data,t=P(e),r=qs(a),n=zs(a),s=Us(a);for(let a=0;a<d;a++)if(f){let e;e=s?(i*l+(a+u))*n:((a+u)*c+i)*n;g(p,a*h,r(t,e))}else for(let e=0;e<c;e++){let i;i=s?(e*l+(a+u))*n:((a+u)*c+e)*n;g(p,(a*c+e)*h,r(t,i))}}}clone(){if(this._closed)throw new Error("AudioSample is closed.");if(Vs(this._data)){const e=new Ls(this._data.clone());return e.setTimestamp(this.timestamp),e}return new Ls({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp,data:this._data})}close(){this._closed||(null==xs||xs.unregister(this),Vs(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");if(Vs(this._data)){if(this._data.timestamp===this.microsecondTimestamp)return this._data.clone();if(Us(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})}}return new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}toAudioBuffer(){if(this._closed)throw new Error("AudioSample is closed.");const e=new AudioBuffer({numberOfChannels:this.numberOfChannels,length:this.numberOfFrames,sampleRate:this.sampleRate}),t=new Float32Array(this.allocationSize({planeIndex:0,format:"f32-planar"})/4);for(let 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,n=e.length,s=Math.floor(24e4/i);let a=0,o=n;for(;o>0;){const n=Math.min(s,o),l=new Float32Array(i*n);for(let t=0;t<i;t++)e.copyFromChannel(l.subarray(t*n,(t+1)*n),t,a);yield new Ls({format:"f32-planar",sampleRate:r,numberOfFrames:n,numberOfChannels:i,timestamp:t+a/r,data:l}),a+=n,o-=n}}static fromAudioBuffer(e,t){if(!(e instanceof AudioBuffer))throw new TypeError("audioBuffer must be an AudioBuffer.");const i=e.numberOfChannels,r=e.sampleRate,n=e.length,s=Math.floor(24e4/i);let a=0,o=n;const l=[];for(;o>0;){const n=Math.min(s,o),c=new Float32Array(i*n);for(let t=0;t<i;t++)e.copyFromChannel(c.subarray(t*n,(t+1)*n),t,a);const u=new Ls({format:"f32-planar",sampleRate:r,numberOfFrames:n,numberOfChannels:i,timestamp:t+a/r,data:c});l.push(u),a+=n,o-=n}return l}}const zs=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")}},Us=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},qs=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)}},Ws=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,$(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,$(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,$(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Vs=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Hs=(e,t,i,r,n,s,a,o)=>{const l=qs(i),c=Ws(r),u=zs(i),d=zs(r),h=Us(i);if(Us(r))if(h){const r=new ArrayBuffer(o*u),n=P(r);e.copyTo(r,{planeIndex:s,frameOffset:a,frameCount:o,format:i});for(let e=0;e<o;e++){c(t,e*d,l(n,e*u))}}else{const r=new ArrayBuffer(o*n*u),h=P(r);e.copyTo(r,{planeIndex:0,frameOffset:a,frameCount:o,format:i});for(let e=0;e<o;e++){c(t,e*d,l(h,(e*n+s)*u))}}else if(h){const r=new ArrayBuffer(o*u),s=P(r);for(let h=0;h<n;h++){e.copyTo(r,{planeIndex:h,frameOffset:a,frameCount:o,format:i});for(let e=0;e<o;e++){c(t,(e*n+h)*d,l(s,e*u))}}}else{const r=new ArrayBuffer(o*n*u),s=P(r);e.copyTo(r,{planeIndex:0,frameOffset:a,frameCount:o,format:i});for(let e=0;e<o;e++)for(let i=0;i<n;i++){const r=e*n+i;c(t,r*d,l(s,r*u))}}},Ks=[],js=[],Xs=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.")},$s=e=>{if(!ye(e))throw new TypeError("timestamp must be a number.")},Qs=(e,t,i)=>i.verifyKeyPackets?t.then(t=>d(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class Gs{constructor(e){if(!(e instanceof la))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return d(this,arguments,function*(e={}){if(Xs(e),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return d(this,arguments,function*(e={}){Xs(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return d(this,arguments,function*(e,t={}){if($s(e),Xs(t),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(Xs(t),this._track.input._disposed)throw new va;return Qs(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return d(this,arguments,function*(e,t={}){if($s(e),Xs(t),this._track.input._disposed)throw new va;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return d(this,arguments,function*(e,t={}){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");if(Xs(t),this._track.input._disposed)throw new va;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;y("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getNextKeyPacket(i,t):i})}packets(e,t,i={}){if(void 0!==e&&!(e instanceof Yt))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!(null==i?void 0:i.metadataOnly))throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof Yt))throw new TypeError("endPacket must be an EncodedPacket.");if(Xs(i),this._track.input._disposed)throw new va;const r=[];let{promise:n,resolve:s}=q(),{promise:a,resolve:o}=q(),l=!1,c=!1,u=null;const h=[],f=()=>Math.max(2,h.length);(()=>d(this,null,function*(){let u=null!=e?e:yield this.getFirstPacket(i);for(;u&&!c&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=(null==t?void 0:t.sequenceNumber));)r.length>f()?(({promise:a,resolve:o}=q()),yield a):(r.push(u),s(),({promise:n,resolve:s}=q()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{u||(u=e,s())});const m=this._track;return{next(){return d(this,null,function*(){for(;;){if(m.input._disposed)throw new va;if(c)return{value:void 0,done:!0};if(u)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(l)return{value:void 0,done:!0};yield n}})},return(){return d(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Ys{constructor(e,t){this.onSample=e,this.onError=t}}class Js{mediaSamplesInRange(e=0,t=1/0,i){$s(e),$s(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=q(),{promise:l,resolve:h}=q(),f=!1,m=!1,p=!1,g=null;const k=u(c({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){var i;const c=yield this._createDecoder(i=>{h(),i.timestamp>=t&&(m=!0),m?i.close():(s&&(i.timestamp>e?(r.push(s),n=!0):s.close()),i.timestamp>=e&&(r.push(i),n=!0),s=n?null:i,r.length>0&&(o(),({promise:a,resolve:o}=q())))},e=>{g||(g=e,o())}),u=this._createPacketSink(),d=null!=(i=yield u.getKeyPacket(e,k))?i:yield u.getFirstKeyPacket(k);let y=d;const b=u.packets(null!=d?d:void 0,void 0,k);for(yield b.next();y&&!m&&!this._track.input._disposed;){const e=Zs(r.length);if(r.length+c.getDecodeQueueSize()>e){({promise:l,resolve:h}=q()),yield l;continue}c.decode(y);const t=yield b.next();if(t.done)break;y=t.value}yield b.return(),p||this._track.input._disposed||(yield c.flush()),c.close(),!n&&s&&r.push(s),f=!0,o()}))().catch(e=>{g||(g=e,o())});const y=this._track,b=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return d(this,null,function*(){for(;;){if(y.input._disposed)throw b(),new va;if(p)return{value:void 0,done:!0};if(g)throw b(),g;if(r.length>0){const e=r.shift();return h(),{value:e,done:!1}}if(f)return{value:void 0,done:!0};yield a}})},return(){return d(this,null,function*(){return p=!0,m=!0,h(),o(),b(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){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=function(e){return f(this,null,function*(){Symbol.iterator in e?yield*m(e[Symbol.iterator]()):yield*m(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=q(),{promise:o,resolve:l}=q(),h=!1,g=!1,k=null;const b=e=>{n.push(e),a(),({promise:s,resolve:a}=q())},T=u(c({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>d(this,null,function*(){const e=yield this._createDecoder(e=>{if(l(),g)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++)b(i<t-1?e.clone():e);else e.close()},e=>{k||(k=e,a())}),t=this._createPacketSink();let s=null,c=null,u=-1;const f=()=>d(this,null,function*(){y(c);let i=c;for(e.decode(i);i.sequenceNumber<u;){const r=Zs(n.length);for(;n.length+e.getDecodeQueueSize()>r&&!g;)({promise:o,resolve:l}=q()),yield o;if(g)break;const s=yield t.getNextPacket(i,T);y(s),e.decode(s),i=s}u=-1}),m=()=>d(this,null,function*(){yield e.flush();for(let e=0;e<r.length;e++)b(null);r.length=0});try{for(var S,v,w,P=p(i);S=!(v=yield P.next()).done;S=!1){const e=v.value;if($s(e),g||this._track.input._disposed)break;const i=yield t.getPacket(e,T),n=i&&(yield t.getKeyPacket(e,T));n?(s&&(n.sequenceNumber!==c.sequenceNumber||i.timestamp<s.timestamp)&&(yield f(),yield m()),r.push(i.timestamp),u=Math.max(i.sequenceNumber,u),s=i,c=n):(-1!==u&&(yield f(),yield m()),b(null),s=null)}}catch(v){w=[v]}finally{try{S&&(v=P.return)&&(yield v.call(P))}finally{if(w)throw w[0]}}g||this._track.input._disposed||(-1!==u&&(yield f()),yield m()),e.close(),h=!0,a()}))().catch(e=>{k||(k=e,a())});const S=this._track,v=()=>{for(const e of n)null==e||e.close()};return{next(){return d(this,null,function*(){for(;;){if(S.input._disposed)throw v(),new va;if(g)return{value:void 0,done:!0};if(k)throw v(),k;if(n.length>0){const e=n.shift();return y(void 0!==e),l(),{value:e,done:!1}}if(h)return{value:void 0,done:!0};yield s}})},return(){return d(this,null,function*(){return g=!0,l(),a(),v(),{value:void 0,done:!0}})},throw(e){return d(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Zs=e=>0===e?40:8;class ea extends Ys{constructor(e,t,i,r,n,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,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.mergerCreationFailed=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1;const a=Ks.find(e=>e.supports(i,r));if(a)this.customDecoder=new a,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof Es))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();y(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if("avc"===i&&this.decoderConfig.description&&de()){const e=(e=>{try{const t=P(e);let i=0;const r=t.getUint8(i++),n=t.getUint8(i++),s=t.getUint8(i++),a=t.getUint8(i++),o=3&t.getUint8(i++),l=31&t.getUint8(i++),c=[];for(let f=0;f<l;f++){const r=t.getUint16(i,!1);i+=2,c.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:n,profileCompatibility:s,avcLevelIndication:a,lengthSizeMinusOne:o,sequenceParameterSets:c,pictureParameterSets:d,chromaFormat:null,bitDepthLumaMinus8:null,bitDepthChromaMinus8:null,sequenceParameterSetExt:null};if((100===n||110===n||122===n||144===n)&&i+4<=e.length){const r=3&t.getUint8(i++),n=7&t.getUint8(i++),s=7&t.getUint8(i++),a=t.getUint8(i++);h.chromaFormat=r,h.bitDepthLumaMinus8=n,h.bitDepthChromaMinus8=s;const o=[];for(let l=0;l<a;l++){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 console.error("Error deserializing AVC Decoder Configuration Record:",t),null}})(w(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=kt(e.sequenceParameterSets[0]);t&&0===t.frameMbsOnlyFlag&&(this.decoderConfig=u(c({},this.decoderConfig),{hardwareAcceleration:"prefer-software"}))}}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(){var e,t;return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),Math.max(this.decoder.decodeQueueSize,null!=(t=null==(e=this.alphaDecoder)?void 0:e.decodeQueueSize)?t:0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--);else{if(y(this.decoder),oe()||U(this.inputTimestamps,e.timestamp,e=>e),de()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];for(const r of ct(e.data,this.decoderConfig)){const i=ut(e.data[r.offset]);i>=20&&i<=31||t.push(e.data.subarray(r.offset,r.offset+r.length))}const i=((e,t)=>{if(t.description){const i=3&w(t.description)[4];return mt(e,i+1)}return ft(e)})(t,this.decoderConfig);e=new Yt(i,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Ft(e.data,this.decoderConfig);t&&(e=new Yt(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha||this.mergerCreationFailed)return void this.pushNullAlphaFrame();if(!this.merger)try{this.merger=new ta}catch(i){return console.error("Due to an error, only color data will be decoded.",i),this.mergerCreationFailed=!0,void this.decodeAlphaData(e)}if(!this.alphaDecoder){const e=e=>{if(this.alphaDecoderQueueSize--,this.colorQueue.length>0){const t=this.colorQueue.shift();y(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();y(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null)},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=Lt(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(null!=t?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 bt(e,this.decoderConfig)){const i=Tt(e[t.offset]);if(i===st.RASL_N||i===st.RASL_R)return!0}return!1}sampleHandler(e){if(oe()){if(this.sampleQueue.length>0&&e.timestamp>=T(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}U(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();y(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)}mergeAlpha(e,t){var i;if(!t){const t=new Es(e);return void this.sampleHandler(t)}y(this.merger),this.merger.update(e,t),e.close(),t.close();const r=new VideoFrame(this.merger.canvas,{timestamp:e.timestamp,duration:null!=(i=e.duration)?i:void 0}),n=new Es(r);this.sampleHandler(n)}flush(){return d(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0: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),oe()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1})}close(){var e,t;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close(),null==(e=this.alphaDecoder)||e.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,null==(t=this.merger)||t.close());for(const i of this.sampleQueue)i.close();this.sampleQueue.length=0}}class ta{constructor(){"undefined"!==typeof OffscreenCanvas?this.canvas=new OffscreenCanvas(300,150):this.canvas=document.createElement("canvas");const e=this.canvas.getContext("webgl2",{premultipliedAlpha:!1});if(!e)throw new Error("Couldn't acquire WebGL 2 context.");this.gl=e,this.program=this.createProgram(),this.vao=this.createVAO(),this.colorTexture=this.createTexture(),this.alphaTexture=this.createTexture(),this.gl.useProgram(this.program),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_colorTexture"),0),this.gl.uniform1i(this.gl.getUniformLocation(this.program,"u_alphaTexture"),1)}createProgram(){const e=this.createShader(this.gl.VERTEX_SHADER,"#version 300 es\n\t\t\tin vec2 a_position;\n\t\t\tin vec2 a_texCoord;\n\t\t\tout vec2 v_texCoord;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tgl_Position = vec4(a_position, 0.0, 1.0);\n\t\t\t\tv_texCoord = a_texCoord;\n\t\t\t}\n\t\t"),t=this.createShader(this.gl.FRAGMENT_SHADER,"#version 300 es\n\t\t\tprecision highp float;\n\t\t\t\n\t\t\tuniform sampler2D u_colorTexture;\n\t\t\tuniform sampler2D u_alphaTexture;\n\t\t\tin vec2 v_texCoord;\n\t\t\tout vec4 fragColor;\n\t\t\t\n\t\t\tvoid main() {\n\t\t\t\tvec3 color = texture(u_colorTexture, v_texCoord).rgb;\n\t\t\t\tfloat alpha = texture(u_alphaTexture, v_texCoord).r;\n\t\t\t\tfragColor = vec4(color, alpha);\n\t\t\t}\n\t\t"),i=this.gl.createProgram();return this.gl.attachShader(i,e),this.gl.attachShader(i,t),this.gl.linkProgram(i),i}createShader(e,t){const i=this.gl.createShader(e);return this.gl.shaderSource(i,t),this.gl.compileShader(i),i}createVAO(){const e=this.gl.createVertexArray();this.gl.bindVertexArray(e);const t=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,1,1,1,0]),i=this.gl.createBuffer();this.gl.bindBuffer(this.gl.ARRAY_BUFFER,i),this.gl.bufferData(this.gl.ARRAY_BUFFER,t,this.gl.STATIC_DRAW);const r=this.gl.getAttribLocation(this.program,"a_position"),n=this.gl.getAttribLocation(this.program,"a_texCoord");return this.gl.enableVertexAttribArray(r),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,16,0),this.gl.enableVertexAttribArray(n),this.gl.vertexAttribPointer(n,2,this.gl.FLOAT,!1,16,8),e}createTexture(){const e=this.gl.createTexture();return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),e}update(e,t){e.displayWidth===this.canvas.width&&e.displayHeight===this.canvas.height||(this.canvas.width=e.displayWidth,this.canvas.height=e.displayHeight),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.colorTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,e),this.gl.activeTexture(this.gl.TEXTURE1),this.gl.bindTexture(this.gl.TEXTURE_2D,this.alphaTexture),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,t),this.gl.viewport(0,0,this.canvas.width,this.canvas.height),this.gl.clear(this.gl.COLOR_BUFFER_BIT),this.gl.bindVertexArray(this.vao),this.gl.drawArrays(this.gl.TRIANGLE_STRIP,0,4)}close(){var e;null==(e=this.gl.getExtension("WEBGL_lose_context"))||e.loseContext(),this.gl=null}}class ia extends Js{constructor(e){if(!(e instanceof da))throw new TypeError("videoTrack must be an InputVideoTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode()))throw new Error("This video track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=yield this._track.getCodec(),r=yield this._track.getRotation(),n=yield this._track.getDecoderConfig(),s=yield this._track.getTimeResolution();return y(i&&n),new ea(e,t,i,n,r,s)})}_createPacketSink(){return new Gs(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){$s(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class ra{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof da))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&&Rs(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.");this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._options=t,this._fit=null!=(r=t.fit)?r:"fill",this._videoSampleSink=new ia(e),this._canvasPool=Array.from({length:null!=(n=t.poolSize)?n:0},()=>null)}_ensureInit(){var e;return null!=(e=this._initPromise)?e:this._initPromise=(()=>d(this,null,function*(){var e;const t=this._options,i=this._videoTrack,r=null!=(e=t.rotation)?e:yield i.getRotation(),n=yield i.getSquarePixelWidth(),s=yield i.getSquarePixelHeight(),[a,o]=r%180===0?[n,s]:[s,n];let l=t.crop;l&&(l=Fs(l,a,o));let[c,u]=l?[l.width,l.height]:[a,o];const d=c/u;void 0!==t.width&&void 0===t.height?(c=t.width,u=Math.round(c/d)):void 0===t.width&&void 0!==t.height?(u=t.height,c=Math.round(u*d)):void 0!==t.width&&void 0!==t.height&&(c=t.width,u=t.height),this._width=c,this._height=u,this._rotation=r,this._crop=l}))()}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],n=!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),n=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||ce()});y(s),s.resetTransform(),n||(!this._alpha&&ce()?(s.fillStyle="black",s.fillRect(0,0,t,i)):s.clearRect(0,0,t,i)),e.drawWithFit(s,{fit:this._fit,rotation:this._rotation,crop:this._crop});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return d(this,null,function*(){$s(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e=0,t=1/0,i){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(X(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return f(this,null,function*(){yield new h(this._ensureInit()),yield*m(X(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class na extends Ys{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new se,this.customDecoderQueueSize=0,this.currentTimestamp=null;const n=t=>{(null===this.currentTimestamp||Math.abs(t.timestamp-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=t.timestamp);const i=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const n=r.sampleRate;t.setTimestamp(Math.round(i*n)/n),e(t)},s=js.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 Ls))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init());else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{n(new Ls(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(y(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).then(()=>this.customDecoderQueueSize--)):(y(this.decoder),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(y(this.decoder),this.decoder.flush())}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(y(this.decoder),this.decoder.close())}}class sa extends Ys{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,y(De.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=He(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-o(2,7):"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 n=(1<<i|(15&r)<<i-4|1<<i-5)-33;return 0===t?n:-n})(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 n=0;return n=4!==i?1<<i|(15&r)<<i-4|1<<i-5:r<<1|1,0===t?n:-n})(e.getUint8(t)):y(!1);break;case 2:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint16(t,s)-o(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):y(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>K(e,t,s)-o(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>K(e,t,i)<<8>>8)(e,t,s):y(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-o(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):y(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):y(!1);break;default:H(n),y(!1)}switch(n){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+o(2,7)));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:H(n),y(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=P(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,n=new ArrayBuffer(r),s=new DataView(n);for(let c=0;c<i*this.decoderConfig.numberOfChannels;c++){const e=c*this.inputSampleSize,i=c*this.outputSampleSize,r=this.readInputValue(t,e);this.writeOutputValue(s,i,r)}const a=i/this.decoderConfig.sampleRate;(null===this.currentTimestamp||Math.abs(e.timestamp-this.currentTimestamp)>=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new Ls({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return d(this,null,function*(){})}close(){}}class aa extends Js{constructor(e){if(!(e instanceof ha))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return d(this,null,function*(){if(!(yield this._track.canDecode()))throw new Error("This audio track cannot be decoded by this browser. Make sure to check decodability before using a track.");const i=yield this._track.getCodec(),r=yield this._track.getDecoderConfig();return y(i&&r),De.includes(r.codec)?new sa(e,t,r):new na(e,t,i,r)})}_createPacketSink(){return new Gs(this._track)}getSample(e){return d(this,arguments,function*(e,t={}){$s(e);try{for(var i,r,n,s=p(this.mediaSamplesAtTimestamps([e],t));i=!(r=yield s.next()).done;i=!1){return r.value}}catch(r){n=[r]}finally{try{i&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n[0]}}throw new Error("Internal error: Iterator returned nothing.")})}samples(e=0,t=1/0,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class oa{constructor(e){if(!(e instanceof ha))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new aa(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return d(this,null,function*(){$s(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e=0,t=1/0,i){return X(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return X(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class la{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof da}isAudioTrack(){return this instanceof ha}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return d(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return ca(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return d(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return ca(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return d(this,null,function*(){return this._backing.getName()})}get name(){return ca(this._backing.getName(),"name","getName")}getTimeResolution(){return d(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return ca(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return d(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getDisposition(){return d(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return ca(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return d(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return d(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return d(this,null,function*(){var e;const t=yield this._backing.getFirstPacket({metadataOnly:!0});return null!=(e=null==t?void 0:t.timestamp)?e:0})}computeDuration(e){return d(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,c({metadataOnly:!0},e)),n=(null!=(t=null==r?void 0:r.timestamp)?t:0)+(null!=(i=null==r?void 0:r.duration)?i:0);return Y(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return d(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return d(this,null,function*(){const i=new Gs(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,u,d=p(i.packets(void 0,void 0,c({metadataOnly:!0},t)));o=!(l=yield d.next()).done;o=!1){const t=l.value;if(s>=e&&t.timestamp>=n)break;r=Math.min(r,t.timestamp),n=Math.max(n,t.timestamp+t.duration),s++,a+=t.byteLength}}catch(l){u=[l]}finally{try{o&&(l=d.return)&&(yield l.call(d))}finally{if(u)throw u[0]}}return{packetCount:s,averagePacketRate:s?Number((s/(n-r)).toPrecision(16)):0,averageBitrate:s?Number((8*a/(n-r)).toPrecision(16)):0}})}isLive(){return d(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return d(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof la))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&(this._backing.getPairingMask()&e._backing.getPairingMask())!==BigInt("0")}getPairableTracks(e){return d(this,null,function*(){return this.input.getTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return d(this,null,function*(){return this.input.getVideoTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return d(this,null,function*(){return this.input.getAudioTracks(ga({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return d(this,null,function*(){return this.input.getPrimaryVideoTrack(ga({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return d(this,null,function*(){return this.input.getPrimaryAudioTrack(ga({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return d(this,null,function*(){e&&(e=ua(e));const t=yield this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||(yield e(i))))return!0;return!1})}hasPairableVideoTrack(e){return e&&(e=ua(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=ua(e)),this.hasPairableTrack(t=>d(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const ca=(e,t,i)=>{if(e instanceof Promise)throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},ua=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 r instanceof Promise?r.then(i):i(r)}:void 0};class da extends la{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ca(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))&&i})}getCodedWidth(){return d(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return ca(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return d(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return ca(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return d(this,null,function*(){return this._backing.getRotation()})}get rotation(){return ca(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return d(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return ca(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return d(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return ca(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return d(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=ve({num:(yield this.getSquarePixelWidth())*(yield this.getCodedHeight()),den:(yield this.getSquarePixelHeight())*(yield this.getCodedWidth())})})}get pixelAspectRatio(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=ve({num:ca(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*ca(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:ca(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*ca(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()})}get displayWidth(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayWidth)?void 0:t.call(e);if(void 0!==i){const e=ca(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=ca(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return ca(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return d(this,null,function*(){var e,t;const i=yield null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(null!=i)return i;return(yield this.getRotation())%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()})}get displayHeight(){var e,t;const i=null==(t=(e=this._backing).getMetadataDisplayHeight)?void 0:t.call(e);if(void 0!==i){const e=ca(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=ca(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return ca(r,"displayHeight","getDisplayHeight")}getColorSpace(){return d(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return d(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pg"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return d(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),Ks.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Yt))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=yield this.getCodec();if(null===t)return null;const i=yield this.getDecoderConfig();return y(i),Lt(t,i,e.data)})}}class ha extends la{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return d(this,null,function*(){return this._backing.getCodec()})}get codec(){return ca(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return d(this,null,function*(){var e,t,i;return null==(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))||i})}getNumberOfChannels(){return d(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return ca(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return d(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return ca(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return d(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return d(this,null,function*(){var e,t,i;const r=yield null==(t=(e=this._backing).getMetadataCodecParameterString)?void 0:t.call(e);if(null!=r)return r;const n=yield this._backing.getDecoderConfig();return null!=(i=null==n?void 0:n.codec)?i:null})}canDecode(){return d(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(y(null!==t),js.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(yield AudioDecoder.isConfigSupported(e)).supported}catch(e){return console.error("Error during decodability check:",e),!1}})}determinePacketType(e){return d(this,null,function*(){if(!(e instanceof Yt))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const fa=e=>-(null!=e?e:-1/0),ma=e=>-e,pa=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 r instanceof Promise?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 r instanceof Promise?r.then(i):i(r)}:void 0}},ga=(e,t)=>({filter:(null==e?void 0:e.filter)||(null==t?void 0:t.filter)?i=>{var r,n;const s=null==(n=null==(r=null==e?void 0:e.filter)?void 0:r.call(e,i))||n,a=e=>{var r,n;return!1!==e&&(null==(n=null==(r=null==t?void 0:t.filter)?void 0:r.call(t,i))||n)};return s instanceof Promise?s.then(a):a(s)}:void 0,sortBy:(null==e?void 0:e.sortBy)||(null==t?void 0:t.sortBy)?i=>{var r,n,s,a;const o=null!=(n=null==(r=null==e?void 0:e.sortBy)?void 0:r.call(e,i))?n:[],l=null!=(a=null==(s=null==t?void 0:t.sortBy)?void 0:s.call(t,i))?a:[],c=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return o instanceof Promise||l instanceof Promise?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),ka=(e,t)=>d(null,null,function*(){let i=e;if(null==t?void 0:t.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>e instanceof Promise)){const t=yield Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!(null==t?void 0:t.sortBy))return i;const r=i.map(e=>t.sortBy(e)),n=r.some(e=>e instanceof Promise)?yield Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:n[t]})).sort((e,t)=>{var i,r;const n=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],s=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(n.length,s.length);for(let o=0;o<a;o++){const e=null!=(i=n[o])?i:0,t=null!=(r=s[o])?r:0;if(e!==t)return e-t}return 0}).map(e=>e.track)});ke();const ya=2;let ba=null;"undefined"!==typeof FinalizationRegistry&&(ba=new FinalizationRegistry(e=>{for(const t of e)t.freed||t.free()}));class Ta extends Ie{get disposed(){return this._disposed}constructor(e){var t,i;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 Jn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof xn||e.source instanceof Cn))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof xn&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Ta))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.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=null!=(t=e.initInput)?t:null,this._formatOptions=null!=(i=e.formatOptions)?i:{},e.source instanceof xn?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef),null==ba||ba.register(this,this._sourceRefs,this)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return d(this,null,function*(){y(this._rootSource instanceof Bn);const t=yield 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&&En(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&En(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>d(this,null,function*(){const i=yield this._getSourceUncached(e);if(Te(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=Se(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);y(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),((e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)})(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);y(-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:n}),n.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){var e;return null!=(e=this._demuxerPromise)?e:this._demuxerPromise=(()=>d(this,null,function*(){var e;this._reader=new wa(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const t of this._formats){if(yield t._canReadInput(this))return this._format=t,null==(e=this._onFormatDetermined)||e.call(this,t),t._createDemuxer(this)}throw new Sa}))()}get source(){return this._rootSource}getFormat(){return d(this,null,function*(){return yield this._getDemuxer(),y(this._format),this._format})}canRead(){return d(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof Sa)return!1;throw e}})}getFirstTimestamp(e){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=yield Promise.all(t.map(e=>e.getFirstTimestamp()));return Math.min(...i)})}computeDuration(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=yield Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)})}getDurationFromMetadata(e,t){return d(this,null,function*(){null!=e||(e=yield this.getTracks());const i=e.filter(e=>null!==e),r=(yield Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)})}getTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return ka(t,e)})}getVideoTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return ka(t,e)})}getAudioTracks(e){return d(this,null,function*(){e&&(e=pa(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return ka(t,e)})}getPrimaryVideoTrack(e){return d(this,null,function*(){var t;e&&(e=pa(e));const i=ga(e,{sortBy:e=>d(null,null,function*(){return[ma((yield e.getDisposition()).default),ma(yield e.hasPairableAudioTrack()),ma(!(yield e.hasOnlyKeyPackets())),fa(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return d(this,null,function*(){var t;e&&(e=pa(e));const i=yield this.getPrimaryVideoTrack(),r=ga(e,{sortBy:e=>d(this,null,function*(){return[ma(!i||e.canBePairedWith(i)),ma((yield e.getDisposition()).default),fa(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return d(this,null,function*(){var e;const t=yield this._getDemuxer();return null!=(e=this._trackBackingsCache)?e:this._trackBackingsCache=yield t.getTrackBackings()})}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new da(this,e):new ha(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return d(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return d(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){var e;if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,null==ba||ba.unregister(this),null==(e=this._demuxerPromise)||e.then(e=>e.dispose())}}[Symbol.dispose](){this.dispose()}}class Sa extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class va extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class wa{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(){var e;return null!=(e=this.source._getFileSize())?e:null}requestSlice(e,t){if(this.source._disposed)throw new va;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 Pa(t,P(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,In);return r instanceof Promise?r.then(t=>t?new Pa(t.bytes,t.view,t.offset,e,i):null):r?new Pa(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new va;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,$(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(y(null!==this.fileSizeNonStrict),this.requestSlice(e,$(this.fileSizeNonStrict-e,t,i)));return r instanceof Promise?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>d(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);const i=1024*e.length;let r=this.requestSliceRange(i,0,1024);if(r instanceof Promise&&(r=yield r),!r)break;e.push(xa(r,r.length)),t+=r.length}const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return new Pa(i,P(i),0,0,t)}))()}}class Pa{constructor(e,t,i,r,n){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=n,this.bufferPos=r-i}static tempFromBytes(e){return new Pa(e,P(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 Pa(this.bytes,this.view,this.offset,e,e+t)}}const Ia=(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.`)},xa=(e,t)=>{Ia(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},Ca=e=>(Ia(e,1),e.view.getUint8(e.bufferPos++)),Ba=(e,t)=>{Ia(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Ea=e=>{Ia(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},_a=e=>{Ia(e,3);const t=K(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Aa=e=>{Ia(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},Fa=(e,t)=>{Ia(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Ra=e=>{Ia(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Da=e=>{Ia(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},Ma=e=>{Ia(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},Na=(e,t)=>{let i,r;return t?(i=Fa(e,!0),r=Fa(e,!0)):(r=Fa(e,!1),i=Fa(e,!1)),4294967296*r+i},Oa=e=>4294967296*Ra(e)+Ra(e),La=e=>4294967296*Ma(e)+Ra(e),za=e=>{const t=Da(e),i=(e=>{Ia(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Ua=e=>{Ia(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},qa=e=>{Ia(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Wa=(e,t)=>{Ia(e,t);let i="";for(let r=0;r<t;r++)i+=String.fromCharCode(e.bytes[e.bufferPos++]);return i},Va=(e,t,i)=>I.decode(xa(e,t)).split("\n").map(e=>e.trim()).filter(e=>{var t;return e.length>0&&!(null==(t=null==i?void 0:i.ignore)?void 0:t.call(i,e))});var Ha,Ka,ja,Xa;(Ka=Ha||(Ha={}))[Ka.Unsynchronisation=128]="Unsynchronisation",Ka[Ka.ExtendedHeader=64]="ExtendedHeader",Ka[Ka.ExperimentalIndicator=32]="ExperimentalIndicator",Ka[Ka.Footer=16]="Footer",(Xa=ja||(ja={}))[Xa.ISO_8859_1=0]="ISO_8859_1",Xa[Xa.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Xa[Xa.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Xa[Xa.UTF_8=3]="UTF_8";const $a=128,Qa=10,Ga=["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"],Ya=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=xa(e,$a-3)),e.filePos=r;const n=Ja(e,30);n&&(null!=t.title||(t.title=n));const s=Ja(e,30);s&&(null!=t.artist||(t.artist=s));const a=Ja(e,30);a&&(null!=t.album||(t.album=a));const o=Ja(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(l,0,1)));const c=xa(e,30);let u;if(0===c[28]&&0!==c[29]){const i=c[29];i>0&&(null!=t.trackNumber||(t.trackNumber=i)),e.skip(-30),u=Ja(e,28),e.skip(2)}else e.skip(-30),u=Ja(e,30);u&&(null!=t.comment||(t.comment=u));const d=Ca(e);d<Ga.length&&(null!=t.genre||(t.genre=Ga[d]))},Ja=(e,t)=>{const i=xa(e,t),r=me(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a<n.length;a++)s+=String.fromCharCode(n[a]);return s.trimEnd()},Za=e=>{const t=e.filePos,i=Wa(e,3),r=Ca(e),n=Ca(e),s=Ca(e),a=Ra(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;return{majorVersion:r,revision:n,flags:s,size:Je(a)}},eo=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void console.warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=xa(e,t.size),u=new to(t,c);if(t.flags&Ha.Footer&&u.removeFooter(),t.flags&Ha.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Ha.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,d=u.pos+e.size;let h=!1,f=!1,m=!1;if(3===t.majorVersion?(h=!!(64&e.flags),f=!!(128&e.flags)):4===t.majorVersion&&(h=!!(4&e.flags),f=!!(8&e.flags),m=!!(2&e.flags)||!!(t.flags&Ha.Unsynchronisation)),h)console.warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=d;else if(f)console.warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=d;else{if(m&&u.ununsynchronizeRegion(u.pos,d),null!=i.raw||(i.raw={}),"TXXX"===e.id){const e=null!=(n=(r=i.raw).TXXX)?n:r.TXXX={},t=u.readId3V2TextEncoding(),s=u.readId3V2Text(t,d),a=u.readId3V2Text(t,d);null!=e[s]||(e[s]=a)}else"T"===e.id[0]?null!=(s=i.raw)[a=e.id]||(s[a]=u.readId3V2EncodingAndText(d)):null!=(o=i.raw)[l=e.id]||(o[l]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":null!=i.title||(i.title=u.readId3V2EncodingAndText(d));break;case"TIT3":case"TT3":null!=i.description||(i.description=u.readId3V2EncodingAndText(d));break;case"TPE1":case"TP1":null!=i.artist||(i.artist=u.readId3V2EncodingAndText(d));break;case"TALB":case"TAL":null!=i.album||(i.album=u.readId3V2EncodingAndText(d));break;case"TPE2":case"TP2":null!=i.albumArtist||(i.albumArtist=u.readId3V2EncodingAndText(d));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(d).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=i.trackNumber||(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=i.tracksTotal||(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(d).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(null!=i.discNumber||(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(null!=i.discsTotal||(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(d);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Ga[e]){null!=i.genre||(i.genre=Ga[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Ga[e]){null!=i.genre||(i.genre=Ga[e]);break}}null!=i.genre||(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(d),t=new Date(e);Number.isNaN(t.getTime())||null!=i.date||(i.date=t)}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(d),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=i.date||(i.date=new Date(t,0,1)))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,d),null!=i.lyrics||(i.lyrics=u.readId3V2Text(e,d))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,d),null!=i.comment||(i.comment=u.readId3V2Text(e,d))}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,d);const n=u.readU8(),s=u.readId3V2Text(e,d).trimEnd(),a=d-u.pos;if(a>=0){const e=u.readBytes(a);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===n?"coverFront":4===n?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=d}}};class to{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),n=this.bytes.subarray(t);this.bytes=new Uint8Array(r.length+i.length+n.length),this.bytes.set(r,0),this.bytes.set(i,r.length),this.bytes.set(n,r.length+i.length),this.view=new DataView(this.bytes.buffer)}removeFooter(){this.bytes=this.bytes.subarray(0,this.bytes.length-Qa),this.view=new DataView(this.bytes.buffer)}readBytes(e){const t=this.bytes.subarray(this.pos,this.pos+e);return this.pos+=e,t}readU8(){const e=this.view.getUint8(this.pos);return this.pos+=1,e}readU16(){const e=this.view.getUint16(this.pos,!1);return this.pos+=2,e}readU24(){const e=this.view.getUint16(this.pos,!1),t=this.view.getUint8(this.pos+1);return this.pos+=3,256*e+t}readU32(){const e=this.view.getUint32(this.pos,!1);return this.pos+=4,e}readAscii(e){let t="";for(let 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?Je(t):t;const r=this.readU16(),n=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:Je(t);s(e)&&(i=e)}return this.pos=n,{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 ja.ISO_8859_1:{let e="";for(let t=0;t<r.length;t++){const n=r[t];if(0===n){this.pos=i+t+1;break}e+=String.fromCharCode(n)}return e}case ja.UTF_16_WITH_BOM:if(255===r[0]&&254===r[1]){const e=new TextDecoder("utf-16le"),t=me(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=me(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=me(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),I.decode(r.subarray(0,e))}case ja.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=me(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 ja.UTF_8:{const e=me(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),I.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class io{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(i){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()}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.audioIterator)?void 0:e.return(),this.audioIterator=null})}handleNoAudioTrack(){this.audioSink=null,this.ensureAudioContext()}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.stopQueuedNodes(),this.paused=!0,this.playbackTimeAtStart=0,this.audioContextStartTime=0;const{input:i,audioTrack:r,duration:n}=e;return this.input=i,this.duration=n,r?null!==r.codec&&(yield r.canDecode())?(this.ensureAudioContext(r.sampleRate),this.audioSink=new oa(r),void(null==t||t())):(this.audioSink=null,this.ensureAudioContext(),void(null==t||t())):(this.handleNoAudioTrack(),void(null==t||t()))})}runIterator(e){return d(this,null,function*(){if(this.audioSink)for(yield this.stopIterator(),this.audioIterator=this.audioSink.buffers(this.currentTime);;){if(e!==this.asyncId||this.paused)return;const i=this.audioIterator.next(),r=setInterval(()=>{e!==this.asyncId||this.paused?clearInterval(r):"running"===this.audioContext.state&&this.audioContext.currentTime>=this.latestScheduledEndTime-.2&&(this.audioContext.suspend(),this.events.emit("waiting"))},50);let n;try{n=yield i}catch(t){console.error("Audio iterator error:",t);break}finally{clearInterval(r)}if(e!==this.asyncId||this.paused)return;if("suspended"===this.audioContext.state&&(yield this.audioContext.resume(),this.events.emit("canplay"),this.events.emit("playing")),n.done)break;const{buffer:s,timestamp:a}=n.value,o=this.audioContext.createBufferSource();o.buffer=s,o.connect(this.gainNode),o.playbackRate.value=this.playbackRate;const l=this.audioContextStartTime+(a-this.playbackTimeAtStart)/this.playbackRate,c=l+s.duration/this.playbackRate;c>this.latestScheduledEndTime&&(this.latestScheduledEndTime=c),l>=this.audioContext.currentTime?o.start(l):o.start(this.audioContext.currentTime,(this.audioContext.currentTime-l)*this.playbackRate),this.queuedNodes.add(o),o.onended=()=>this.queuedNodes.delete(o)}})}play(){return d(this,null,function*(){if(!this.paused)return;this.audioContext||this.ensureAudioContext(),"suspended"===this.audioContext.state&&(yield this.audioContext.resume()),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime,this.paused=!1;const e=++this.asyncId;this.runIterator(e)})}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime,this.paused=!0,this.stopIterator(),this.stopQueuedNodes())}seek(e){return d(this,null,function*(){this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext.currentTime,this.latestScheduledEndTime=this.audioContextStartTime;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(){var e;this.asyncId++,this.pause(),null==(e=this.audioContext)||e.close(),this.audioContext=null,this.input=null,this.audioSink=null}}const ro=/\.m3u8(?:$|[?#])/i;function no(e){return"string"===typeof e&&ro.test(e)}function so(e){const t=function(e){return"string"===typeof e?new Mn(e):e instanceof Blob?new An(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Nn(e):null!=e?e:null}(e);return t?new Ta({source:t,formats:no(e)?ws:vs}):null}function ao(e){return d(this,arguments,function*({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(Boolean),n=t||i,s=Boolean(n&&(yield n.isLive()));let a=Number.NaN;return r.length>0&&(a=yield e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==a||s||(a=yield e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:null!=a?a:Number.NaN})}function oo(e){return d(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}class lo{constructor({canvas:e,ctx:t,events:i,timeupdateInterval:r=250,avSyncTolerance:n=.12,dropLateFrames:s=!1,poster:a="",preflightRange:o=!1}){this.canvas=e,this.ctx=t,this.events=i,this.timeupdateInterval=r,this.avSyncTolerance=n,this.dropLateFrames=s,this.poster=a,this.preflightRange=o,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}preflight(e){return d(this,null,function*(){if(!this.preflightRange||"string"!==typeof e||no(e))return!0;try{const t=(yield fetch(e,{method:"HEAD"})).headers.get("accept-ranges");return!(!t||"none"===t)||(this.events.emit("error",new Event("RangeNotSupported")),!1)}catch(t){return console.warn("Preflight check failed:",t),!0}})}drawPoster(){if(!this.poster||this.posterDrawn)return;const e=new Image;e.onload=()=>{this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,this.ctx.drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e.src=this.poster}stopIterator(){return d(this,null,function*(){var e;yield null==(e=this.videoIterator)?void 0:e.return(),this.videoIterator=null})}clear(){this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height)}load(e,t){return d(this,null,function*(){++this.asyncId,yield this.stopIterator(),this.clear(),this.posterDrawn=!1;const{input:i,videoTrack:r,duration:n}=e;if(this.input=i,this.duration=n,!r)return this.handleNoVideoTrack(),void(null==t||t());if(null===r.codec||!(yield r.canDecode()))return this.handleNoVideoTrack(),void(null==t||t());const s=yield r.canBeTransparent();this.videoSink=new ra(r,{poolSize:2,fit:"contain",alpha:s}),this.width=r.displayWidth,this.height=r.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==t||t(),yield this.resetIterator(0)})}handleNoVideoTrack(){this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster()}resetIterator(e){return d(this,null,function*(){var t,i;if(yield this.stopIterator(),!this.videoSink)return;this.videoIterator=this.videoSink.canvases(e);const r=null!=(t=(yield this.videoIterator.next()).value)?t:null,n=null!=(i=(yield this.videoIterator.next()).value)?i:null;this.nextFrame=n,r?this.ctx.drawImage(r.canvas,0,0):this.drawPoster()})}updateNextFrame(e){return d(this,null,function*(){var t;if(this.videoIterator&&!this.isFetching){this.isFetching=!0;try{for(;;){const i=null!=(t=(yield this.videoIterator.next()).value)?t:null;if(!i||e!==this.asyncId)return;const r=this.audioClock.currentTime,n=this.dropLateFrames?Math.max(.06,this.avSyncTolerance/Math.max(1,this.playbackRate)):0;if(!(this.dropLateFrames&&i.timestamp<r-n)){if(!(i.timestamp<=r+n))return void(this.nextFrame=i);if(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(i.canvas,0,0),!this.dropLateFrames&&i.timestamp>r)return void(this.nextFrame=null)}}}finally{this.isFetching=!1}}})}render(){if(!this.audioClock)return;const e=this.audioClock.currentTime,t=Date.now();if(t-this.lastTimeUpdate>=this.timeupdateInterval&&(this.events.emit("timeupdate"),this.lastTimeUpdate=t),Number.isFinite(this.duration)&&e>=this.duration)return this.stop(),this.stalled=!1,this.events.emit("ended"),this.events.emit("pause"),void this.events.emit("canplay");this.nextFrame&&this.nextFrame.timestamp<=e?(this.ctx.clearRect(0,0,this.canvas.width,this.canvas.height),this.ctx.drawImage(this.nextFrame.canvas,0,0),this.nextFrame=null,this.updateNextFrame(this.asyncId),this.stalled&&(this.events.emit("canplay"),this.events.emit("playing"),this.stalled=!1)):this.nextFrame||(this.updateNextFrame(this.asyncId),!this.nextFrame&&Number.isFinite(this.duration)&&e<this.duration&&!this.stalled&&(this.stalled=!0,this.events.emit("waiting"))),this.rafId=requestAnimationFrame(()=>this.render())}start(e){this.audioClock=e,this.asyncId++,this.stalled=!1,this.updateNextFrame(this.asyncId),this.rafId=requestAnimationFrame(()=>this.render())}stop(){cancelAnimationFrame(this.rafId)}seek(e){return d(this,null,function*(){this.asyncId++,yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){this.asyncId++,this.stop(),this.stopIterator(),this.posterDrawn=!1,this.videoSink=null,this.input=null}}class co{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l,c;this.events=i,this.option=r,this.audio=new io(i),this.video=new lo({canvas:e,ctx:t,events:i,timeupdateInterval:null!=(n=r.timeupdateInterval)?n:250,avSyncTolerance:null!=(s=r.avSyncTolerance)?s:.12,dropLateFrames:null!=(a=r.dropLateFrames)&&a,poster:null!=(o=r.poster)?o:"",preflightRange:null!=(l=r.preflightRange)&&l}),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,null==(c=i.addEventListener)||c.call(i,"ended",()=>{this.ended=!0,this.paused=!0})}load(e){return d(this,null,function*(){const t=++this.loadSeq;this.pause(),this.disposeInput(),this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,setTimeout(()=>this.events.emit("waiting"),0),setTimeout(()=>this.events.emit("loadstart"),0);const i=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout:0;try{yield Promise.race([this.performLoad(e,t),i>0?this.createTimeout(i):new Promise(()=>{})])}catch(r){if(t!==this.loadSeq)return;this.loadSeq++,this.error={code:4,message:r.message},this.networkState=3,this.events.emit("error")}})}performLoad(e,t){return d(this,null,function*(){if(!(yield this.video.preflight(e)))return;const i=so(e);if(!i)return this.video.handleNoVideoTrack(),void this.audio.handleNoAudioTrack();const r=yield function(e,t){return d(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield ao({input:e,videoTrack:i,audioTrack:r});return{input:e,videoTrack:i,audioTrack:r,duration:n,isLive:!Number.isFinite(n)&&Boolean((i||r)&&(yield(i||r).isLive())),isHls:no(t),videoMode:no(t)?"auto":"manual",audioMode:no(t)?"auto":"manual"}})}(i,e);if(t!==this.loadSeq)return void i.dispose();this.disposeInput(),this.input=i,this.media=r;let n=!r.videoTrack,s=!r.audioTrack;const a=()=>{n&&s&&(this.readyState=1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"))};try{if(yield Promise.all([this.video.load(r,()=>{t===this.loadSeq&&(n=!0,a())}),this.audio.load(r,()=>{t===this.loadSeq&&(s=!0,a())})]),t!==this.loadSeq)return;this.readyState=4,this.networkState=1,this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("progress")}catch(o){if(t!==this.loadSeq)return;this.error={code:4,message:o.message},this.networkState=3,this.events.emit("error"),console.error("MediaBunny load error:",o)}})}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){var e;null==(e=this.input)||e.dispose(),this.input=null,this.media=null}replaceTracks(e){return d(this,arguments,function*({videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}){if(!this.media)return;const n=u(c({},this.media),{videoTrack:e,audioTrack:t,videoMode:i,audioMode:r}),s=!this.paused,a=this.currentTime;this.pause(),this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),n.duration=yield ao(n),this.media=n,yield Promise.all([this.video.load(n),this.audio.load(n)]),yield Promise.all([this.video.seek(a),this.audio.seek(a)]),this.readyState=4,this.networkState=1,this.seeking=!1,this.events.emit("loadedmetadata"),this.events.emit("durationchange"),this.events.emit("progress"),this.events.emit("loadeddata"),this.events.emit("canplay"),this.events.emit("canplaythrough"),this.events.emit("seeked"),s&&(yield this.play())})}selectHlsQuality(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getVideoTracks(),n="auto"===e?yield this.input.getPrimaryVideoTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.videoTrack;if(!n)return;let s=this.media.audioTrack,a=this.media.audioMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableAudioTrack(),a="auto"),yield this.replaceTracks({videoTrack:n,audioTrack:s,videoMode:"auto"===e?"auto":"manual",audioMode:a})})}selectHlsAudio(e){return d(this,null,function*(){var t,i;if(!(null==(t=this.media)?void 0:t.isHls)||!this.input)return;const r=yield this.input.getAudioTracks(),n="auto"===e?this.media.videoTrack?yield this.media.videoTrack.getPrimaryPairableAudioTrack():yield this.input.getPrimaryAudioTrack():null!=(i=r.find(t=>t.id===e))?i:this.media.audioTrack;if(!n)return;let s=this.media.videoTrack,a=this.media.videoMode;s&&n.canBePairedWith(s)||(s=yield n.getPrimaryPairableVideoTrack(),a="auto"),yield this.replaceTracks({videoTrack:s,audioTrack:n,videoMode:a,audioMode:"auto"===e?"auto":"manual"})})}getHlsState(){return function(e){return d(this,null,function*(){var t,i,r,n;if(!(null==e?void 0:e.isHls)||!e.input)return null;const[s,a]=yield Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[o,l]=yield Promise.all([Promise.all(s.map((e,t)=>d(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield oo(e)}}))),Promise.all(a.map((e,t)=>d(null,null,function*(){const i=yield e.getName(),r=yield e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:yield oo(e)}})))]);return{levels:o,audios:l,currentLevel:e.videoTrack&&null!=(t=o.find(t=>t.id===e.videoTrack.id))?t:null,currentAudio:e.audioTrack&&null!=(i=l.find(t=>t.id===e.audioTrack.id))?i:null,videoMode:null!=(r=e.videoMode)?r:"auto",audioMode:null!=(n=e.audioMode)?n:"auto"}})}(this.media)}play(){return d(this,null,function*(){this.paused&&(this.ended&&(this.ended=!1,yield this.seek(0)),this.paused=!1,yield this.audio.play(),this.video.start(this.audio),this.events.emit("play"),this.events.emit("playing"))})}pause(){this.paused||(this.paused=!0,this.audio.pause(),this.video.stop(),this.events.emit("pause"))}seek(e){return d(this,null,function*(){const t=!this.paused;this.ended=!1,this.seeking=!0,this.events.emit("seeking"),this.events.emit("waiting"),this.pause(),yield Promise.all([this.audio.seek(e),this.video.seek(e)]),this.seeking=!1,this.events.emit("seeked"),t&&!this.ended&&(yield this.play())})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}destroy(){this.pause(),this.disposeInput(),this.audio.destroy(),this.video.destroy()}get currentTime(){return this.audio.currentTime}get duration(){var e,t,i;return null!=(i=null!=(t=null==(e=this.media)?void 0:e.duration)?t:this.audio.duration)?i:this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}class uo{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new k,this.engine=new co({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=null!=(n=r.volume)?n:.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:(null==(s=e.option)?void 0:s.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){this.engine.seek(Number(e)||0)}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){const i=this.engine.duration;return!i||Number.isNaN(i)||t<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>e,end:()=>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){this._volume=function(e,t,i){return Math.max(t,Math.min(i,Number(e)||0))}(e,0,1),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 requestAnimationFrame(t=>{e(t,{presentationTime:this.engine.currentTime,expectedDisplayTime:t+16.6,width:this.engine.videoWidth,height:this.engine.videoHeight,mediaTime:this.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:t,receiveTime:t,rtpTimestamp:0})})}cancelVideoFrameCallback(e){cancelAnimationFrame(e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:this.canvas.setAttribute(e,t)}destroy(){this.engine.destroy()}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,n=r("canvas"),s=n.getContext("2d"),a=new uo({art:t,canvas:n,ctx:s,option:e});t.mediabunny=a;const o={};for(const e in n)"function"===typeof n[e]&&(o[e]=n[e].bind(n));const l=new Set([...Object.getOwnPropertyNames(a),...Object.getOwnPropertyNames(Object.getPrototypeOf(a))]);for(const e of l)"constructor"!==e&&(e in n||Object.defineProperty(n,e,{get(){const t=a[e];return"function"===typeof t?t.bind(a):t},set(t){a[e]=t},configurable:!0,enumerable:!0}));for(const e in o)n[e]=(...t)=>o[e](...t);function c(){var e;(null==(e=t.template)?void 0:e.$player)&&!t.option.autoSize&&Object.assign(n.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",c),t.on("video:loadedmetadata",c),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 n(t){e.setting.find(t)&&e.setting.remove(t)}function s(){r("mediabunny-quality"),n("mediabunny-quality")}function a(){r("mediabunny-audio"),n("mediabunny-audio")}function o(e={}){return e.control||e.setting}function l(r){return d(this,null,function*(){var n;const a=(null==(n=i.m3u8)?void 0:n.quality)||{};if(!o(a)||!(null==r?void 0:r.levels.length))return void s();const l=a.auto||"Auto",c=a.title||"Quality",h=a.getName||(e=>e.name||`${e.height}P`),f=r.currentLevel?h(r.currentLevel):l,m=g(r.levels.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentLevel)?void 0:t.id)===e.id}}),"html").sort((e,t)=>{const i=r.levels.find(t=>t.id===e.value),n=r.levels.find(e=>e.id===t.value);return((null==n?void 0:n.height)||0)-((null==i?void 0:i.height)||0)});m.push({html:l,value:"auto",default:!r.currentLevel});const p=i=>d(null,null,function*(){return yield t.switchM3u8Quality(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});a.control&&e.controls.update({name:"mediabunny-quality",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),a.setting&&e.setting.update({name:"mediabunny-quality",tooltip:f,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:m,onSelect:p})})}function c(r){return d(this,null,function*(){var n;const s=(null==(n=i.m3u8)?void 0:n.audio)||{};if(!o(s)||!(null==r?void 0:r.audios.length)||r.audios.length<2)return void a();const l=s.auto||"Auto",c=s.title||"Audio",h=s.getName||(e=>e.name||e.lang||e.language),f=r.currentAudio?h(r.currentAudio):l,m=g(r.audios.map(e=>{var t;return{html:h(e),value:e.id,default:(null==(t=r.currentAudio)?void 0:t.id)===e.id}}),"html");m.push({html:l,value:"auto",default:!r.currentAudio});const p=i=>d(null,null,function*(){return yield t.switchM3u8Audio(i.value),e.notice.show=`${c}: ${i.html}`,yield u(),i.html});s.control&&e.controls.update({name:"mediabunny-audio",position:"right",html:f,style:{padding:"0 10px"},selector:m,onSelect:p}),s.setting&&e.setting.update({name:"mediabunny-audio",tooltip:f,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:m,onSelect:p})})}function u(){return d(this,null,function*(){const e=yield t.getM3u8State();if(!e)return s(),void a();yield Promise.all([l(e),c(e)])})}}({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}});