diff --git a/docs/compiled/artplayer-proxy-mediabunny.js b/docs/compiled/artplayer-proxy-mediabunny.js index dceb215e3..099dbcd87 100644 --- a/docs/compiled/artplayer-proxy-mediabunny.js +++ b/docs/compiled/artplayer-proxy-mediabunny.js @@ -4,4 +4,4 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,a,s,n,o,c,l,u,h,d,f,m,p,g,k,y,b,w,T,S,v,P,I,x,C,B,E,_,R,F,A=e=>{throw TypeError(e)},M=(e,t,i)=>t.has(e)||A("Cannot "+i),D=(e,t,i)=>(M(e,t,"read from private field"),i?i.call(e):t.get(e)),N=(e,t,i)=>t.has(e)?A("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),O=(e,t,i,r)=>(M(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),L=(e,t,i)=>(M(e,t,"access private method"),i),z=(e,t,i,r)=>({set _(r){O(e,t,r,i)},get _(){return D(e,t,r)}});function U(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function q(e,t,i){const r={control:!1,setting:!1};let a=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function n(){a=null,U([()=>s("control"),()=>s("setting")])}return{update:function(o,c,l,u){if(!o)return void n();a=o;const h=()=>a===o&&l(),d=async e=>h()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html;c.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:d})):s("control"),h()&&(c.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:d})):s("setting"))},clear:n}}function W(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function H({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,a=0,s=0;const n=q(e,"mediabunny-quality",''),o=q(e,"mediabunny-audio",''),c=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;async function l(){if(r||t.engine.destroyed)return;const e=++a,s=t.engine.loadSeq,l=()=>e===a&&c(s);try{const e=await t.getM3u8State();if(!l())return;const r=i.m3u8?.quality||{},a=function(e,t,i){if(!t.control&&!t.setting||!e?.levels.length)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||`${e.height}P`),s=e.currentLevel?a(e.currentLevel):r,n=[];for(const l of e.levels){if(!i())return null;n.push({html:a(l),value:l.id,default:e.currentLevel?.id===l.id})}const o=new Map(e.levels.map(e=>[e.id,e.height])),c=W(n).sort((e,t)=>("auto"===t.value?0:o.get(t.value)||0)-("auto"===e.value?0:o.get(e.value)||0));return c.push({html:r,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:s,selector:c}}(e,r,l);if(!l())return;if(n.update(a,r,()=>c(s),(e,t)=>u("quality",e,t)),!l())return;const h=i.m3u8?.audio||{},d=function(e,t,i){if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||e.lang||e.language),s=e.currentAudio?a(e.currentAudio):r,n=[];for(const c of e.audios){if(!i())return null;n.push({html:a(c),value:c.id,default:e.currentAudio?.id===c.id})}const o=W(n);return o.push({html:r,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:s,selector:o}}(e,h,l);l()&&o.update(d,h,()=>c(s),(e,t)=>u("audio",e,t))}catch(h){if(l())throw h}}async function u(i,r,n){const o=++s,u=t.engine.loadSeq;a++;const d=()=>o===s&&c(u);try{"quality"===i?await t.switchM3u8Quality(r.value):await t.switchM3u8Audio(r.value),d()&&(await l(),d()&&(e.notice.show=`${n}: ${r.html}`))}catch(f){if(d()&&(await h(),d()))throw f}return r.html}function h(){return l().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function d(){a++,s++;try{U([n.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}return e.on("video:loadedmetadata",h),e.on("restart",h),e.on("video:loadstart",d),e.on("video:error",d),e.on("destroy",function t(){if(!r){r=!0,d();try{U([()=>e.off("video:loadedmetadata",h),()=>e.off("restart",h),()=>e.off("video:loadstart",d),()=>e.off("video:error",d),()=>e.off("destroy",t)])}catch(i){console.warn("MediaBunny HLS listener cleanup:",i)}}}),{update:l}}class V{constructor(){N(this,e,!1),this.listeners=new Map}addEventListener(t,i){D(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t)?.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){if(D(this,e))return;const r=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{D(this,e)||t(r)})}destroy(){O(this,e,!0),this.listeners.clear()}}function j(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const K=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},X=e=>e&&e[e.length-1],$=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-2**r)},Q=e=>{const t=$(e);return 0===(1&t)?-(t>>1):t+1>>1},Y=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),J=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Z=new TextDecoder,ee=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),te={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ie=ee(te),re={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ae=ee(re),se={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ne=ee(se),oe=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,ce={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},le=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class ue{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const he=/^[0-9a-fA-F]+$/,de=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),fe=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,me=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},ge=(e,t,i)=>{const r=pe(e,i(t),i);e.splice(r+1,0,t)},ke=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},ye=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},be=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},we=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Te=e=>{throw new Error(`Unexpected value: ${e}`)},Se=(e,t,i)=>{const r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},ve=(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)},Pe=(e,t)=>({async next(){const i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),Ie=(e,t,i)=>Math.max(t,Math.min(i,e)),xe="und",Ce=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Be=(e,t)=>Math.round(e/t)*t,Ee=(e,t)=>Math.round(e*t)/t,_e=(e,t)=>Math.floor(e/t)*t,Re=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},Fe=/^[a-z]{3}$/,Ae=e=>Fe.test(e),Me=1e6*(1+Number.EPSILON),De=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?Ne(e.headers):{},a=t.headers?Ne(t.headers):{},s={...r};Object.entries(a).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},Ne=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},Oe=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(n){if(a())throw n;s++;const e=r(s,n,t);if(null===e)throw n;if(ct._error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await at(1e3*e),a())throw n}};class Le{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ze=null;const Ue=()=>null!==ze?ze:ze=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let qe=null;const We=()=>null!==qe?qe:qe="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let He=null;const Ve=()=>null!==He?He:He=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),je=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,Ke=(async()=>{})().constructor,Xe=e=>e instanceof Ke||e instanceof Promise||"function"===typeof e?.then,$e=(e,t)=>-1!==e?e:t,Ge=(e,t,i,r)=>e<=r&&i<=t,Qe=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Je=e=>"number"===typeof e&&!Number.isNaN(e),Ze=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const a=e.indexOf("/",r+3);i=-1===a?e+t:e.slice(0,a)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const a=i.indexOf("://");if(-1!==a){const e=i.indexOf("/",a+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),n=[];for(const o of s)".."===o?n.pop():"."!==o&&n.push(o);return r+n.join("/")},et=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{j(Number.isInteger(e.num)),j(Number.isInteger(e.den)),j(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}},rt=(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.`)},at=e=>new Promise(t=>setTimeout(t,e));class st{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const r={fn:t,once:i?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(a){console.error(a)}s.once&&r.delete(s)}}}var nt,ot;(ot=nt||(nt={}))[ot.Silent=0]="Silent",ot[ot.Errors=1]="Errors",ot[ot.Warnings=2]="Warnings",ot[ot.Info=3]="Info";class ct{constructor(){}static get level(){return ct._level}static set level(e){if(e!==nt.Silent&&e!==nt.Errors&&e!==nt.Warnings&&e!==nt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ct._level=e}static get _emitter(){return ct._emitterInstance??(ct._emitterInstance=new st)}static on(e,t,i){return ct._emitter.on(e,t,i)}static _error(...e){ct._emitter._emit("error",e),ct._level>=nt.Errors&&console.error(...e)}static _warn(...e){ct._emitter._emit("warn",e),ct._level>=nt.Warnings&&console.warn(...e)}static _info(...e){ct._emitter._emit("info",e),ct._level>=nt.Info&&console.info(...e)}}ct._level=nt.Info,ct._emitterInstance=null;class lt{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 ut{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 ht={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class dt{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(7&this.pos),r=(t&1<>i;return this.pos++,r}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new dt(this.bytes);return e.pos=this.pos,e}}const ft=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],mt=[-1,1,2,3,4,5,6,8],pt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new dt(e),i=gt(t),{frequencyIndex:r,sampleRate:a}=kt(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=mt[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=kt(t).sampleRate,o=gt(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===gt(t)&&t.readBits(1)&&(l=kt(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(c=!!t.readBits(1)));break}t.pos=e+1}return null!==n&&n>1&&(c=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:c&&1===n?2:n}},gt=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},kt=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let a=0;t+3i&&(yield{offset:i,length:t-i}),i=t+a,t=i):t++}-1!==i&&i{if(t.description){const i=3&Y(t.description)[4];return It(e,i+1)}return Pt(e)},Ct=e=>31&e,Bt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Et.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Et,r),r+=Et.byteLength,i.set(a,r),r+=a.byteLength;return i},Rt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let a=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(a,s.byteLength);break;case 2:e.setUint16(a,s.byteLength,!1);break;case 3:ve(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Ft=e=>{try{const t=[],i=[],r=[];for(const o of Pt(e)){const a=e.subarray(o.offset,o.offset+o.length),s=Ct(a[0]);s===wt.SPS?t.push(a):s===wt.PPS?i.push(a):s===wt.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=Nt(a);j(null!==s);const n=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:n?s.chromaFormatIdc:null,bitDepthLumaMinus8:n?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:n?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:n?r:null}}catch(t){return ct._error("Error building AVC Decoder Configuration Record:",t),null}},At=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint8(i++),n=t.getUint8(i++),o=3&t.getUint8(i++),c=31&t.getUint8(i++),l=[];for(let f=0;f{try{const t=Bt(e),i=new dt(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();$(i);let n=1,o=0,c=0,l=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=$(i),3===n&&(l=i.readBits(1)),o=$(i),c=$(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==n?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,a=8;for(let e=0;ee.level>=s)??X(Ai),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);v=r,P=r}else v=0,P=0}return j(null!==P),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:S,colourPrimaries:y,matrixCoefficients:w,transferCharacteristics:b,fullRangeFlag:T,numReorderFrames:v,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:C,bitstreamRestrictionFlagBitOffset:I,bitstreamRestrictionFlag:x}}catch(t){return ct._error("Error parsing AVC SPS:",t),null}},Ot=e=>{const t=$(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)$(e),$(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Lt=e=>{j(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new dt(e.emulationUnpreventedBytes),r=new dt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(j(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),G(r,2),G(r,1),G(r,16),G(r,16),G(r,e.numReorderFrames),G(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return j(Number.isInteger(a)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,a))},zt=(e,t)=>{if(t.description){const i=3&Y(t.description)[21];return It(e,i+1)}return Pt(e)},Ut=e=>e>>1&63,qt=e=>{try{const t=new dt(Bt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Ht(t,i);$(t);const u=$(t);let h=0;3===u&&(h=t.readBits(1));const d=$(t),f=$(t);let m=d,p=f;if(t.readBits(1)){const e=$(t),i=$(t),r=$(t),a=$(t);let s=1,n=1;const o=0===h?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),m-=(e+i)*s,p-=(r+a)*n}const g=$(t),k=$(t);$(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)$(t),b=$(t),$(t);$(t),$(t),$(t),$(t),$(t),$(t),t.readBits(1)&&t.readBits(1)&&Vt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),$(t),$(t),t.skipBits(1));const w=$(t);if(jt(t,w),t.readBits(1)){const e=$(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of Pt(e)){const s=e.subarray(c.offset,c.offset+c.length),n=Ut(s[0]);n===St.VPS_NUT?t.push(s):n===St.SPS_NUT?i.push(s):n===St.PPS_NUT?r.push(s):n!==St.PREFIX_SEI_NUT&&n!==St.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=qt(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new dt(Bt(e));t.skipBits(16),$(t),$(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),$(t),$(t),Q(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&$(t),Q(t),Q(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType: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}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ut(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:n,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return ct._error("Error building HEVC Decoder Configuration Record:",t),null}},Ht=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let u=0;u<6;u++)n[u]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let u=0;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&Q(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){if(t===i){n=t-($(e)+1)}else n=t-1;e.readBits(1),$(e);const s=r[n]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=r[n]}else{const t=$(e),i=$(e);for(let r=0;r{let i=2,r=2,a=2,s=0,n=0,o={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{const e=Dt[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&($(e),$(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&($(e),$(e),$(e),$(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&$(e),e.readBits(1)&&$t(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=$(e),$(e),$(e),$(e),$(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},$t=(e,t,i)=>{let r=!1,a=!1,s=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?$(e):i=1===e.readBits(1);let n=1;if(!i){n=$(e)+1}r&&Gt(e,n,s),a&&Gt(e,n,s)}},Gt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=Qt.audAllowed;for(const s of zt(e,t)){if(r===Qt.noMoreDataAllowed){i.add(s.offset);continue}const t=Ut(e[s.offset]);if(r===Qt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>Qt.audAllowed?a=!0:r=Qt.beforeFirstVcl:t<=31?r>Qt.afterFirstVcl?a=!0:r=Qt.afterFirstVcl:36===t?r!==Qt.afterFirstVcl?a=!0:r=Qt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>Qt.beforeFirstVcl?a=!0:r=Qt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&Y(t.description)[21];return Rt(e,i+1)}return _t(e)})(a,t)},Zt={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},ei=e=>{const t=new dt(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(r>=2){a=t.readBits(1)?12:10}const s=t.readBits(3);let n=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);n=e||i?e&&!i?2:1:3,t.skipBits(1)}else n=1}else n=3,o=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let l=X(Mi).level;for(const h of Mi)if(c<=h.maxPictureSize){l=h.level;break}const u=Zt[s];return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:u?.colourPrimaries??2,transferCharacteristics:u?.transferCharacteristics??2,matrixCoefficients:u?.matrixCoefficients??2}},ti=function*(e){const t=new dt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*2**(7*i),!(128&r))break;if(7===i&&128&r)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),a=t.readBits(1),s=t.readBits(1);let n;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;n=e}else n=Math.floor(t.getBitsLeft()/8);j(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},ii=e=>{for(const{type:t,data:i}of ti(e)){if(1!==t)continue;const e=new dt(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const h=l+1;e.skipBits(h);let d=0;if(d=a?0:e.readBits(1),d&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},ri=e=>{if(e.length<36)return null;const t=J(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},ai=[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],si=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;u97;)if(1===r.readBits(1)){a=r.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;r.getBitsLeft()>=97;){const e=r.pos,t=r.readBits(8),i=r.readBits(16),a=r.readBits(16);if(t>63||0!==i||0!==a){r.pos=e;break}if(r.skipBits(1),s++,s>64)break;r.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;r.pos=0,r.skipBits(a);const l=Array(c).fill(0);for(let u=c-1;u>=0;u--)r.skipBits(40),l[u]=r.readBits(1);return{modeBlockflags:l}},ni=(e,t,i)=>{switch(e){case"avc":for(const e of xt(i,t)){const t=i[e.offset],r=Ct(t);if(r>=wt.NON_IDR_SLICE&&r<=wt.SLICE_DPC)return"delta";if(r===wt.IDR)return"key";if(r===wt.SEI&&!Ve()){const t=i.subarray(e.offset,e.offset+e.length),r=Bt(t);let a=1;do{let e=0;for(;;){const t=r[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new dt(r);e.pos=8*a;const t=$(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=J(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=Z.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(i=t.raw).vendor??(i.vendor=o));const c=a.getUint32(s,!0);s+=4;for(let l=0;l0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=l.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.discNumber??(t.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??(t.discsTotal=r))}break;case"DISCTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(l);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=l);break;case"METADATA_BLOCK_PICTURE":{const e=Qe(l),i=J(e),r=i.getUint32(0,!1),a=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=i.getUint32(8+a,!1),o=Z.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),u=e.subarray(a+n+32,a+n+32+c);t.images??(t.images=[]),t.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},ui=[2,1,2,3,3,4,4,5],hi=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),a=t.readBits(5);if(a>8)return null;const s=t.readBits(3),n=t.readBits(3);0!==(1&n)&&1!==n&&t.skipBits(2),0!==(4&n)&&t.skipBits(2),2===n&&t.skipBits(2);return{fscod:i,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},di=[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],fi=[1,2,3,6],mi=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),a=t.readBits(2);let s,n=0;3===a?(n=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;const u=fi[s];let h;h=a<3?yt[a]/1e3:bt[n]/1e3;return{dataRate:Math.round((r+1)*h/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},pi=e=>{const t=e.substreams[0];return j(t),t.fscod<3?yt[t.fscod]:null!==t.fscod2&&t.fscod2<3?bt[t.fscod2]:null},gi=e=>{const t=e.substreams[0];j(t);let i=ui[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},ki=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],yi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],bi=[16,16,20,20,0,24,24,0],wi=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ti=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Si=[32e3,44100,48e3,0],vi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Pi=[512,1024,2048,4096],Ii=e=>{const t=Ci(e),i=J(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Bi(e.subarray(r));if(!t)break;a??(a=t),r+=t.frameSize}if(t)return{frameSize:a?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==a};if(!a?.asset)return null;const{asset:s}=a;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},xi=e=>{const t=Ii(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Ci=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new dt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const a=t.readBits(14)+1;if(a<96)return null;const s=t.readBits(6);if(s>=wi.length)return null;const n=ki[t.readBits(4)];if(0===n)return null;const o=yi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const c=t.readBits(2);if(3===c)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const l=bi[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:wi[s]+(u?1:0),sampleCount:32*r,channelLayout:Ti[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Bi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new dt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),a=8+4*r,s=16+4*r;t.skipBits(a);const n=t.readBits(s)+1,o={frameSize:n,asset:null};if(!t.readBits(1))return o;const c=Si[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,h=t.readBits(3)+1,d=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===c||t.getBitsLeft()<0?o:{frameSize:n,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:f}}},Ei=e=>Re(e)+Re(44646&e),_i=["avc","hevc","vp9","av1","vp8","prores"],Ri=["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"],Fi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Ri],Ai=[{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}],Mi=[{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}],Di=".01.01.01.01.00",Ni=".0.110.01.01.01.0",Oi=["ap4x","ap4h","apch","apcn","apcs","apco"],Li=["dtsc","dtsh","dtsl","dtse"],zi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o,proresFormat:c}=e;if("avc"===t){if(j(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${de(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}.${de(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=fe(s.generalProfileCompatibilityFlags),a=s.generalTierFlag,n=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=J(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=fe(s.getUint32(2)),a=c>>5&1,n=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=r.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=n;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!n){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${n.profile.toString().padStart(2,"0")}.${n.level.toString().padStart(2,"0")}.${n.bitDepth.toString().padStart(2,"0")}.${n.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${n.colourPrimaries.toString().padStart(2,"0")}.${n.transferCharacteristics.toString().padStart(2,"0")}.${n.matrixCoefficients.toString().padStart(2,"0")}.${n.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Di)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),a=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),n=o.monochrome?"1":"0",c=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),l=r?.primaries?te[r.primaries]:1,u=r?.transfer?re[r.transfer]:1,h=r?.matrix?se[r.matrix]:1,d=r?.fullRange?1:0;let f=`av01.${t}.${i}${a}.${s}`;return f+=`.${n}.${c.toString().padStart(3,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${d}`,f.endsWith(Ni)&&(f=f.slice(0,-17)),f}if("prores"===t)return c??"apch";throw null!==t&&Te(t),new TypeError(`Unhandled codec '${t}'.`)},Ui=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Mt(e.codecDescription)?.sequenceParameterSets[0]),t){const e=Nt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===St.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),h=(15&t.getUint8(i++))<<8|t.getUint8(i++),d=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,w=k>>2&1,T=3&k,S=t.getUint8(i++),v=[];for(let P=0;P>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===St.SPS_NUT)?.nalUnits[0]),t){const e=qt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ie[e.vp9CodecInfo.colourPrimaries],transfer:ae[e.vp9CodecInfo.transferCharacteristics],matrix:ne[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ie[e.av1CodecInfo.colourPrimaries],transfer:ae[e.av1CodecInfo.transferCharacteristics],matrix:ne[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ie[e.proresCodecInfo.colourPrimaries],transfer:ae[e.proresCodecInfo.transferCharacteristics],matrix:ne[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},qi=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=pt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return a??"dtsc";if(t&&Ri.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Wi=48e3,Hi=/^pcm-([usf])(\d+)(be)?$/,Vi=e=>{if(j(Ri.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=Hi.exec(e);let i;j(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},ji=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":Oi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":Li.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Hi.test(e)?e:"webvtt"===e?"webvtt":null,Ki=[44100,48e3,32e3],Xi=[-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],$i=1483304551,Gi=1231971951,Qi=(e,t)=>3===e?3===t?21:36:3===t?13:21,Yi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,h=s>>6&3,d=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Xi[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=Ki[u]>>n+o,b=((e,t,i,r,a)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Zi,er;(er=Zi||(Zi={}))[er.FrameCount=1]="FrameCount",er[er.FileSize=2]="FileSize",er[er.Toc=4]="Toc";const tr=e=>3===e?1:2;class ir{constructor(e){this.input=e}dispose(){}}const rr=new Uint8Array(0);class ar{constructor(e,t,i,r,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=a,e===rr&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!==typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===rr}get microsecondTimestamp(){return Math.trunc(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new ar(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new ar(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const sr=e=>{const t=J(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=de(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=uc(e);const i=bc(e,4);let r=8;1===t&&(t=mc(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},cr=e=>dc(e)/65536,lr=e=>dc(e)/1073741824,ur=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=ac(e);if(t|=127&i,0===(128&i))break}return t},hr=e=>{let t=nc(e);return e.skip(2),t=Math.min(t,e.remainingLength),Z.decode(rc(e,t))},dr=e=>{const t=or(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=uc(e);e.skip(4);const r=rc(e,t.contentSize-8);switch(i){case 1:return Z.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new lt(r,"image/jpeg");case 14:return new lt(r,"image/png");case 27:return new lt(r,"image/bmp");default:return r}},fr=16,mr=new Uint32Array(256),pr=new Uint32Array(256),gr=new Uint32Array(256),kr=new Uint32Array(256),yr=new Uint32Array(256),br=new Uint32Array(256),wr=new Uint32Array(10);let Tr=!1;class Sr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(fr/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(fr),this.out=new Uint8Array(fr),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){j(16===e.byteLength),j(16===t.byteLength),Tr||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,n=1;s<256;s++)i[s]=n,t[n]=s,n=n^n<<1^(128&n?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let a=r^r<<1^r<<2^r<<3^r<<4;a=a>>>8^255&a^99,e[s]=a}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);mr[s]=t<<24|t<<16|t<<8|t,br[s]=i<<24|i<<16|i<<8|i;const a=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);pr[s]=a,gr[s]=a>>>8|a<<24,kr[s]=a>>>16|a<<16,yr[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)wr[s]=a<<24,a=a<<1^(128&a?283:0);Tr=!0})();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let a=4;a<44;a+=4){const e=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^4278190080&mr[e>>>16&255]^16711680&mr[e>>>8&255]^65280&mr[e>>>0&255]^255&mr[e>>>24&255]^wr[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a>>24&255]]^gr[255&mr[t>>>16&255]]^kr[255&mr[t>>>8&255]]^yr[255&mr[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,h;for(let g=1;g<10;g++){const a=4*g;c=pr[e>>>24]^gr[r>>>16&255]^kr[i>>>8&255]^yr[255&t]^this.roundkey[a],l=pr[t>>>24]^gr[e>>>16&255]^kr[r>>>8&255]^yr[255&i]^this.roundkey[a+1],u=pr[i>>>24]^gr[t>>>16&255]^kr[e>>>8&255]^yr[255&r]^this.roundkey[a+2],h=pr[r>>>24]^gr[i>>>16&255]^kr[t>>>8&255]^yr[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=h}const d=4278190080&br[e>>>24&255]^16711680&br[r>>>16&255]^65280&br[i>>>8&255]^255&br[t>>>0&255]^this.roundkey[40],f=4278190080&br[t>>>24&255]^16711680&br[e>>>16&255]^65280&br[r>>>8&255]^255&br[i>>>0&255]^this.roundkey[41],m=4278190080&br[i>>>24&255]^16711680&br[t>>>16&255]^65280&br[e>>>8&255]^255&br[r>>>0&255]^this.roundkey[42],p=4278190080&br[r>>>24&255]^16711680&br[i>>>16&255]^65280&br[t>>>8&255]^255&br[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,d^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class vr extends ir{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Xe(r)&&(r=await r),!r)break;const a=e,s=or(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=bc(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Xe(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>a+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=a+s.totalSize}if(!i&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){j(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Xe(e)&&(e=await e),j(e);const t=uc(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Xe(e)&&(e=await e),e){const t=or(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Xe(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==vr)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const i of t.tracks){const e={id:i.id,demuxer:this,trackBacking:null,disposition:i.disposition,timescale:i.timescale,durationInMediaTimescale:i.durationInMediaTimescale,durationInMovieTimescale:i.durationInMovieTimescale,rotation:i.rotation,internalCodecId:i.internalCodecId,name:i.name,languageCode:i.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:i.editListPreviousSegmentDurations,editListOffset:i.editListOffset,encryptionInfo:i.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:i.info};if(i.trackBacking)if(j(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ir(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new xr(t),this.tracks.push(e)}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,null===e.sampleTableByteOffset)return t;j(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(i),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Ri.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){j("audio"===e.info?.type);const i=Vi(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),u=t.sampleTimingEntries[l],h=pe(t.sampleTimingEntries,c,e=>e.startIndex),d=t.sampleTimingEntries[h],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta-f,p=X(r);p&&p.delta===m?p.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:f,count:1,delta:m});const g=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(g)}n.startSampleIndex=n.startChunkIndex,n.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let i=0;ie.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===a.moofOffset);if(i)Rr(s,i.timestamp);else{const e=pe(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Rr(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=pe(t,s.startTimestamp,e=>e.startTimestamp);if(-1!==i&&t[i].moofOffset===a.moofOffset||t.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:s.startTimestamp,endTimestamp:s.endTimestamp}),s.encryptionAuxInfo&&e.encryptionInfo){const t=await Dr(this.reader,e.encryptionInfo,s.encryptionAuxInfo);for(let e=0;e0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ae(t.languageCode)||(t.languageCode=xe)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=bc(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...ce},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=M,this.readContiguousBoxes(e.slice(N,D.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=ac(e);e.skip(3);const r=uc(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*uc(e),e.skip(8)):2===n&&(e.skip(4),l=yc(e),o=uc(e),e.skip(4),c=uc(e),u=uc(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const h="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===h);else if("opus"===h)t.info.codec="opus",t.info.sampleRate=Wi;else if("flac"===h)t.info.codec="flac";else if("ulaw"===h)t.info.codec="ulaw";else if("alaw"===h)t.info.codec="alaw";else if("ac-3"===h)t.info.codec="ac3";else if("ec-3"===h)t.info.codec="eac3";else if(Li.includes(h))t.info.codec="dts",t.info.dtsFormat=h;else if("twos"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ct._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(ct._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===h)t.info.codec="pcm-u8";else if("in24"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===h){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":(ct._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":(ct._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===h){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===h&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==ac(e),t.encryptionInfo.defaultPerSampleIvSize=ac(e),t.encryptionInfo.defaultKid=de(rc(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=ac(e),r=new Uint8Array(16);r.set(rc(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(4);const i=ac(e),r=ac(e),a=ac(e),s=a>>4,n=a>>1&7,o=1&a,c=ac(e),l=ac(e),u=ac(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case"av1C":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(1);const i=ac(e),r=i>>5,a=31&i,s=ac(e),n=s>>7,o=s>>6&1,c=s>>4&1,l=s>>3&1,u=s>>2&1,h=3&s,d=2===r&&o?s>>5&1?12:10:o?10:8;e.skip(1);const f=rc(e,D.contentSize-4),m=ii(f);t.info.av1CodecInfo={profile:r,level:a,tier:n,bitDepth:d,monochrome:c,chromaSubsamplingX:l,chromaSubsamplingY:u,chromaSamplePosition:h,videoFullRangeFlag:m?.videoFullRangeFlag??0,colourPrimaries:m?.colourPrimaries??2,transferCharacteristics:m?.transferCharacteristics??2,matrixCoefficients:m?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=bc(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=nc(e),a=nc(e),s=nc(e);let n;"nclx"===i&&(n=Boolean(128&ac(e))),t.info.colorSpace={primaries:ie[r],transfer:ae[a],matrix:ne[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=uc(e),r=uc(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==t.info?.type)break;e.skip(4);j(3===ac(e)),ur(e),e.skip(2);const i=ac(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=ac(e);e.skip(t)}a&&e.skip(2);j(4===ac(e));const s=ur(e),n=e.filePos,o=ac(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":ct._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-n){j(5===ac(e));const i=ur(e);if(t.info.codecDescription=rc(e,i),"aac"===t.info.codec){const e=pt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&nc(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=ac(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=ac(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(1);const i=ac(e),r=nc(e),a=uc(e),s=cc(e),n=ac(e);let o;o=0!==n?rc(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,i),l.setUint16(10,r,!0),l.setUint32(12,a,!0),l.setInt16(16,s,!0),l.setUint8(18,n),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=127,r=128,a=e.filePos;for(;e.filePos>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(a&r)break}const s=e.filePos;e.filePos=a;const n=rc(e,s-a),o=new Uint8Array(4+n.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(n,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=rc(e,3),r=new dt(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=yt[a]),t.info.numberOfChannels=ui[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new dt(e),i=t.readBits(13),r=t.readBits(3),a=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),n=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let c=0;o>0?c=t.readBits(9):t.skipBits(1),a.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:n,numDepSub:o,chanLoc:c})}return 0===a.length?null:{dataRate:i,substreams:a}})(rc(e,D.contentSize));if(!i){ct._warn("Invalid dec3 box contents, ignoring.");break}const r=pi(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=gi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=J(e),i=t.getUint32(0);if(0===i)return null;const r=new dt(e);r.seekToByte(13);const a=r.readBits(2);r.skipBits(5);const s=r.readBits(1),n=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return 0!==o?c=Ei(o):ne.id===i);if(!r)break;const a=uc(e),s=(12&a)>>2,n=3&a,o=[ac,nc,oc,uc],c=o[(48&a)>>4],l=o[s],u=o[n],h=uc(e);for(let d=0;de.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let a=0;ae.id===l);if(!u)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=mc(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=uc(e)),a&&(u.currentFragmentState.defaultSampleDuration=uc(e)),s&&(u.currentFragmentState.defaultSampleSize=uc(e)),n&&(u.currentFragmentState.defaultSampleFlags=uc(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;j(t.currentFragmentState);const i=ac(e);e.skip(3);const r=0===i?uc(e):mc(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;j(this.currentFragment),j(t.currentFragmentState);const i=ac(e),r=oc(e),a=Boolean(1&r),s=Boolean(4&r),n=Boolean(256&r),o=Boolean(512&r),c=Boolean(1024&r),l=Boolean(2048&r),u=uc(e);let h=null;a&&(h=dc(e));let d,f=null;s&&(f=uc(e)),this.currentFragment.trackData.has(t.id)?(d=this.currentFragment.trackData.get(t.id),null!==h&&(d.currentOffset=t.currentFragmentState.baseDataOffset+h)):(d={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(h??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,d));for(let m=0;m0&&(a=rc(e,r));const s=Mr(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=ac(e);if(1&oc(e)){const i=bc(e,4),r=uc(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=uc(e);if(0===r)break;r>1&&ct._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?uc(e):Number(mc(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Mr(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;j(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=oc(e),a=Boolean(2&r),s=uc(e),n=t.encryptionInfo.defaultPerSampleIvSize;j(null!==n);for(let o=0;o0?r.set(rc(e,n),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=nc(e);s=[];for(let i=0;i0&&((B=this.metadataTags).trackNumber??(B.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((E=this.metadataTags).tracksTotal??(E.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((_=this.metadataTags).trackNumber??(_.trackNumber=t)),i>0&&((R=this.metadataTags).tracksTotal??(R.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((F=this.metadataTags).discNumber??(F.discNumber=t)),i>0&&((A=this.metadataTags).discsTotal??(A.discsTotal=i))}}}}}return e.filePos=O,!0}}class Pr{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;j(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return(t?.timestamp??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ce(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Cr(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Ar(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=pe(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=we(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 j(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Er(i,e);if(!r)return null;let a;if(t.metadataOnly)a=rr;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Xe(t)&&(t=await t),!t)return null;if(a=rc(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Dr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),u=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,h=pe(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),d=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(u?.moofOffset??0,d?.moofOffset??0)||null;let m;for(e?null===f||e.moofOffset>=f?(m=e.moofOffset+e.moofSize,n=e):m=f:m=f??0;;){if(n){const e=n.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(m,8,16);if(Xe(e)&&(e=await e),!e)break;const i=m,l=or(e);if(!l)break;if("moof"===l.name){n=await s.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(n);if(r)return this.fetchPacketInFragment(n,e,a);-1!==e&&(o=n,c=e)}m=i+l.totalSize}if(u&&(!o||o.moofOffset{var e,t,i,r,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&ri(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&ii(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&ei(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else{const e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Wt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Ft(e.data)}if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(this.internalTrack.info);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const s={codec:zi(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(s.displayAspectWidth=this.internalTrack.info.squarePixelWidth,s.displayAspectHeight=this.internalTrack.info.squarePixelHeight),s})()):null}}class xr extends Pr{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Cr=(e,t)=>{if(e.presentationTimestamps){const i=pe(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=pe(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)}},Br=(e,t)=>{if(!e.keySampleIndices)return Cr(e,t);if(e.presentationTimestamps){const i=pe(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!==me(e.keySampleIndices,i,e=>e))return i}return-1}{const i=Cr(e,t),r=pe(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Er=(e,t)=>{const i=pe(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=pe(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),n=e.sampleCompositionTimeOffsets[s];n&&t-n.startIndexe.startSampleIndex),l=e.sampleToChunk[c];j(l);const u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),h=e.chunkOffsets[u],d=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk;let f=0,m=h;if(1===e.sampleSizes.length)m+=o*(t-d),f+=o*l.samplesPerChunk;else for(let g=d;ge)}},_r=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=pe(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Rr=(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},Fr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Ar=e=>0===e.sampleSizes.length,Mr=e=>{var t;return e.currentFragmentState?(t=e.currentFragmentState).encryptionAuxInfo??(t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):e.encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},Dr=async(e,t,i)=>{if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{j(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[o],r=new Uint8Array(16);s>0?r.set(rc(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=nc(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Or=async(e,t,i,r)=>{j(e.encryptionInfo);const a=e.encryptionInfo;j(null!==a.defaultKid);const s=a.defaultKid;let n;const o=e.demuxer.decryptionKeyCache.get(s);if(o)n=await o;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(s));for(let e=0;e{j(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const a=new Uint8Array(16);a.set(i.iv,0);const s=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),n=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:a,length:64},s,e);return new Uint8Array(t)};if(!i.subsamples)return n(r);j(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Ur(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let c=0;for(const m of o)for(const e of m.perSubsample)c+=e.length;const l=new Uint8Array(c);let u=0;for(const m of o)for(const e of m.perSubsample)l.set(r.subarray(e.offset,e.offset+e.length),u),u+=e.length;const h=await n(l),d=new Uint8Array(r);let f=0;for(const m of o)for(const e of m.perSubsample)d.set(h.subarray(f,f+e.length),e.offset),f+=e.length;return d},zr=(e,t,i,r)=>{const a=new Sr;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,n=t.defaultSkipByteBlock;if(j(null!==s&&null!==n),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{const r=[],a=0!==t||0!==i;let s=0;for(const n of e){s+=n.clearLen;const e=[];if(a){let r=n.protectedLen,a=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:a,length:s}),a+=s,r-=s;const n=Math.min(16*i,r);a+=n,r-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;r.push({perSubsample:e})}return r};var qr,Wr;(Wr=qr||(qr={}))[Wr.EBML=440786851]="EBML",Wr[Wr.EBMLVersion=17030]="EBMLVersion",Wr[Wr.EBMLReadVersion=17143]="EBMLReadVersion",Wr[Wr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Wr[Wr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Wr[Wr.DocType=17026]="DocType",Wr[Wr.DocTypeVersion=17031]="DocTypeVersion",Wr[Wr.DocTypeReadVersion=17029]="DocTypeReadVersion",Wr[Wr.Void=236]="Void",Wr[Wr.Segment=408125543]="Segment",Wr[Wr.SeekHead=290298740]="SeekHead",Wr[Wr.Seek=19899]="Seek",Wr[Wr.SeekID=21419]="SeekID",Wr[Wr.SeekPosition=21420]="SeekPosition",Wr[Wr.Duration=17545]="Duration",Wr[Wr.Info=357149030]="Info",Wr[Wr.TimestampScale=2807729]="TimestampScale",Wr[Wr.MuxingApp=19840]="MuxingApp",Wr[Wr.WritingApp=22337]="WritingApp",Wr[Wr.Tracks=374648427]="Tracks",Wr[Wr.TrackEntry=174]="TrackEntry",Wr[Wr.TrackNumber=215]="TrackNumber",Wr[Wr.TrackUID=29637]="TrackUID",Wr[Wr.TrackType=131]="TrackType",Wr[Wr.FlagEnabled=185]="FlagEnabled",Wr[Wr.FlagDefault=136]="FlagDefault",Wr[Wr.FlagForced=21930]="FlagForced",Wr[Wr.FlagOriginal=21934]="FlagOriginal",Wr[Wr.FlagHearingImpaired=21931]="FlagHearingImpaired",Wr[Wr.FlagVisualImpaired=21932]="FlagVisualImpaired",Wr[Wr.FlagCommentary=21935]="FlagCommentary",Wr[Wr.FlagLacing=156]="FlagLacing",Wr[Wr.Name=21358]="Name",Wr[Wr.Language=2274716]="Language",Wr[Wr.LanguageBCP47=2274717]="LanguageBCP47",Wr[Wr.CodecID=134]="CodecID",Wr[Wr.CodecPrivate=25506]="CodecPrivate",Wr[Wr.CodecDelay=22186]="CodecDelay",Wr[Wr.SeekPreRoll=22203]="SeekPreRoll",Wr[Wr.DefaultDuration=2352003]="DefaultDuration",Wr[Wr.Video=224]="Video",Wr[Wr.PixelWidth=176]="PixelWidth",Wr[Wr.PixelHeight=186]="PixelHeight",Wr[Wr.DisplayWidth=21680]="DisplayWidth",Wr[Wr.DisplayHeight=21690]="DisplayHeight",Wr[Wr.DisplayUnit=21682]="DisplayUnit",Wr[Wr.AlphaMode=21440]="AlphaMode",Wr[Wr.Audio=225]="Audio",Wr[Wr.SamplingFrequency=181]="SamplingFrequency",Wr[Wr.Channels=159]="Channels",Wr[Wr.BitDepth=25188]="BitDepth",Wr[Wr.SimpleBlock=163]="SimpleBlock",Wr[Wr.BlockGroup=160]="BlockGroup",Wr[Wr.Block=161]="Block",Wr[Wr.BlockAdditions=30113]="BlockAdditions",Wr[Wr.BlockMore=166]="BlockMore",Wr[Wr.BlockAdditional=165]="BlockAdditional",Wr[Wr.BlockAddID=238]="BlockAddID",Wr[Wr.BlockDuration=155]="BlockDuration",Wr[Wr.ReferenceBlock=251]="ReferenceBlock",Wr[Wr.Cluster=524531317]="Cluster",Wr[Wr.Timestamp=231]="Timestamp",Wr[Wr.Cues=475249515]="Cues",Wr[Wr.CuePoint=187]="CuePoint",Wr[Wr.CueTime=179]="CueTime",Wr[Wr.CueTrackPositions=183]="CueTrackPositions",Wr[Wr.CueTrack=247]="CueTrack",Wr[Wr.CueClusterPosition=241]="CueClusterPosition",Wr[Wr.Colour=21936]="Colour",Wr[Wr.MatrixCoefficients=21937]="MatrixCoefficients",Wr[Wr.TransferCharacteristics=21946]="TransferCharacteristics",Wr[Wr.Primaries=21947]="Primaries",Wr[Wr.Range=21945]="Range",Wr[Wr.Projection=30320]="Projection",Wr[Wr.ProjectionType=30321]="ProjectionType",Wr[Wr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Wr[Wr.Attachments=423732329]="Attachments",Wr[Wr.AttachedFile=24999]="AttachedFile",Wr[Wr.FileDescription=18046]="FileDescription",Wr[Wr.FileName=18030]="FileName",Wr[Wr.FileMediaType=18016]="FileMediaType",Wr[Wr.FileData=18012]="FileData",Wr[Wr.FileUID=18094]="FileUID",Wr[Wr.Chapters=272869232]="Chapters",Wr[Wr.Tags=307544935]="Tags",Wr[Wr.Tag=29555]="Tag",Wr[Wr.Targets=25536]="Targets",Wr[Wr.TargetTypeValue=26826]="TargetTypeValue",Wr[Wr.TargetType=25546]="TargetType",Wr[Wr.TagTrackUID=25541]="TagTrackUID",Wr[Wr.TagEditionUID=25545]="TagEditionUID",Wr[Wr.TagChapterUID=25540]="TagChapterUID",Wr[Wr.TagAttachmentUID=25542]="TagAttachmentUID",Wr[Wr.SimpleTag=26568]="SimpleTag",Wr[Wr.TagName=17827]="TagName",Wr[Wr.TagLanguage=17530]="TagLanguage",Wr[Wr.TagString=17543]="TagString",Wr[Wr.TagBinary=17541]="TagBinary",Wr[Wr.ContentEncodings=28032]="ContentEncodings",Wr[Wr.ContentEncoding=25152]="ContentEncoding",Wr[Wr.ContentEncodingOrder=20529]="ContentEncodingOrder",Wr[Wr.ContentEncodingScope=20530]="ContentEncodingScope",Wr[Wr.ContentCompression=20532]="ContentCompression",Wr[Wr.ContentCompAlgo=16980]="ContentCompAlgo",Wr[Wr.ContentCompSettings=16981]="ContentCompSettings",Wr[Wr.ContentEncryption=20533]="ContentEncryption";const Hr=[qr.EBML,qr.Segment],Vr=[qr.SeekHead,qr.Info,qr.Cluster,qr.Tracks,qr.Cues,qr.Attachments,qr.Chapters,qr.Tags],jr=[...Hr,...Vr],Kr=16,Xr=e=>{if(e.remainingLength<1)return null;const t=ac(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=ac(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=Xr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===ac(e))return;e.skip(-1);const t=$r(e);return null===t?null:72057594037927940!==t?t:void 0},Jr=e=>{j(e.remainingLength>=2);const t=Qr(e);if(null===t)return null;const i=Yr(e);return null===i?null:{id:t,size:i}},Zr=(e,t)=>{const i=rc(e,t);let r=0;for(;r{const i=rc(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?kc(e):yc(e)},ia=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},ra=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;se.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,Kr);if(Xe(t)&&(t=await t),!t)break;const i=Jr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===qr.EBML){ya(a);let e=this.reader.requestSlice(s,a);if(Xe(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===qr.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===qr.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await ia(this.reader,s,jr,this.reader.fileSize)).pos-s}const e=X(this.segments);e&&(e.elementEndPos=s+a)}ya(a),e=s+a}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;null===this.currentSegment.elementEndPos||ie.id===a);if(-1!==o){const e=Ia[o].flag;this.currentSegment[e]=!0,ya(s);let t=this.reader.requestSlice(n,s);Xe(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===qr.Tags||a===qr.Attachments){a===qr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ya(s);let e=this.reader.requestSlice(n,s);Xe(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===qr.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Ia.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,Kr);if(Xe(i)&&(i=await i),!i)continue;const r=Jr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;ya(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);Xe(o)&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const n of this.currentSegment.tracks)null!==n.defaultDurationNs&&(n.defaultDuration=this.currentSegment.timestampFactor*n.defaultDurationNs/1e9);const r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const n of this.currentSegment.cuePoints){const e=r.get(n.trackId);e&&e.cuePoints.push(n)}for(const n of this.currentSegment.tracks){n.cuePoints.sort((e,t)=>e.time-t.time);for(let e=0;es&&(s=n.cuePoints.length,a=n);for(const n of this.currentSegment.tracks)0===n.cuePoints.length&&(n.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,2,Kr);Xe(i)&&(i=await i),j(i);const r=e,a=Jr(i);j(a);j(a.id===qr.Cluster);let s=a.size;const n=i.filePos;if(void 0===s){s=(await ia(this.reader,n,jr,t.elementEndPos)).pos-n}let o=this.reader.requestSlice(n,s);Xe(o)&&(o=await o);const c={segment:t,elementStartPos:r,elementEndPos:n+s,dataStartPos:n,timestamp:-1,trackData:new Map};if(this.currentCluster=c,o){const e=this.readContiguousElements(o,jr);c.elementEndPos=e}for(const[,l]of c.trackData){const e=l.track;j(l.blocks.length>0);let t=!1;for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const i=l.blocks[l.presentationTimestamps[0].blockIndex],a=l.blocks[X(l.presentationTimestamps).blockIndex];l.startTimestamp=i.timestamp,l.endTimestamp=a.timestamp+a.duration;const s=pe(e.clusterPositionCache,l.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:l.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=Jr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(ya(a),r){case qr.DocType:this.isWebM="webm"===Zr(e,a);break;case qr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case qr.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Gr(e,a)}break;case qr.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Gr(e,a)}break;case qr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Gr(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case qr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=ta(e,a);break;case qr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ht,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,a)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Ta.Block||e.data.algorithm!==va.HeaderStripping)&&(ct._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===aa)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===sa)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===na)this.currentTrack.info.codec="vp8";else if(t===oa)this.currentTrack.info.codec="vp9";else if(t===ca)this.currentTrack.info.codec="av1";else if(t===la){const e=this.currentTrack.codecPrivate?Z.decode(this.currentTrack.codecPrivate):"";Oi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Ea(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===ua?(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===ha?this.currentTrack.info.codec="mp3":t===da?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Wi):t===fa?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ma?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===pa?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ga?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ka?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new _a(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case qr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Gr(e,a);break;case qr.TrackType:{if(!this.currentTrack)break;const t=Gr(e,a);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...ce},alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case qr.FlagEnabled:if(!this.currentTrack)break;Gr(e,a)||(this.currentTrack=null);break;case qr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Gr(e,a);break;case qr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Gr(e,a);break;case qr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Gr(e,a);break;case qr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Gr(e,a);break;case qr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Gr(e,a);break;case qr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Gr(e,a);break;case qr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Zr(e,a);break;case qr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=rc(e,a);break;case qr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Gr(e,a);break;case qr.Name:if(!this.currentTrack)break;this.currentTrack.name=ea(e,a);break;case qr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Zr(e,a),Ae(this.currentTrack.languageCode)||(this.currentTrack.languageCode=xe);break;case qr.LanguageBCP47:{if(!this.currentTrack)break;const t=Zr(e,a).split("-")[0];this.currentTrack.languageCode=t||xe,this.currentTrack.hasLanguageBcp47=!0}break;case qr.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Gr(e,a);break;case qr.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Gr(e,a);break;case qr.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Gr(e,a);break;case qr.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Gr(e,a);break;case qr.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Gr(e,a);break;case qr.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Gr(e,a);break;case qr.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ne[t];this.currentTrack.info.colorSpace.matrix=i}break;case qr.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case qr.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ae[t];this.currentTrack.info.colorSpace.transfer=i}break;case qr.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ie[t];this.currentTrack.info.colorSpace.primaries=i}break;case qr.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-ta(e,a);try{this.currentTrack.info.rotation=K(t)}catch{}}break;case qr.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=ta(e,a);break;case qr.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Gr(e,a);break;case qr.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Gr(e,a);break;case qr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case qr.CueTime:this.currentCueTime=Gr(e,a);break;case qr.CueTrackPositions:{if(null===this.currentCueTime)break;j(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case qr.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Gr(e,a)}break;case qr.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;j(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Gr(e,a)}break;case qr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Gr(e,a);break;case qr.SimpleBlock:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=rc(e,a-(e.filePos-s)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case qr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case qr.Block:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e)>>1&3,o=rc(e,a-(e.filePos-s)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case qr.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case qr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case qr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=rc(e,a);break;case qr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Gr(e,a);break;case qr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Gr(e,a);break;case qr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case qr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case qr.Targets:this.readContiguousElements(e.slice(s,a));break;case qr.TargetTypeValue:50!==Gr(e,a)&&(this.currentTagTargetIsMovie=!1);break;case qr.TagTrackUID:case qr.TagEditionUID:case qr.TagChapterUID:case qr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case qr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case qr.TagName:this.currentSimpleTagName=ea(e,a);break;case qr.TagString:{if(!this.currentSimpleTagName)break;const t=ea(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.TagBinary:{if(!this.currentSimpleTagName)break;const t=rc(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new ut(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case qr.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;rt.order-e.order);break;case qr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ta.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case qr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Gr(e,a);break;case qr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Gr(e,a);break;case qr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:va.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case qr.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Gr(e,a);break;case qr.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=rc(e,a);break;case qr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){j(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(j(r.data),"decompress"===r.data.type)if(r.data.algorithm===va.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var i;if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??(r.raw={}),(i=r.raw)[e]??(i[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":r.title??(r.title=t);break;case"description":r.description??(r.description=t);break;case"artist":r.artist??(r.artist=t);break;case"album":r.album??(r.album=t);break;case"album_artist":r.albumArtist??(r.albumArtist=t);break;case"genre":r.genre??(r.genre=t);break;case"comment":r.comment??(r.comment=t);break;case"lyrics":r.lyrics??(r.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??(r.date=e))}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??(r.trackNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??(r.tracksTotal=a))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??(r.discNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??(r.discsTotal=a))}}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){j(r.trackBacking);const e=await r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=t??0,i}}class Ba{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ce(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=pe(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=we(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 j(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(-1===t)return null;const r=e.trackData.get(this.internalTrack.id).blocks[t];if(j(r),r.decoded||(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),r.decoded=!0),!r.postProcessed){if("prores"===this.internalTrack.info?.codec){if(!(r.data.length>=8&&105===r.data[4]&&99===r.data[5]&&112===r.data[6]&&102===r.data[7])){const e=new Uint8Array(r.data.length+8);J(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(r.data,8),r.data=e}}r.postProcessed=!0}const a=i.metadataOnly?rr:r.data,s=r.timestamp/this.internalTrack.segment.timestampFactor,n=r.duration/this.internalTrack.segment.timestampFactor,o={};r.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(o.alpha=i.metadataOnly?rr:r.mainAdditional,o.alphaByteLength=r.mainAdditional.byteLength);const c=new ar(a,r.isKeyFrame?"key":"delta",s,n,e.dataStartPos+t,r.data.byteLength,o);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,i,r,a){const{demuxer:s,segment:n}=this.internalTrack;let o=null,c=null,l=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(c=e,l=i)}const u=pe(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==u?this.internalTrack.cuePoints[u]:null,d=pe(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),f=-1!==d?this.internalTrack.clusterPositionCache[d]:null,m=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let p;for(e?null===m||e.elementStartPos>=m?(p=e.elementEndPos,o=e):p=m:p=m??n.clusterSeekStartPos;null===n.elementEndPos||p<=n.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,2,Kr);if(Xe(e)&&(e=await e),!e)break;const i=p,u=Jr(e);if(!u||!Vr.includes(u.id)&&u.id!==qr.Void){const e=await ra(s.reader,i,Vr,Math.min(n.elementEndPos??1/0,i+xa));if(e){p=e;continue}break}const h=u.id;let d=u.size;const f=e.filePos;if(h===qr.Cluster){o=await s.readCluster(i,n),d=o.elementEndPos-f;const{blockIndex:e,correctBlockFound:r}=t(o);if(r)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,l=e)}if(void 0===d){j(h!==qr.Cluster);d=(await ia(s.reader,f,jr,n.elementEndPos)).pos-f}const m=f+d;if(null===n.elementEndPos){let e=s.reader.requestSliceRange(m,2,Kr);if(Xe(e)&&(e=await e),!e)break;if(Qr(e)===qr.Segment){n.elementEndPos=m;break}}p=m}if(h&&(!c||c.elementStartPos{var e,t,i,r;let a=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(a=await this.getFirstPacket({}));const s={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&a?Ft(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?Wt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?ei(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?ii(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?ri(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(s);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const n={codec:zi(s),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})()):null}}class _a extends Ba{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Ra=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=uc(s),n=null!==e.fileSize?e.fileSize-a:null,o=Yi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&tr(o.header.channel)===tr(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Fa extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Aa(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Ra(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Qi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Xe(r)&&(r=await r),r){const a=uc(r);if(a===$i||a===Gi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Xe(t)&&(t=await t),t){const e=rc(t,12),i=J(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Zi.FrameCount?i.getUint32(4,!1):null,fileSize:r&Zi.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(Xe(a)&&(a=await a),!a)break;Rc(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Ic){let e=this.reader.requestSlice(this.reader.fileSize-Ic,Ic);Xe(e)&&(e=await e),j(e);"TAG"===bc(e,3)&&Bc(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Aa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(j(null!==e.firstFrameHeader),j(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,a=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(a<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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>>0&4294967295}const Na=e=>{const t=J(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let a=0;a>>24^t])>>>0}return t.setUint32(22,i,!0),r},Oa=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){j(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,n=(e[0]&s)>>1;if(n>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const c=t.vorbisInfo.modeBlockflags[n];if(a=t.vorbisInfo.blocksizes[c],1===c){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+a>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:ai[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},La=27,za=282,Ua=e=>{const t=e.filePos;if(hc(e)!==Ma)return null;e.skip(1);const i=ac(e),r=gc(e),a=hc(e),s=hc(e),n=hc(e),o=ac(e),c=new Uint8Array(o);for(let h=0;he+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},qa=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Ma)return!0;e.skip(1)}}return!1};class Wa extends ir{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,La,za);if(Xe(t)&&(t=await t),!t)break;const i=Ua(t);if(!i)break;if(!!!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const e=await this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?await this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&await this.readOpusMetadata(e,t),null!==t.codecInfo.codec&&this.trackBackings.push(new Ha(t,this)))}})())}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=await this.findNextPacketStart(r),!i)return;const a=await this.readPacket(i.startPage,i.startSegmentIndex);if(!a)return;if(3!==r.data[0]||5!==a.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const c=J(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&l),1<<(l>>4)],modeBlockflags:si(a.data).modeBlockflags},li(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const a=(e=>{const t=J(e),i=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}})(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=Wi,t.codecInfo.opusInfo={preSkip:a.preSkip},li(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){j(te+t.length,0);if(0===o)return null;const c=new Uint8Array(o);let l=0;for(let u=0;u{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Ha{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ue,this.internalSampleRate="opus"===e.codecInfo.codec?Wi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return j(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return j(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(j(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=Oa(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new ar(i.metadataOnly?rr:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),s}async getFirstPacket(e){j(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(j(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=await this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const a=i.timestampInSamples+i.durationInSamples,s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const i=Ce(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;j(this.bitstream.lastMetadataPacket);const r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let a=r.startPage,s=this.demuxer.reader.fileSize;const n=[a];e:for(;a.headerStartPos+a.totalSizei?s=l.headerStartPos:(a=l,n.push(l));continue e}r=l.headerStartPos+l.totalSize}}let o=r.startPage;for(const k of n){if(k.granulePosition===a.granulePosition)break;(!o||k.headerStartPos>o.headerStartPos)&&(o=k)}let c=o;const l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,La,za);Xe(t)&&(t=await t),j(t);const i=Ua(t);j(i),c=i,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}j(-1!==c.granulePosition);let u,h,d=null,f=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{u=0,h=!1;for(let t=c.lacingValues.length-1;t>=0;t--){if(c.lacingValues[t]<255){d=t+1;break}}if(null===d)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const e={data:rr,endPage:f,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){const e=ja(l,c,d);j(e);const t=Va(l,e.page,e.segmentIndex);t&&(c=t.page,d=t.segmentIndex)}else for(;;){const e=ja(l,c,d);if(!e)break;const t=Va(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,d=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,m=e.segmentIndex;break}}}let p=null,g=null;for(;null!==c;){j(null!==d);const e=await this.demuxer.readPacket(c,d);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&di||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,d=a.startSegmentIndex}return p}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=Ce(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=pe(this.sequentialScanCache,i,e=>e.timestampInSamples);let a;if(-1!==r){const e=this.sequentialScanCache[r];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let s=0;for(;a&&a.timestampe)break;if(a=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(a);j(e),this.sequentialScanCache.length>0&&j(X(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Va=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}j(-1===a);if(!(1&r.headerType)){a=0;break}const t=be(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=be(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);Xe(e)&&(e=await e),j(e);const t=bc(e,4),i="RIFX"!==t,r="RF64"===t,a=lc(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==bc(e,4))throw new Error("Invalid WAVE file - wrong format");let n=0,o=null,c=e.filePos;for(;null===s||c=18&&357!==a){const e=sc(r,i),s=t-18;if(Math.min(s,e)>=22&&a===Ka.EXTENSIBLE){r.skip(6);const e=rc(r,16);a=e[0]|e[1]<<8}}if(a!==Ka.MULAW&&a!==Ka.ALAW||(c=8),a!==Ka.PCM&&a!==Ka.IEEE_FLOAT&&a!==Ka.ALAW&&a!==Ka.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===Ka.PCM&&![8,16,24,32].includes(c))throw new Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(a===Ka.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,h,d,f;let m=this.reader.requestSlice(e,t);if(Xe(m)&&(m=await m),!m)return;const p=bc(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=bc(m,4),t=lc(m,i),p=rc(m,t);let k=0;for(let i=0;i0&&((c=this.metadataTags).trackNumber??(c.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((l=this.metadataTags).tracksTotal??(l.tracksTotal=i))}break;case"ICRD":case"IDIT":{const e=new Date(y);Number.isNaN(e.getTime())||((u=this.metadataTags).date??(u.date=e))}break;case"YEAR":{const e=Number.parseInt(y,10);Number.isInteger(e)&&e>0&&((h=this.metadataTags).date??(h.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(d=this.metadataTags).genre??(d.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(Xe(i)&&(i=await i),!i)return;const r=_c(i);if(r){const a=t-xc;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+xc,r.size);Rc(t,r,this.metadataTags)}}}getCodec(){if(j(this.audioInfo),this.audioInfo.format===Ka.MULAW)return"ulaw";if(this.audioInfo.format===Ka.ALAW)return"alaw";if(this.audioInfo.format===Ka.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===Ka.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}j(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Ga=2048;class Qa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(j(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht}}async getPacketAtIndex(e,t){j(e>=0),j(this.demuxer.audioInfo);const i=e*Ga*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(Ga*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(Xe(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=rr;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Xe(e)&&(e=await e),j(e),a=rc(e,r)}const s=e*Ga/this.demuxer.audioInfo.sampleRate,n=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new ar(a,"key",s,n,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){j(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ga,(this.demuxer.dataSize-1)/(Ga*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=await this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;j(null===this.demuxer.reader.fileSize);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){const e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){j(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ga);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ya=e=>{const t=e.filePos,i=rc(e,9),r=new dt(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const a=r.readBits(1),s=r.readBits(2)+1,n=r.readBits(4);if(15===n)return null;r.skipBits(1);const o=r.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const c=r.readBits(13);r.skipBits(11);const l=r.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===a?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:n,channelConfiguration:o,frameLength:c,numberOfAacFrames:l,crcCheck:u,startPos:t}},Ja=1024;class Za extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();j(this.firstFrameHeader),this.trackBackings=[new es(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ya(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=ft[t.samplingFrequencyIndex];j(void 0!==i);const r=Ja/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=Ja,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,xc);if(Xe(t)&&(t=await t),!t)break;const i=_c(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Xe(r)&&(r=await r),!r)break;Rc(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class es{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Ja}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getCodec(){return"aac"}getInternalCodecId(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){j(this.demuxer.firstFrameHeader);const e=mt[this.demuxer.firstFrameHeader.channelConfiguration];return j(void 0!==e),e}getSampleRate(){j(this.demuxer.firstFrameHeader);const e=ft[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return j(void 0!==e),e}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.dataSize)}return new ar(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=me(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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{var e;let t=0;for(;;){let e=this.reader.requestSlice(t,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=_c(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Xe(r)&&(r=await r),j(r),Rc(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:s.end-e,isLastFrame:!0};if(255===ac(s)){const t=s.filePos;if(ac(s)!==(1===this.blockingBit?249:248)){s.filePos=t;continue}s.skip(-2);const i=s.filePos-e,r=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!r){s.filePos=t;continue}if(0===this.blockingBit){if(r.num-n.num!==1){s.filePos=t;continue}}else if(r.num-n.num!==n.blockSize){s.filePos=t;continue}return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=rc(e,4),a=new dt(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){j(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){j(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");j(!t);if(0!==a.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(a.readBits(4));if(!s)return null;j(this.audioInfo);const n=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(a.readBits(4),this.audioInfo.sampleRate);if(!n)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const o=(e=>{let t=0;const i=new dt(rc(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new dt(rc(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?nc(e)+1:"uncommon-u8"===t?ac(e)+1:"number"===typeof t?t:(Te(t),void j(!1)))(e,s),l=((e,t)=>"uncommon-u16"===t?nc(e):"uncommon-u16-10"===t?10*nc(e):"uncommon-u8"===t?ac(e):"number"===typeof t?t:null)(e,n);if(null===l)return null;if(l!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,h=ac(e);e.skip(-u),e.skip(-1);const d=(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})(rc(e,u));return h!==d?null:{num:o,blockSize:c,sampleRate:l}}async advanceReader(){await this.readMetadata(),j(null!==this.lastLoadedPos),j(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class is{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return xe}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(j(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){await this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],a=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.byteSize)}j(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new ar(r,"key",a,s,e,i.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const rs=9e4,as=2**33,ss=188,ns="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.",os=new Set([133,134,162]),cs=new Set;class ls extends ir{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,205);Xe(e)&&(e=await e),j(e);const t=rc(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ss;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,r=null,a=!1,s=!1;for(;;){const e=await this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){i+=this.packetStride;continue}const t=await this.readSection(i,!0,!s);if(!t)break;const n=3,o=32;let c=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i);c=2===e.readBits(8)}}if(0!==t.pid||a)if(t.pid!==r&&!c||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=hs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(await this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const r=new gs(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,await r.markNextPacket(),"avc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=Ft(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];j(t);const i=Nt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const a=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;a>0&&s>0&&(a>s?(e.info.squarePixelWidth=Math.round(e.info.width*a/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/a))),e.info.colorSpace={primaries:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[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=Wt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===St.SPS_NUT).nalUnits[0];j(t);const i=qt(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:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:zi({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await r.markNextPacket(),!r.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=tc.tempFromBytes(r.suppliedPacket.data),i=Ya(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=mt[i.channelConfiguration],e.info.sampleRate=ft[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=uc(tc.tempFromBytes(r.suppliedPacket.data)),i=Yi(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=tr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=hi(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=ui[t.acmod]+t.lfeon,e.info.sampleRate=yt[t.fscod]}else if("eac3"===e.info.codec){const t=mi(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=pi(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=gi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ii(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:qi({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const a=e.readBits(10),c=e.pos+8*a;let l=!1;for(;e.pos=4){const t=e.readBits(32);l||(l=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=c;8*(r+n)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),a=e.pos+8*r;let s=!1,n=!1,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let c=null;const u=l&&os.has(t)?130:t;switch(u){case 27:case 36:c={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",c={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:n?c={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?c={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(c={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:cs.has(t)||(ct._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),cs.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}s=!0}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+n)-e.pos>o;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==r)throw new Error("Only files with a single program are supported.");r=i}}if(null===r)throw new Error("Program Association Table must link to a Program Map Table.");a=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!a)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const n of this.elementaryStreams)n.initialized&&("video"===n.info.type?this.trackBackingEntries.push(new fs(n)):this.trackBackingEntries.push(new ms(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),h=!!(1&e.adaptationFieldControl);let d=0;if(n&&(d=1+e.body[0],e===c&&d>1&&(u=e.body[1]>>6&1)),h&&(0===d?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(d)),o+=e.body.byteLength-d)),r=a,!t&&o>=64){l=!1;break}if(-1!==me(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=pe(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!c)return null;if(1===s.length)n=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);n=new Uint8Array(e);let t=0;for(const i of s)n.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:c.pid,payload:n,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(Xe(t)&&(t=await t),!t)return null;if(71!==ac(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=nc(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:ac(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,ss);if(Xe(t)&&(t=await t),!t)return null;const i=rc(t,ss);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=as-t?-8589934592:as}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new dt(t.payload);if(1!==r.readBits(24))return null;const a=r.readBits(8);if(r.skipBits(16),188===a||190===a||191===a||240===a||241===a||255===a||242===a||248===a)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let n=null;if(2===s||3===s)n=0,r.skipBits(4),n+=r.readBits(3)*(1<<30),r.skipBits(1),n+=32768*r.readBits(15),r.skipBits(1),n+=r.readBits(15),n=e.normalizeTimestamp(n);else if(i)throw new Error(ns);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},hs=(e,t,i)=>{j(null!==t.endPos);const r=us(e,t,i);if(!r)return null;const a=new dt(t.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const n=a.readBits(8),o=a.pos+8*n;a.pos=o;const c=o/8;j(Number.isInteger(c));const l=t.payload.subarray(c,s>0?6+s:t.payload.byteLength);return{...r,data:l}};class ds{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++,j(r instanceof ds),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 xe}getDisposition(){return{...ht,primary:!1}}getTimeResolution(){return rs}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new ar(i.metadataOnly?rr:e.data,r,e.pts/rs,Math.max(t/rs,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;j(t);const i=hs(this.elementaryStream.demuxer,t,!0);j(i);const r=new gs(this.elementaryStream,i),a=new ks(this,r),s=await a.readNext();if(!s)return null;const n=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(n,a),this.packetSectionStarts.set(n,s.packet.sectionStartPos),n}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const r=await i.readNext();if(!r)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(a,i),this.packetSectionStarts.set(a,r.packet.sectionStartPos),a}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const a=this.elementaryStream.demuxer,s=await a.readSection(r,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n);i=new ks(this,o);const c=e.sequenceNumber;for(;;){const e=await i.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){const r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){const r=Ce(e*rs),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:n}=a,o=this.elementaryStream.pid,c=async(e,t,i)=>{let r=e;for(;re.pts),m=-1!==f?d[f]:null;if(m&&r-m.pts<45e3)h=m.sectionStartPos;else{let e=0;if(null!==s.fileSize){const t=Math.ceil(s.fileSize/n);if(t>1){let i=0,s=t-1;for(e=i;i<=s;){const t=Math.floor((i+s)/2),o=_e(t*n,a.packetStride)+u.sectionStartPos,l=o+n,h=await c(o,l,!1);h?h.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}h=_e(e*n,a.packetStride)+u.sectionStartPos}const p=await c(h,s.fileSize??1/0,!1);let g=p?.pesPacketHeader??null;g||(g=u);const k=this.getReorderSize(),y=async(e,t)=>{const s=await a.readSection(e,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n),c=new ks(this,o);for(;;){if((X(c.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await c.readNextPacket()))break}const l=we(c.presentationOrderPackets,t);if(-1===l)return null;const u=c.presentationOrderPackets[l],h=0===l?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=h;const d=await c.readNext();j(d);const f=this.createEncodedPacket(d.packet,d.duration,i);return this.packetBuffers.set(f,c),this.packetSectionStarts.set(f,d.packet.sectionStartPos),f};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=g.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;g=e,ps(this.elementaryStream,g);break}}}e+=a.packetStride}}e:for(let e=0;e=a.packetOffset;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){g=e;break}}}e-=a.packetStride}}return y(g.sectionStartPos,e=>e.pts<=r)}{let e=h,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let h=null;const d=e<=u.sectionStartPos;let f,m=null;if(d)f=u,m=l;else{const t=await c(e,s.fileSize??1/0,i);f=t?.pesPacketHeader??null,m=t?.section??null}let p=!1,g=0;e:for(;f&&!(null!==t&&f.sectionStartPos>=t);){if(f.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===f.randomAccessIndicator;else{j(m);const t=hs(a,m,!0);j(t);const i=new gs(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(h=f)}if(f.pts>r&&(p=!0),p&&(g++,g>k))break;let e=f.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,i);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){f=e,m=t,ps(this.elementaryStream,f);break}}}e+=a.packetStride}}if(h){let e=h;if(0===g)e:for(let r=0;r=a.packetOffset;){const r=await a.readPacketHeader(t);if(!r)break e;if(r.pid===o&&1===r.payloadUnitStartIndicator){const r=await a.readSection(t,i);if(r){const t=us(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await y(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return j(t),t}if(d)return null;t=e,e=Math.max(_e(e-u.sectionStartPos-n,a.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}}class fs extends ds{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class ms extends ds{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const ps=(e,t)=>{const i=e.referencePesPackets,r=pe(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const a=i[r];if(t.pts<=a.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return j(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=l)break;u=e;const i=o+u;if(u+3>=l){this.seekTo(i);break}const h=c[u+1],d=c[u+2],f=c[u+3];let m=0;if(0===h&&0===d&&1===f?m=4:0===h&&1===d&&(m=3),0===m){u++;continue}const p=i;a??(a=p);const g=u+m,k=g+r,y=6;if(k+("avc"===t?y:1)>l){this.seekTo(i);break}const b=c[g];let w,T,S;if("avc"===t)w=Ct(b),T=w===wt.NON_IDR_SLICE||w===wt.SLICE_DPA||w===wt.IDR,S=w===wt.SEI||w===wt.SPS||w===wt.PPS||w===wt.AUD;else{w=Ut(b);if(((1&b)<<5|c[g+1]>>3)>0){u+=m;continue}T=w<=St.RASL_R||w>=St.BLA_W_LP&&w<=21,S=w>=St.VPS_NUT&&w<=37||w===St.PREFIX_SEI_NUT||w>=41&&w<=44||w>=48&&w<=55}let v=!1;if(T){let e;if("avc"===t){const t=c.subarray(k,k+y),i=$(new dt(t));e=!s||i<=n,n=i}else e=c[k]>>7===1;e&&(s?v=!0:s=!0)}else S&&s&&(v=!0);if(v){const e=p-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=m}if(ea){const e=this.endPos-a;return this.seekTo(a),this.supplyPacket(e,0)}}else{const t=e.info.codec,i=128;for(;;){let r=this.ensureBuffered(i);Xe(r)&&(r=await r);const a=this.currentPos;for(;this.currentPos-a>6,n=63&a[4];if(3===s||n>37){this.seekTo(t+1);continue}const o=di[3*n+s];j(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),Xe(r)&&(r=await r);const c=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,c)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(Xe(r)&&(r=await r),r<5)return;const a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}const s=2*(((7&a[2])<<8|a[3])+1),n=3===a[4]>>6?3:a[4]>>4&3,o=fi[n];this.seekTo(t),r=this.ensureBuffered(s),Xe(r)&&(r=await r);const c=256*o,l=Math.round(c*rs/e.info.sampleRate);return this.supplyPacket(r,l)}if("dts"===t){if(127!==i&&100!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(18);if(Xe(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=Ci(a);let n=s?null:Bi(a);if(!s&&!n){this.seekTo(t+1);continue}if(n&&!n.asset){this.seekTo(t);const e=Math.min(n.frameSize,4096);let i=this.ensureBuffered(e);Xe(i)&&(i=await i),n=Bi(this.readBytes(i))??n}let o=s?s.frameSize:n.frameSize;if(s){let e=4*Math.ceil(s.frameSize/4);for(;;){this.seekTo(t);const i=e+10;let r=this.ensureBuffered(i);if(Xe(r)&&(r=await r),r=0)}async readNext(){if(0===this.decodeOrderPackets.length){if(!(await this.readNextPacket()))return null}await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(j(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(j(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(await this.readNextPacket()))break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const ys="application/vnd.apple.mpegurl",bs="#EXT-X-STREAM-INF:",ws="#EXT-X-I-FRAME-STREAM-INF:",Ts="#EXT-X-MEDIA:",Ss="#EXTINF:",vs="#EXT-X-MAP:",Ps="#EXT-X-KEY:",Is="#EXT-X-MEDIA-SEQUENCE:",xs="#EXT-X-BYTERANGE:",Cs="#EXT-X-PROGRAM-DATE-TIME:",Bs="#EXT-X-TARGETDURATION:",Es="#EXT-X-PLAYLIST-TYPE:",_s=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Rs{constructor(e){this._attributes={};let t="",i="",r=!1,a=!1;for(let s=0;s{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,t,i))}else if("audio"===t.type){const i=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=await t.getTracks();for(const r of i)if("video"===r.type){const t=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,{id:e.length+1,type:"audio"},t))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let r;if(this.firstSegmentFirstTimestamps.has(i))r=this.firstSegmentFirstTimestamps.get(i);else{const e=this.getInputForSegment(i);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(i,r)}if(i===e)return i.timestamp-r;const a=await this.getFirstTimestampForInput(t),s=e.timestamp-i.timestamp,n=a-r-s;return Math.abs(n)<=Math.min(.25,s)?i.timestamp-r:e.timestamp-a}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class As{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var e;if((e=this.segmentedInput).firstSegment??(e.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let t=this.segmentedInput.firstSegment,i=null;for(;t;){const e=this.segmentedInput.getInputForSegment(t);if(i=(await e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,i)break;t=await this.segmentedInput.getNextSegment(t,{})}if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i,this.firstSegment=t})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),j(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){j(e.sequenceNumber>=0),j(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:Ee(e.timestamp+r,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s}async getFirstPacket(e){await this.hydrate(),j(this.firstInputTrack),j(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){const r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,i,t)}if(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait}),!i)break;const r=this.segmentedInput.getInputForSegment(i);t=(await r.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,i){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const a=i?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(a)return this.createAdjustedPacket(a,r.segment,r.track);let s=r.segment;for(;;){const e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),a=(await i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!a){s=e;continue}const n=await a._backing.getFirstPacket(t);return n?this.createAdjustedPacket(n,e,a):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){const a=this.segmentedInput.getInputForSegment(r),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const n=e-await this.segmentedInput.getMediaOffset(r,a),o=i?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(o)return this.createAdjustedPacket(o,r,s);r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null}}class Ms extends As{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Ds extends As{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}Ye();const Ns=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class Os extends st{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Zo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Ns),e=this._getFileSize(),j(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new Zo;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Js(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Ls(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Ls{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;j(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class zs extends Os{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 Os||e instanceof Ls))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof Os?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Xe(t)?t.then(i):i(t)}}const Us=(e,t)=>e.path===t.path;class qs extends zs{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 Os?e.ref():e;return this._root=t,this._rootRequest=null,t};Xe(e)?this._rootRequest=e.then(t):(t(e),j(this._root))}if(this._rootRequest)return this._rootRequest.then(a=>a.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const Ws="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class Hs extends Os{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),Ws?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Qs.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){j(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Ue()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),Ws?.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch{}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return ct._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)},js=new Set;class Ks extends zs{constructor(e,t={}){if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new Ks(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Vs,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...Ne(t.requestInit.headers)},r=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==r&&(i=e[r],delete e[r],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){i??(i=t);const r=new Request(e);r.headers.delete("Range"),this._url=r}}if(null!==i){const e=$s(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:Qs.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:Ie(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const a=this._offset,s=this._sequentialBacking?this._sequentialBacking._read(a+e,a+t):this._orchestrator.read(a+e,a+t,Math.max(a+i,a),a+Math.min(r,this._length??1/0)),n=e=>e?(e.offset-=this._offset,e):null;return Xe(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);r.redirected&&(this.rootPath=r.url);e:if(null===this._orchestrator.fileSize&&(206===r.status||"basic"===r.type&&!r.headers.has("Content-Encoding"))){const t=r.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=r.headers.get("Content-Length");if(i){const t=206===r.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==r.status){if(this._sequentialBacking)return void r.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||js.has(e.origin)||(ct._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),js.add(e.origin))}return void this._transitionToSequentialMode(r.body)}const a=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return i.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let r;try{r=await a.read()}catch(t){if(this._disposed)throw t;const e=this._getRetryDelay(1,t,this._url);if(null!==e){ct._error("Error while reading response stream. Attempting to resume.",t),await at(1e3*e);break}throw t}if(e.aborted)continue;const{done:s,value:n}=r;if(s){if(e.currentPos>=e.targetPos)return void this._orchestrator.onWorkerFinished(e);if(e.strictTarget)break;return void this._orchestrator.onWorkerFinished(e)}this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const a=new ReadableStream({pull:async e=>{for(;;){let s;try{s=await t.read()}catch(a){if(this._disposed)throw a;const e=this._getRetryDelay(1,a,this._url);if(null===e)throw a;ct._error("Error while reading response stream. Attempting to resume.",a),await at(1e3*e);const s=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=s.body.getReader(),r=206===s.status?0:i;continue}if(s.done)return void e.close();let n=s.value;if(r>0){const e=Math.min(r,n.length);r-=e,n=n.subarray(e)}if(0!==n.length)return i+=n.length,void e.enqueue(n)}},cancel:()=>t.cancel()}),s=new Gs(a,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const n=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)n.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)n.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of n){const e=s._read(o.start,o.start+o.bytes.length);Xe(e)?e.then(e=>{e?(j(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(j(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Xs=/^bytes=(\d+)-(\d*)$/,$s=e=>{const t=Xs.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=pe(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let a=e;const s=new Uint8Array(t-e);if(-1!==i)for(let l=i;l=t)break;const r=Math.max(e,i.start);r>a&&this._throwDueToCacheMiss();const n=Math.min(t,i.end);ra&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:c}=ke();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),n}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex0;){const e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new Zo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Qs={fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(Ge(e,t,r,a.targetPos)){const e=a.targetPos-a.startPos,r=Math.ceil((e+1)/i)*i,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,r);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+524288)}}};class Ys{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){j(!this.disposed);const a=this.options.prefetchProfile(e,t,this.workers),s=Math.max(a.start,i),n=Math.min(a.end,this.fileSize??1/0,r);j(s<=e&&t<=n);let o=null;const c=pe(this.cache,e,e=>e.start),l=-1!==c?this.cache[c]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,o={bytes:l.bytes,view:l.view,offset:l.start});const u=pe(this.cache,s,e=>e.start),h=o?null:new Uint8Array(t-e);let d=0,f=s;const m=[];if(-1!==u){for(let i=u;i=n)break;if(r.end<=s)continue;const a=Math.max(s,r.start),o=Math.min(n,r.end);if(j(a<=o),f=h.length&&(o={bytes:h,view:J(h),offset:e}),0===m.length)return j(o),o;const{promise:p,resolve:g,reject:k}=ke(),y=[];for(const w of m){const i=Math.max(e,w.start),r=Math.min(t,w.end);i===w.start&&r===w.end?y.push(w):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&w.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,w.end),i.strictTarget&&(i.strictTarget=e),b&&i.pendingSlices.push(b)):(t++,i={hole:{start:w.start,end:w.end},strictTarget:e,pendingSlices:b?[b]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.hole.end)break;i.hole.end=Math.max(i.hole.end,e.hole.end),i.pendingSlices.push(...e.pendingSlices),i.strictTarget&&(i.strictTarget=e.strictTarget),i.age=Math.min(i.age,e.age),this.queuedReads.splice(t+1,1)}}}return o?p.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(j(h),o=p.then(t=>t&&{bytes:t,view:J(t),offset:e})),o}checkHoleAgainstWorker(e,t,i){if(Ge(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=r),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const t=this.workers.indexOf(e);j(-1!==t),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=pe(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=J(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=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=J(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;ithis._length)return null;const a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return Xe(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var Zs=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},en=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const tn=/^0[xX][0-9a-fA-F]+$/,rn=/^data:.*;base64,/i;class an extends Fs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await at(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new ec(i.source),a=await r.requestEntireFile();j(a),e=wc(a,a.length,{ignore:_s}),i.source instanceof zs&&(this.rootPath=i.source.rootPath)}catch(y){t.error=y,t.hasError=!0}finally{en(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,n=null,o=0,c=null,l=null,u=null,h=null,d=null,f=null,m=!1,p=X(this.segments)??null;const g=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},k=e=>{o=e,p&&(j(null!==p.sequenceNumber),p.sequenceNumber0&&null!==f&&(r=o*f),m=!0);const e=y.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);s=a}else if(y.startsWith(vs)){const e=new Rs(y.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let o=null;if(null!==i&&(o=g(i)),o&&null===o.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!p){const e={path:Ze(this.rootPath,t),offset:o?.offset??0,length:o?.length??null};if("AES-128"===n?.method&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:d}}s=null,null===h?u=null:h=null}else if(y.startsWith(Ps)){const e=new Rs(y.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!tn.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(fr);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=J(t).getUint32(0);r=sr(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(y.startsWith(Is)){const e=y.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);k(t)}else if(y.startsWith(xs)){const e=g(y.slice(17));if(null===e.offset){if(null===u)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=u}h=e,u=e.offset+e.length}else if(y.startsWith(Cs)){if(p)continue;const e=y.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(d===s)continue;if(null===d&&this.segments.length>0){const e=X(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}d=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===y)c=null;else if(y.startsWith(Bs)){const e=y.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,f=t}else{if("#EXT-X-ENDLIST"===y){this.streamHasEnded=!0;break}if(y.startsWith(Es)){"vod"===y.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==y)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0}}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return 0===this.segments.length&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){0===this.segments.length&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=pe(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let r=null;(t.initSegment||t.firstSegment)&&(r=this.getInputForSegment(t.initSegment??t.firstSegment));const a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let i=e.psshBoxes;const{psshBox:r}=t.encryption;return null!==r.keyIds&&!r.keyIds.includes(e.keyId)||i.some(e=>nr(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new Yo({source:new qs(t.location.path,async e=>{j(e.isRoot);const i={...e,isRoot:!1};let r;const a=t.location.offset>0||null!==t.location.length;if(t.encryption&&"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method)if("AES-128"===t.encryption.method){const e=t.encryption;j(e.iv);let s=await this.input._getSourceCached(i);if(a){const e=s.source.slice(t.location.offset,t.location.length??void 0).ref();s.free(),s=e}const n=((e,t,i)=>{let r=!1,a=0;const s=new Sr;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(Xe(o)&&(o=await o),!o||0===o.length)throw new Error("Invalid ciphertext.");const c=o.length;if(c%16!==0)throw new Error("Invalid ciphertext.");const l=65552===c?c-16:c,u=rc(o,l),h=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=h.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new ec(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},Qo),!1),r=new ec(i.source),a=await r.requestSlice(0,fr);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:rc(a,fr),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{en(t)}},()=>{s.free()});r=new Gs(n).ref()}else j(!1);else if(r=await this.input._getSourceCached(i),a){const e=r.source.slice(t.location.offset,t.location.length??void 0).ref();r.free(),r=e}return r}),formats:this.input._formats.filter(e=>!(e instanceof Pn)),initInput:r??void 0,formatOptions:a});s._onFormatDetermined=e=>{if(("SAMPLE-AES"===t.encryption?.method||"SAMPLE-AES-CTR"===t.encryption?.method)&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:s,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=tt(this.inputCache,e=>e.age);j(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class sn extends ir{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{j(this.input._rootSource instanceof zs);const e=await this.input._reader.requestEntireFile();j(e);const t=wc(e,e.length,{ignore:_s}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let u=1;u"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],n=[...new Set(a.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=await Promise.all(r.map(async(e,t)=>{const r=[],o=e.attributes.get("codecs");let c;if(o)c=o.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=await t.getTrackBackings(),r=await Promise.all(i.map(async e=>({track:e,codec:await e.getCodec()})));c=await Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const l=e.attributes.get("video"),u=e.attributes.get("audio"),h=c.some(e=>_i.includes(ji(e))),d=c.some(e=>Fi.includes(ji(e)));if(null!==l&&!h){if(!s.includes(l))throw new Error(`Invalid M3U8 file; variant stream references video group "${l}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===l&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}if(null!==u&&!d){if(!n.includes(u))throw new Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}c=[...new Set(c)];let f=null,m=null;const p=e.attributes.getAsNumber("bandwidth");j(null!==p);const g=e.attributes.getAsNumber("average-bandwidth"),k=e.attributes.get("name");for(const i of c){const o=ji(i);if(null!==o)if(_i.includes(o)){if(null!==f)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");f=i;const n=e.attributes.get("video");if(null===n){const i=e.attributes.get("resolution");let a=null,s=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(a=Number(e[1]),s=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:xe,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:f,pairingMask:1n<0?a:null}})}else{if(!n.includes(s))throw new Error(`Invalid M3U8 file; variant stream references audio group "${s}" which is not defined in any #EXT-X-MEDIA tags.`);for(const i of a){const a=i.attributes.get("group-id"),n=i.attributes.get("type");if(a!==s||"audio"!==n.toLowerCase())continue;const o=i.attributes.get("channels")??e.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;r.push({id:-1,demuxer:this,backingTrack:null,default:ln(i.attributes),autoselect:ln(i.attributes)||un(i.attributes),languageCode:hn(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<0?c:null}})}}}}return r})),c=[],l=e=>{const t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||(t.default=e.default),t.autoselect||(t.autoselect=e.autoselect),t.lineNumber=Math.min(t.lineNumber,e.lineNumber),null!==e.peakBitrate&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),null!==e.averageBitrate&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===xe&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(const u of o)for(const e of u)l(e);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of c)"video"===u.info.type?this.trackBackings.push(new on(u)):this.trackBackings.push(new cn(u));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),j(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 an(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ys}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class nn{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof on){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{j(this instanceof cn);for(const e of i)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...ht,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(){j(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class on extends nn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ji(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class cn extends nn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ji(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const ln=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}".`)},un=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}".`)},hn=e=>{if(null===e)return xe;const t=e.split("-")[0];return t||xe};class dn{constructor(){this._isIsobmff=!1}}class fn extends dn{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return null;t.skip(4);const i=bc(t,4);return"ftyp"!==i&&"styp"!==i?null:bc(t,4)}_createDemuxer(e){return new vr(e)}}class mn extends fn{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(Xe(t)&&(t=await t),!t)return!1;let r=uc(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Xe(t)&&(t=await t),!t)return!1;r=mc(t),a=16}if(r8)return!1;if(Gr(i,r)!==qr.EBML)return!1;const a=Yr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(Xe(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Jr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case qr.EBMLVersion:if(1!==Gr(s,r))return!1;break;case qr.EBMLReadVersion:if(1!==Gr(s,r))return!1;break;case qr.DocType:if(Zr(s,r)!==t)return!1;break;case qr.DocTypeVersion:if(Gr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Ca(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class kn extends gn{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class yn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}const i=await Ra(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=Qi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(Xe(s)&&(s=await s),!s)return!1;const n=uc(s);if(n===$i||n===Gi)return!0;t=i.startPos+i.header.totalSize;const o=await Ra(e._reader,t,t+4);if(!o)return!1;const c=o.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new Fa(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class bn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return!1;const i=bc(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===bc(t,4)}_createDemuxer(e){return new $a(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class wn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return Xe(t)&&(t=await t),!!t&&"OggS"===bc(t,4)}_createDemuxer(e){return new Wa(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Tn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Xe(i)&&(i=await i),!!i&&"fLaC"===bc(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ts(e)}}class Sn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Xe(i)&&(i=await i),!i)return!1;const r=Ya(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Xe(i)&&(i=await i),!i)return!1;const a=Ya(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new Za(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class vn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(Xe(t)&&(t=await t),!t)return!1;const i=rc(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 ls(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Pn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(Xe(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===bc(t,7)))return!1;if(!(e._rootSource instanceof zs))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 sn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return ys}}const In=new mn,xn=new pn,Cn=new gn,Bn=new kn,En=new yn,_n=new bn,Rn=new wn,Fn=new Sn,An=new Tn,Mn=new vn,Dn=new Pn,Nn=[Dn,In,xn,Cn,Bn,_n,Rn,An,En,Fn,Mn],On=[Dn,In,xn,En,Fn,Mn];var Ln=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});Ye();let zn=-1/0,Un=-1/0,qn=null;"undefined"!==typeof FinalizationRegistry&&(qn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-zn>=1e3&&(ct._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."),zn=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Un>=1e3&&(ct._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."),Un=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Wn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Hn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Vn=new Set(Hn);class jn{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(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!Vn.has(t.format))throw new TypeError("init.format must be one of: "+Hn.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&&rt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??to(t.format,t.codedWidth,t.codedHeight);let r=t.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?Y(e):Y(e).slice(),this._layout=i,this.colorSpace=new Qn(r)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==t?.visibleRect&&rt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Qn(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&rt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new jn(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Me),duration:Math.trunc((t.duration??0)*Me)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const a=t.visibleRect??{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(a.width,a.height),n=s.getContext("2d",{alpha:We(),willReadFrequently:!0});if(!n)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");n.drawImage(e,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Qn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Wn))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!Hn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=it({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),qn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return j(null!==this._data),this._data instanceof Wn?new jn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Yn(this._data)?new jn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(j(this._layout),new jn(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new jn(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(qn?.unregister(this),this._data instanceof Wn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Yn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(eo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(e.format??this.format))throw new Error("Cannot get allocation size when format is null.");if(Yn(this._data))return this._data.allocationSize(e);return ro(this,e).allocationSize}async copyTo(e,t={}){if(!le(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(eo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(j(null!==this._data),Yn(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof Wn)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(i,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(r instanceof jn))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(r.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${r.format}' instead.`);return await r.copyTo(e,t)}catch(c){i.error=c,i.hasError=!0}finally{Ln(i)}}}const i=ro(this,t);j(this.format);const r=Y(e);if(r.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=e}else if(this._data instanceof Uint8Array)j(this._layout),j(this._layout.length===a.length),s=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");j(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:Y(t.data),stride:4*this.codedWidth}]}const n=[],o=a.length;for(let l=0;la.byteLength)throw new Error("Source buffer OOB read.");if(c+u>r.byteLength)throw new Error("Destination buffer OOB write.");const i=a.subarray(o,o+u);r.set(i,c),o+=t,c+=e.destinationStride}n.push(h)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const a=[];for(const s of e)i.set(s.data,r),a.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:a[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Yn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(j(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,h=this.displayWidth,d=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,h=r,d=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=h,g=d)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:h,sHeight:d}=this._rotateSourceRegion(l,u,h,d,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,h,d,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Zn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,h=t.crop;h&&(h=Jn(h,s,n));const{sx:d,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],h="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*h,u=a*h,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?Gn(u,h):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,h)):m||f.clearRect(0,0,u,h),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(d,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(d,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(j(null!==this._data),this._data instanceof Wn||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(e){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&Zn(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=K(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=Jn(a,i,r));const s=a?a.width:i,n=a?a.height:r,o=s/n;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/o):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*o):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=n),c=Be(c,e.roundDimensionsTo??1),l=Be(l,e.roundDimensionsTo??1);const u={width:c,height:l,fit:e.fit??"fill",rotation:t,crop:a??{left:0,top:0,width:i,height:r},alpha:e.alpha??"keep"};for(const m of Kn){let e=m(this,u);if(Xe(e)&&(e=await e),null!==e)return e}const{canvas:h,context:d,isNew:f}=Gn(u.width,u.height);return this._drawWithFitAndMipmapping(h,d,{fit:u.fit,rotation:u.rotation,crop:u.crop,targetIsFresh:f,fillBlack:"discard"===u.alpha}),new jn(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Kn=[],Xn=[];let $n=0;const Gn=(e,t)=>{for(const a of Xn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=$n++,{canvas:a.canvas,context:a.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Xn.length>=3&&Xn.splice(tt(Xn,e=>e.age),1),Xn.push({canvas:i,context:r,age:$n++}),{canvas:i,context:r,isNew:!0}};class Qn{constructor(e){if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(te);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(re);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(se);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!==typeof e.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Yn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Jn=(e,t,i)=>{const r=Math.min(e.left,t),a=Math.min(e.top,i),s=Math.min(e.width,t-r),n=Math.min(e.height,i-a);return j(s>=0),j(n>=0),{left:r,top:a,width:s,height:n}},Zn=(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.")},eo=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.")}},to=(e,t,i)=>{const r=io(e),a=[];let s=0;for(const n of r){const e=Math.ceil(t/n.widthDivisor),r=Math.ceil(i/n.heightDivisor),o=e*n.sampleBytes,c=o*r;a.push({offset:s,stride:o}),s+=c}return a},io=e=>{const t=(e,t,i,r,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Te(e),j(!1)}},ro=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=ao(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let n;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");n=t.format}else n=e.format;return no(a,n,s)},ao=(e,t,i,r,a)=>{const s={...e};if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!so(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},so=(e,t)=>{if(null===e)return!0;const i=io(e);for(let r=0;r{const r=io(t),a=r.length;if(void 0!==i&&i.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const n=[],o=[];for(let c=0;c4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(d),s=Math.max(s,d);for(let e=0;e 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(uo(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*uo(this.format);if(i.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const a=uo(t),s=ho(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?r:r*this.numberOfChannels)*a}copyTo(e,t){if(!le(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&&!oo.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:a}=t;let{planeIndex:s}=t,n=this.format;const o=i??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:c-u;if(h>c-u)throw new RangeError("frameCount out of range");const d=uo(o),f=ho(o);if(f&&s>=l)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?h:h*l)*d;if(e.byteLength2&&o!==n)return void go(this._data,p,n,o,l,s,u,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:h,format:o})}catch(S){if("f32-planar"===o)throw S;n="f32-planar"}}const k=fo(n),y=uo(n),b=ho(n);let w;if(this._data instanceof co){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=c*y*(b?1:l);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)w=e(s),s=0;else{w=new Uint8Array(c*y*l);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new lo({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(qn?.unregister(this),this._data instanceof co?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof co?this._createAudioDataFromData():po(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(ho(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const a=Math.min(s,o),c=new Float32Array(i*a);for(let t=0;t0;){const a=Math.min(s,o),l=new Float32Array(i*a);for(let t=0;t{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")}},ho=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},fo=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)}},mo=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,Ie(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,Ie(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,Ie(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},po=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,go=(e,t,i,r,a,s,n,o)=>{const c=fo(i),l=mo(r),u=uo(i),h=uo(r),d=ho(i);if(ho(r))if(d){const r=new ArrayBuffer(o*u),a=J(r);e.copyTo(r,{planeIndex:s,frameOffset:n,frameCount:o,format:i});for(let e=0;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.")},wo=e=>{if(!Je(e))throw new TypeError("timestamp must be a number.")},To=(e,t,i)=>i.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const i=await e.determinePacketType(t);return i&&(t.type=i),t}):t;class So{constructor(e){if(!(e instanceof Oo))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(bo(e),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){bo(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i}async getNextKeyPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,t):i}packets(e,t,i={}){if(void 0!==e&&!(e instanceof ar))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof ar))throw new TypeError("endPacket must be an EncodedPacket.");if(bo(i),this._track.input._disposed)throw new Zo;const r=[];let{promise:a,resolve:s}=ke(),{promise:n,resolve:o}=ke(),c=!1,l=!1,u=null,h=!1;const d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=ke()),await n):(r.push(u),s(),({promise:a,resolve:s}=ke()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{h||(u=e,h=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Zo;if(l)return{value:void 0,done:!0};if(h)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class vo{constructor(e,t){this.onSample=e,this.onError=t}}class Po{mediaSamplesInRange(e=-1/0,t=1/0,i){wo(e),wo(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=ke(),{promise:c,resolve:l}=ke(),u=!1,h=!1,d=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(h=!0),h?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=ke())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!h&&!this._track.input._disposed;){const e=Io(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=ke()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),d||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,h=!0,y(),new Zo;if(d)return{value:void 0,done:!0};if(p)throw d=!0,h=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,h=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:n}=ke(),{promise:o,resolve:c}=ke(),l=!1,u=!1,h=null,d=null,f=!1;const m=e=>{a.push(e),n(),({promise:s,resolve:n}=ke())},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(d=e,f=!0,n())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=async()=>{j(s),j(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:c}=ke()),await o;if(u)break;const r=await e.getNextPacket(t,p);j(r),h.decode(r),t=r}g=-1},y=async()=>{j(h),await h.flush();for(let e=0;e{f||(d=e,f=!0,n())}).finally(()=>{h?.close()});const g=this._track,k=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(g.input._disposed)throw u=!0,k(),new Zo;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),d;if(a.length>0){const e=a.shift();return j(void 0!==e),c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await s}},return:async()=>(u=!0,c(),n(),k(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Io=e=>0===e?40:8;class xo extends vo{constructor(e,t,i,r,a,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=a,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const n=ko.find(e=>e.supports(i,r));if(n)this.customDecoder=new n,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof jn))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();j(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(Ve()){if("avc"===i&&this.decoderConfig.description){const e=Mt(Y(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Nt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Lt(t),this.decoderConfig={...this.decoderConfig,description:At(e)}))}}oe(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(j(this.decoder),Ue()||ge(this.inputTimestamps,e.timestamp,e=>e),Ve()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of xt(e.data,this.decoderConfig)){const r=Ct(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===wt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(a.offset,a.offset+a.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&Y(t.description)[4];return Rt(e,i+1)}return _t(e)})(t,this.decoderConfig);e=new ar(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Jt(e.data,this.decoderConfig);t&&(e=new ar(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new Bo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();j(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();j(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=ni(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of zt(e,this.decoderConfig)){const i=Ut(e[t.offset]);if(i===St.RASL_N||i===St.RASL_R)return!0}return!1}sampleHandler(e){if(Ue()){if(this.sampleQueue.length>0&&e.timestamp>=X(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ge(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();j(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){const i=ke();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){j(this.merger);const i=await this.merger.merge(e,t);r.sample=new jn(i)}else r.sample=new jn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){ye(this.finalSamples,r),this.onError(a)}finally{ye(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Ue()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let Co=null;class Bo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Co){const e=new Blob([`(${Eo.toString()})()`],{type:"application/javascript"});Co=URL.createObjectURL(e)}const e=Ie(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=ke();this.pendingRequests.set(i,r);const a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Eo=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:a,alpha:s}=e.data;i=i.then(async()=>{try{const e=await r(a,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{a.close(),s.close()}})});const r=async(e,t)=>{const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),c=i.includes("P12"),l=r.includes("P10"),u=r.includes("P12");if(l!==o||u!==c)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return await a(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return await s(e,t,i);if("NV12"===i)return await n(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)},a=async(e,t,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=new Uint8Array(4*s);await e.copyTo(n);const c=await o(t,r,a,1);for(let o=0,u=3;o{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=i.includes("P10"),n=i.includes("P12"),c=s||n?2:1;let l,u;i.startsWith("I420")?(l=Math.ceil(r/2),u=Math.ceil(a/2)):i.startsWith("I422")?(l=Math.ceil(r/2),u=a):(l=r,u=a);const h=r*a,d=h*c,f=l*u*c,m=new Uint8Array(d+2*f+h*c);await e.copyTo(m);const p=await o(t,r,a,c),g=d+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,h=s+n,d=s;for(let o=0;o{const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e);const n=t.format;if("RGBA"===n||"BGRA"===n||"RGBX"===n||"BGRX"===n){const t="RGBA"===n||"RGBX"===n?0:2,a=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class Ro extends Po{constructor(e,t={}){if(!(e instanceof Uo))throw new TypeError("videoTrack must be an InputVideoTrack.");_o(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(je("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getRotation();let a=await this._track.getDecoderConfig();const s=await this._track.getTimeResolution();return j(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new xo(e,t,i,a,r,s)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Fo{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Uo))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&&Zn(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&_o(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ro(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[s,n]=i%180===0?[r,a]:[a,r];let o=e.crop;o&&(o=Jn(o,s,n));let[c,l]=o?[o.width,o.height]:[s,n];const u=c/l;void 0!==e.width&&void 0===e.height?(c=e.width,l=Math.round(c/u)):void 0===e.width&&void 0!==e.height?(l=e.height,c=Math.round(l*u)):void 0!==e.width&&void 0!==e.height&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=i,this._crop=o})())}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],a=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||We()});j(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&We()});const n={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e,t){wo(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*Pe(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Pe(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Ao extends vo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const a=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=yo.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 lo))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new lo(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(j(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Mo extends vo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,j(Ri.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=Vi(this.codec);switch(this.inputSampleSize=a,a){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const a=(1<(e=>{let t=0,i=0,r=85^e;128&r&&(r&=-129,t=-1),i=4+((240&r)>>4);let a=0;return a=4!==i?1<e.getUint16(t,s)-32768:"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):j(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Se(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Se(e,t,i)<<8>>8)(e,t,s):j(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-2**31:"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):j(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):j(!1);break;default:Te(a),j(!1)}switch(a){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:Te(a),j(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=J(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(r),s=new DataView(a);for(let l=0;l=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const c=new lo({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Do extends Po{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(je("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getDecoderConfig();return j(i&&r),Ri.includes(r.codec)?new Mo(e,t,r):new Ao(e,t,i,r)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class No{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Do(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){wo(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return Pe(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Pe(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Oo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Uo}isAudioTrack(){return this instanceof qo}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Lo(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Lo(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Lo(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Lo(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return null!==await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Lo(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return Ee((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new So(this);let r=1/0,a=-1/0,s=0,n=0;for await(const o of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-r)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-r)).toPrecision(16)):0}}async isLive(){return null!==await this._backing.getLiveRefreshInterval()}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Oo))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&0n!==(this._backing.getPairingMask()&e._backing.getPairingMask())}async getPairableTracks(e){return this.input.getTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=zo(e));const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Lo=(e,t,i)=>{if(Xe(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},zo=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 Xe(r)?r.then(i):i(r)}:void 0};class Uo extends Oo{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??"prores"===await this._backing.getCodec()}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Lo(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Lo(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Lo(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Lo(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Lo(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:Lo(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Lo(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){const e=await(this._backing.getMetadataDisplayWidth?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(void 0!==e){const t=Lo(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Lo(t,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await(this._backing.getMetadataDisplayHeight?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(void 0!==e){const t=Lo(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Lo(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),ko.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(null===t)return null;const i=await this.getDecoderConfig();return j(i),ni(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!Je(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,r=new So(this),a=[];let s=-1/0,n=0;for await(const I of r.packets(void 0,void 0,{metadataOnly:!0})){if(a.length>=i&&I.timestamp>=s)break;a.push(I.timestamp),s=Math.max(s,I.timestamp),n++}const o=new Float64Array(a.length);for(let I=0;Ie-t),b=k-1>>1,w=k>>1;let T=0,S=0,v=0;for(const I of y)if(v+=f.get(I),0===T&&v>b&&(T=I),v>w){S=I;break}const P=(h/T+h/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:Go(P),minFrameRate:h/p,maxFrameRate:h/m,averageFrameRate:h*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class qo extends Oo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Lo(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Lo(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),yo.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Wo=e=>-(e??-1/0),Ho=e=>-e,Vo=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 Xe(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return Xe(r)?r.then(i):i(r)}:void 0}},jo=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return Xe(r)?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Xe(r)||Xe(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),Ko=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>Xe(e))){const t=await Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!t?.sortBy)return i;const r=i.map(e=>t.sortBy(e)),a=r.some(e=>Xe(e))?await Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{const i=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(i.length,r.length);for(let s=0;se.track)},Xo=(e,t)=>{const i=1e6,r=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let T=1;T0))return null;s[T-1]=t}const n=s.slice();n.sort();let o=n[Math.floor(.05*n.length)];for(let T=0;T<6;T++){let e=0,t=0;for(const a of s){const i=Math.max(1,Math.round(a/o));Math.abs(a-i*o)>=r||(e+=a,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let c=0,l=0,u=0;for(const T of s){const e=Math.max(1,Math.round(T/o));Math.abs(T-e*o)>=r||(c++,l+=T,u+=e)}if(c/s.length<.98)return null;o=l/u;const h=1/Math.min(u,1e3),d=Math.max(Number.EPSILON,o-h),f=o+h,m=t/f,p=t/d,g=t/o;let k=null,y=1/0;for(const T of a){if(Tp)continue;const e=Math.abs(T/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,a=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof dn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Os||e.source instanceof Ls))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Os&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Yo))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Os?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){j(this._rootSource instanceof zs);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){const i=this._sourceCache.find(i=>i.cacheGroup===t&&Us(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Us(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(et(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=tt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);j(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),ye(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);j(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:a}),a.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new ec(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)}throw new Jo})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),j(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Jo)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=await Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e),r=(await Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)}async getTracks(e){e&&(e=Vo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Ko(t,e)}async getVideoTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return Ko(t,e)}async getAudioTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return Ko(t,e)}async getPrimaryVideoTrack(e){e&&(e=Vo(e));const t=jo(e,{sortBy:async e=>[Ho((await e.getDisposition()).default),Ho(await e.hasPairableAudioTrack()),Ho(!(await e.hasOnlyKeyPackets())),Wo(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Vo(e));const t=await this.getPrimaryVideoTrack(),i=jo(e,{sortBy:async e=>[Ho(!t||e.canBePairedWith(t)),Ho((await e.getDisposition()).default),Wo(await e.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new Uo(this,e):new qo(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class Jo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Zo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class ec{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new Zo;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 tc(t,J(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Ns);return Xe(r)?r.then(t=>t?new tc(t.bytes,t.view,t.offset,e,i):null):r?new tc(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Zo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(j(null!==this.fileSizeNonStrict),this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i)));return Xe(r)?r.then(a):a(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(async()=>{const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(Xe(i)&&(i=await i),!i||0===i.length)break;const r=rc(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new tc(i,J(i),0,0,t)})()}}class tc{constructor(e,t,i,r,a){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=a,this.bufferPos=r-i}static tempFromBytes(e){return new tc(e,J(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new tc(this.bytes,this.view,this.offset,e,e+t)}}const ic=(e,t)=>{if(e.filePose.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.`)},rc=(e,t)=>{ic(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},ac=e=>(ic(e,1),e.view.getUint8(e.bufferPos++)),sc=(e,t)=>{ic(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},nc=e=>{ic(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},oc=e=>{ic(e,3);const t=Se(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},cc=e=>{ic(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},lc=(e,t)=>{ic(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},uc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},hc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},dc=e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},fc=(e,t)=>{let i,r;return t?(i=lc(e,!0),r=lc(e,!0)):(r=lc(e,!1),i=lc(e,!1)),4294967296*r+i},mc=e=>4294967296*uc(e)+uc(e),pc=e=>4294967296*dc(e)+uc(e),gc=e=>{const t=hc(e),i=(e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},kc=e=>{ic(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},yc=e=>{ic(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},bc=(e,t)=>{ic(e,t);let i="";for(let r=0;rZ.decode(rc(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Tc,Sc,vc,Pc;(Sc=Tc||(Tc={}))[Sc.Unsynchronisation=128]="Unsynchronisation",Sc[Sc.ExtendedHeader=64]="ExtendedHeader",Sc[Sc.ExperimentalIndicator=32]="ExperimentalIndicator",Sc[Sc.Footer=16]="Footer",(Pc=vc||(vc={}))[Pc.ISO_8859_1=0]="ISO_8859_1",Pc[Pc.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Pc[Pc.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Pc[Pc.UTF_8=3]="UTF_8";const Ic=128,xc=10,Cc=["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"],Bc=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=rc(e,Ic-3)),e.filePos=r;const a=Ec(e,30);a&&(t.title??(t.title=a));const s=Ec(e,30);s&&(t.artist??(t.artist=s));const n=Ec(e,30);n&&(t.album??(t.album=n));const o=Ec(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=rc(e,30);let u;if(0===l[28]&&0!==l[29]){const i=l[29];i>0&&(t.trackNumber??(t.trackNumber=i)),e.skip(-30),u=Ec(e,28),e.skip(2)}else e.skip(-30),u=Ec(e,30);u&&(t.comment??(t.comment=u));const h=ac(e);h{const i=rc(e,t),r=$e(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=bc(e,3),r=ac(e),a=ac(e),s=ac(e),n=uc(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=Ji(n);return s&Tc.Footer&&(o+=xc),{majorVersion:r,revision:a,flags:s,size:o}},Rc=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void ct._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Tc.Footer?t.size-xc:t.size,l=rc(e,c),u=new Fc(t,l);if(t.flags&Tc.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Tc.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let h=!1,d=!1,f=!1;if(3===t.majorVersion?(h=!!(64&e.flags),d=!!(128&e.flags)):4===t.majorVersion&&(h=!!(4&e.flags),d=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&Tc.Unsynchronisation)),h)ct._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(d)ct._warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=l;else{if(f&&u.ununsynchronizeRegion(u.pos,l),i.raw??(i.raw={}),"TXXX"===e.id){const e=(r=i.raw).TXXX??(r.TXXX={}),t=u.readId3V2TextEncoding(),a=u.readId3V2Text(t,l),s=u.readId3V2Text(t,l);e[a]??(e[a]=s)}else"T"===e.id[0]?(a=i.raw)[s=e.id]??(a[s]=u.readId3V2EncodingAndText(l)):(n=i.raw)[o=e.id]??(n[o]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":i.title??(i.title=u.readId3V2EncodingAndText(l));break;case"TIT3":case"TT3":i.description??(i.description=u.readId3V2EncodingAndText(l));break;case"TPE1":case"TP1":i.artist??(i.artist=u.readId3V2EncodingAndText(l));break;case"TALB":case"TAL":i.album??(i.album=u.readId3V2EncodingAndText(l));break;case"TPE2":case"TP2":i.albumArtist??(i.albumArtist=u.readId3V2EncodingAndText(l));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.trackNumber??(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.tracksTotal??(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.discNumber??(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.discsTotal??(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(l);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}i.genre??(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(l),t=new Date(e);Number.isNaN(t.getTime())||(i.date??(i.date=t))}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(l),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.lyrics??(i.lyrics=u.readId3V2Text(e,l))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.comment??(i.comment=u.readId3V2Text(e,l))}break;case"APIC":case"PIC":{const e=u.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=u.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=u.readId3V2Text(e,l);const a=u.readU8(),s=u.readId3V2Text(e,l).trimEnd(),n=l-u.pos;if(n>=0){const e=u.readBytes(n);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===a?"coverFront":4===a?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=l}}};class Fc{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{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:Ji(t);s(e)&&(i=e)}return this.pos=a,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case vc.ISO_8859_1:{let e="";for(let t=0;t0===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=$e(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=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}case vc.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=$e(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 vc.UTF_8:{const e=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ac{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch{i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(a){try{r?.disconnect()}catch(s){console.warn("MediaBunny gain setup cleanup:",s)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),a}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{t?.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Mc{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(a){r=!0,i=a}try{e.disconnect()}catch(a){r||(r=!0,i=a)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const a=function(e,t,i,r){const a=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(a+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(a,r),offset:a=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===a.offset?s.start(a.startAt):s.start(a.startAt,a.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,a.endMediaTime)}catch(n){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw n}}}const Dc=Symbol("cancelled");class Nc{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Dc);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function Oc(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class Lc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}async stopIterator(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),await t}cancel(){this.task?.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}async run(e){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Nc;this.task=r;let a=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!a||this.host.audioIterator===a);try{for(a=t.buffers(this.host.currentTime),this.host.audioIterator=a;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=await r.wait(a.next());if(i===Dc||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if(await r.wait(this.contexts.resume(i))===Dc||!s())return;Oc(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(await r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(await r.delay(50))||!s())return}}catch(n){if(s())throw n}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}}}class zc{constructor(e,h){N(this,u),N(this,t,!1),N(this,i,0),N(this,r),N(this,a),N(this,s),N(this,n,null),N(this,o,null),N(this,c,null),N(this,l),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,O(this,r,new Ac(this)),O(this,a,new Mc(this)),O(this,s,new Lc(this,D(this,r),D(this,a))),O(this,l,h)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){D(this,r).ensure(e)}updateGain(){D(this,r).updateGain()}stopQueuedNodes(){D(this,a).stop()}async stopIterator(){await D(this,s).stopIterator()}handleNoAudioTrack(){D(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){z(this,i)._++;try{this.pause()}finally{O(this,c,null),this.input=null,this.audioSink=null}}async load(e,r){if(D(this,t))return;this.cancelPending();const a=D(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>L(this,u,h).call(this,e,a,r));O(this,c,s);try{await s}finally{D(this,c)===s&&O(this,c,null)}}async runIterator(e){D(this,t)||await D(this,s).run(e)}async play(){if(D(this,t))return;if(D(this,o))return D(this,o);if(!this.paused)return;const e=new Nc;O(this,n,e);const r=D(this,i),a=L(this,u,f).call(this,e,r);O(this,o,a);try{await a}finally{D(this,n)===e&&(O(this,n,null),O(this,o,null))}}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,D(this,n)?.cancel(),O(this,n,null),O(this,o,null),D(this,s).cancel(),this.stopQueuedNodes()}async seek(e){if(D(this,t))return;const i=!this.paused;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext?.currentTime??0,this.latestScheduledEndTime=this.playbackTimeAtStart;const r=++this.asyncId;i&&L(this,u,d).call(this,r)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(D(this,t)||e===this.playbackRate)return;const i=this.currentTime;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=i,this.audioContextStartTime=this.audioContext?.currentTime??0,this.playbackRate=e,this.latestScheduledEndTime=i;const r=++this.asyncId;this.paused||L(this,u,d).call(this,r)}destroy(){if(D(this,t))return;O(this,t,!0),z(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>D(this,r).destroy()])try{t()}catch(a){e.push(a)}if(this.input=null,this.audioSink=null,O(this,c,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,a=new WeakMap,s=new WeakMap,n=new WeakMap,o=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakSet,h=async function({input:e,audioTrack:r,duration:a},s,n){const o=()=>!D(this,t)&&D(this,i)===s;if(o()){this.input=e,this.duration=a;try{const e=r&&null!==r.codec&&await r.canDecode();if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new No(r)}else this.handleNoAudioTrack();o()&&n?.()}catch(c){if(o())throw c}}},d=function(e){this.runIterator(e).catch(i=>{if(!D(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{D(this,l)?D(this,l).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=async function(e,a){const s=()=>!D(this,t)&&!e.cancelled&&D(this,i)===a;try{const t=D(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if(await e.wait(D(this,r).resume(t))===Dc||!s())return}if(D(this,c)){if(await e.wait(D(this,c))===Dc||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,L(this,u,d).call(this,++this.asyncId)}catch(n){if(s())throw n}};const Uc=new WeakMap;async function qc(e,t,i){const{input:r,loadSeq:a}=e;if(!e.media?.isHls||!r||e.destroyed)return;const s={};Uc.set(e,s);const n=()=>!e.destroyed&&e.loadSeq===a&&e.input===r&&Uc.get(e)===s;for(;n();){const a=e.media;if(!a?.isHls)return;let s;try{s=await i(r,a,t,n)}catch(o){if(!n())return;if(e.media===a)throw o;continue}if(!n())return;if(e.media===a){if(s)try{await e.replaceTracks(s)}catch(o){if(n())throw o}return}}}async function Wc(e,t,i,r){const a=await e.getVideoTracks();if(!r())return null;const s="auto"===i?await e.getPrimaryVideoTrack():a.find(e=>e.id===i)??t.videoTrack;if(!r()||!s)return null;let n=t.audioTrack,o=t.audioMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableAudioTrack(),o="auto"),{videoTrack:s,audioTrack:n,videoMode:"auto"===i?"auto":"manual",audioMode:o}}async function Hc(e,t,i,r){const a=await e.getAudioTracks();if(!r())return null;const s="auto"===i?t.videoTrack?await t.videoTrack.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack():a.find(e=>e.id===i)??t.audioTrack;if(!r()||!s)return null;let n=t.videoTrack,o=t.videoMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableVideoTrack(),o="auto"),{videoTrack:n,audioTrack:s,videoMode:o,audioMode:"auto"===i?"auto":"manual"}}async function Vc(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const jc=/\.m3u8(?:$|[?#])/i;function Kc(e){return"string"===typeof e&&jc.test(e)}function Xc(e){const t=function(e){return"string"===typeof e?new Ks(e):e instanceof Blob?new Hs(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Gs(e):e??null}(e);return t?new Yo({source:t,formats:Kc(e)?On:Nn}):null}class $c{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){return this.controller?.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}async wait(e,t){try{await Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,e?.dispose()}cancel(){if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),this.controller?.abort(),this.disposeInput()}}}async function Gc({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),a=t||i,s=Boolean(a&&await a.isLive());let n=Number.NaN;return r.length>0&&(n=await e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==n||s||(n=await e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:n??Number.NaN}function Qc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class Yc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return{...Qc(),source:this.host.loadSeq,complete:Qc()}}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,e?.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,e?.complete.resolve(),e?.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}async runPlay(e){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(await this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,await this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),Oc(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}}seek(e,t){return this.position(async t=>{const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();await Promise.all([i,r])},["seeked"],!1,t)}replace(e,t){return this.position(async i=>{e.duration=await Gc(e),i()&&(this.host.media=e,await Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(await Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))},["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=r??(this.seeking?this.wanted:!this.host.paused),this.cancelPlay();const a=this.seeking,s=this.operation();return this.seeking=s,a?.complete.resolve(),a?.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}async runPosition(e,t,i,r){const a=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!a())return;if(this.host.ended=!1,this.host.seeking=!0,Oc(this.host.events,a,["seeking","waiting"]),!a())return;if(r||this.stop(),!a())return;if(await t(a),!a())return;if(this.host.seeking=!1,e.complete.resolve(),Oc(this.host.events,a,i),!a())return;this.seeking=null,s=this.wanted}catch(n){if(!a())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(n),n}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&await this.play()}}const Jc=new WeakMap,Zc=new WeakMap;function el(e){const t=Zc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>e.value??null);Zc.set(e,i);const r=()=>{Zc.get(e)===i&&Zc.delete(e)};return i.then(r,r),i}function tl(e,t,i,r,a){const s=i?Math.max(.06,r/Math.max(1,a)):0;return i&&e{if(this.image===a&&t()){this.cancel();try{i(a)}catch(e){r(e)}}},a.onerror=()=>{this.image===a&&this.cancel()},a.src=e}}class rl{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}async update(e){const t=this.host.videoIterator;if(!t||!this.ready()||!this.current(e)||this.host.isFetching)return;const i={};this.fetching=i,this.host.isFetching=!0;const r=()=>this.current(e)&&this.host.videoIterator===t;try{for(;r();){const e=await el(t);if(!r()||!e)return;const i=this.host.audioClock?.currentTime;if(void 0===i)return;const a=tl(e.timestamp,i,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==a){if("draw"!==a)return void(this.host.nextFrame=e);this.draw(e)}}}catch(a){if(r())throw a}finally{this.fetching===i&&(this.fetching=null,this.host.isFetching=!1)}}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void Oc(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(Oc(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!D(this,w),e=>L(this,P,E).call(this,e,!0),e=>L(this,P,C).call(this,e)))}async preflight(e,t,i){return async function(e,t,i,r,a=()=>!0){if(r?.aborted||!a())return!1;if(!t||"string"!==typeof e||Kc(e))return!0;try{const t=await fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if(r?.aborted||!a())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!(r?.aborted||!a())&&(console.warn("Preflight check failed:",s),!0)}}(e,this.preflightRange,this.events,t,i)}drawPoster(){if(D(this,b)||!this.poster||this.posterDrawn)return;const e=D(this,m);D(this,T).draw(this.poster,()=>L(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,L(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>L(this,P,C).call(this,e))}async stopIterator(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,await function(e){if(!e)return Promise.resolve();const t=Jc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return Jc.set(e,i),i}(e)}clear(){L(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){z(this,m)._++,z(this,p)._++,this.stop(),L(this,P,B).call(this),D(this,T).cancel(),O(this,w,!1),O(this,g,null),O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null}async load(e,t){if(D(this,b))return;this.cancelPending();const i=D(this,m),r=D(this,p);O(this,w,!0);const a=Promise.resolve().then(()=>L(this,P,_).call(this,e,i,r,t));O(this,g,a);try{await a}finally{D(this,g)===a&&O(this,g,null)}}handleNoVideoTrack(){D(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}async resetIterator(e){if(D(this,b))return;const t=D(this,m),i=++z(this,p)._,r=D(this,g);this.stop(),D(this,T).cancel(),O(this,w,!0);try{r&&await r,await L(this,P,R).call(this,e,t,i)}catch(a){if(L(this,P,I).call(this,t)&&D(this,p)===i)throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}}async updateNextFrame(e){await D(this,S).update(e)}render(){D(this,S).render()}start(e){D(this,S).start(e)}stop(){D(this,S).stop()}async seek(e){await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){D(this,b)||(O(this,b,!0),z(this,m)._++,D(this,S).destroy(),D(this,T).cancel(),L(this,P,B).call(this),this.posterDrawn=!1,O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,w=new WeakMap,T=new WeakMap,S=new WeakMap,v=new WeakMap,P=new WeakSet,I=function(e){return!D(this,b)&&D(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){D(this,b)||(L(this,P,B).call(this),D(this,v)?D(this,v).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){D(this,T).cancel(),t&&this.clear(),L(this,P,x).call(this).drawImage(e.canvas,0,0)},_=async function(e,t,i,r){if(L(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:a,videoTrack:s,duration:n}=e;if(this.input=a,this.duration=n,!s)return this.handleNoVideoTrack(),void r?.();const o=null!==s.codec&&await s.canDecode();if(!L(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void r?.();const c=await s.canBeTransparent();if(!L(this,P,I).call(this,t))return;O(this,k,()=>new Fo(s,{poolSize:2,fit:"contain",alpha:c})),this.videoSink=D(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,r?.(),L(this,P,I).call(this,t)&&await L(this,P,R).call(this,0,t,i)}catch(a){if(L(this,P,I).call(this,t))throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}},R=async function(e,t,i){if(!L(this,P,I).call(this,t)||D(this,p)!==i)return;L(this,P,B).call(this),D(this,k)&&this.videoSink===D(this,y)&&(this.videoSink=D(this,k).call(this));const r=this.videoSink;if(!r||!L(this,P,I).call(this,t))return;O(this,y,r);const a=r.canvases(e);this.videoIterator=a;const s=()=>L(this,P,I).call(this,t)&&D(this,p)===i&&this.videoIterator===a,n=await el(a);if(!s())return;const o=await el(a);s()&&(this.nextFrame=o,n?L(this,P,E).call(this,n,!1):this.drawPoster())};class sl{constructor({canvas:e,ctx:t,events:i,option:r={}}){N(this,F),this.events=i,this.option=r,this.audio=new zc(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new al({canvas:e,ctx:t,events:i,timeupdateInterval:r.timeupdateInterval??250,avSyncTolerance:r.avSyncTolerance??.12,dropLateFrames:r.dropLateFrames??!1,poster:r.poster??"",preflightRange:r.preflightRange??!1,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,O(this,F,new Yc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,D(this,F).ended(),this.audio.pause())})}async load(e){if(this.destroyed)return;const t=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),this.loadSession?.cancel(),t!==this.loadSeq||this.destroyed)return;if(this.pause(),t!==this.loadSeq||this.destroyed)return;this.disposeInput();const i=new $c;this.loadSession=i,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,i.defer(()=>this.events.emit("waiting")),i.defer(()=>this.events.emit("loadstart"));const r=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout??0:0;try{await i.wait(this.performLoad(e,t,i),r)}catch(a){if(t!==this.loadSeq)return;const e=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),i.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}}async performLoad(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(await this.video.preflight(e,i.signal,r))||!r())return;const a=Xc(e);if(!a)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(a);const s=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await Gc({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Kc(t);return{input:e,videoTrack:i,audioTrack:r,duration:a,isLive:!Number.isFinite(a)&&Boolean(s&&await s.isLive()),isHls:n,videoMode:n?"auto":"manual",audioMode:n?"auto":"manual"}}(a,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=a,this.media=s;const n=function(e,t){let i=!1,r=!1,a=!1;function s(s){t()&&!a&&("video"===s?i=!0:r=!0,i&&r&&(a=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,Oc(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,n.video),t=r()?this.audio.load(s,n.audio):Promise.resolve();if(await Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,Oc(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){this.loadSession?.disposeInput(),this.input=null,this.media=null}async replaceTracks(e){if(this.media&&!this.destroyed)return D(this,F).replace({...this.media,...e},this.currentTime)}async selectHlsQuality(e){return function(e,t){return qc(e,t,Wc)}(this,e)}async selectHlsAudio(e){return function(e,t){return qc(e,t,Hc)}(this,e)}async getHlsState(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=await async function(e){if(!e?.isHls||!e.input)return null;const[t,i]=await Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[r,a]=await Promise.all([Promise.all(t.map(async(e,t)=>({id:e.id,track:e,index:t,name:await e.getName(),height:await e.getDisplayHeight(),bitrate:await Vc(e)}))),Promise.all(i.map(async(e,t)=>{const i=await e.getName(),r=await e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:await Vc(e)}}))]);return{levels:r,audios:a,currentLevel:e.videoTrack?r.find(t=>t.id===e.videoTrack?.id)??null:null,currentAudio:e.audioTrack?a.find(t=>t.id===e.audioTrack?.id)??null:null,videoMode:e.videoMode??"auto",audioMode:e.audioMode??"auto"}}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}}async play(){return D(this,F).play()}pause(){D(this,F).pause()}async seek(e){return D(this,F).seek(e)}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,D(this,F).invalidate();const e=[];for(const i of[()=>this.loadSession?.cancel(),()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){return this.media?.duration??this.audio.duration??this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}F=new WeakMap;const nl=new WeakMap;function ol(e){let t=nl.get(e);return t||(t={closed:!1,frames:new Set},nl.set(e,t)),t}class cl{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new V,this.engine=new sl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=r.volume??.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:e.option?.url&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=ol(e);if(i.closed)return 0;const r=requestAnimationFrame(a=>{i.frames.delete(r),i.closed||t(a,{presentationTime:e.engine.currentTime,expectedDisplayTime:a+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:a,receiveTime:a,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){ol(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=ol(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,a=r("canvas"),s=a.getContext("2d"),n=new cl({art:t,canvas:a,ctx:s,option:e});t.mediabunny=n;const o={};for(const e in a)"function"===typeof a[e]&&(o[e]=a[e].bind(a));const c=new Set([...Object.getOwnPropertyNames(n),...Object.getOwnPropertyNames(Object.getPrototypeOf(n))]);for(const e of c)"constructor"!==e&&(e in a||Object.defineProperty(a,e,{get(){const t=n[e];return"function"===typeof t?t.bind(n):t},set(t){n[e]=t},configurable:!0,enumerable:!0}));for(const e in o)a[e]=(...t)=>o[e](...t);function l(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(a.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",l),t.on("video:loadedmetadata",l),H({art:t,shim:n,option:e}),t.on("destroy",()=>{delete t.mediabunny,n.destroy()}),a}}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,a,s,n,o,c,l,u,h,d,f,m,p,g,k,y,b,w,T,S,v,P,I,x,C,B,E,_,R,F,A=e=>{throw TypeError(e)},M=(e,t,i)=>t.has(e)||A("Cannot "+i),D=(e,t,i)=>(M(e,t,"read from private field"),i?i.call(e):t.get(e)),N=(e,t,i)=>t.has(e)?A("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),O=(e,t,i,r)=>(M(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),L=(e,t,i)=>(M(e,t,"access private method"),i),z=(e,t,i,r)=>({set _(r){O(e,t,r,i)},get _(){return D(e,t,r)}});function U(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function q(e,t,i){const r={control:!1,setting:!1};let a=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function n(){a=null,U([()=>s("control"),()=>s("setting")])}return{update:function(o,c,l,u){if(!o)return void n();a=o;const h=()=>a===o&&l(),d=async e=>h()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html;c.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:d})):s("control"),h()&&(c.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:d})):s("setting"))},clear:n}}function W(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function H({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,a=0,s=0;const n=q(e,"mediabunny-quality",''),o=q(e,"mediabunny-audio",''),c=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;async function l(){if(r||t.engine.destroyed)return;const e=++a,s=t.engine.loadSeq,l=()=>e===a&&c(s);try{const e=await t.getM3u8State();if(!l())return;const r=i.m3u8?.quality||{},a=function(e,t,i){if(!t.control&&!t.setting||!e?.levels.length)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||`${e.height}P`),s=e.currentLevel?a(e.currentLevel):r,n=[];for(const l of e.levels){if(!i())return null;n.push({html:a(l),value:l.id,default:e.currentLevel?.id===l.id})}const o=new Map(e.levels.map(e=>[e.id,e.height])),c=W(n).sort((e,t)=>("auto"===t.value?0:o.get(t.value)||0)-("auto"===e.value?0:o.get(e.value)||0));return c.push({html:r,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:s,selector:c}}(e,r,l);if(!l())return;if(n.update(a,r,()=>c(s),(e,t)=>u("quality",e,t)),!l())return;const h=i.m3u8?.audio||{},d=function(e,t,i){if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||e.lang||e.language),s=e.currentAudio?a(e.currentAudio):r,n=[];for(const c of e.audios){if(!i())return null;n.push({html:a(c),value:c.id,default:e.currentAudio?.id===c.id})}const o=W(n);return o.push({html:r,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:s,selector:o}}(e,h,l);l()&&o.update(d,h,()=>c(s),(e,t)=>u("audio",e,t))}catch(h){if(l())throw h}}async function u(i,r,n){const o=++s,u=t.engine.loadSeq;a++;const d=()=>o===s&&c(u);try{"quality"===i?await t.switchM3u8Quality(r.value):await t.switchM3u8Audio(r.value),d()&&(await l(),d()&&(e.notice.show=`${n}: ${r.html}`))}catch(f){if(d()&&(await h(),d()))throw f}return r.html}function h(){return l().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function d(){a++,s++;try{U([n.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}function f(){if(!r){r=!0,d();try{U([()=>e.off("video:loadedmetadata",h),()=>e.off("restart",h),()=>e.off("video:loadstart",d),()=>e.off("video:error",d),()=>e.off("destroy",f)])}catch(t){console.warn("MediaBunny HLS listener cleanup:",t)}}}try{e.on("video:loadedmetadata",h),e.on("restart",h),e.on("video:loadstart",d),e.on("video:error",d),e.on("destroy",f)}catch(m){throw f(),m}return{update:l,destroy:f}}class V{constructor(){N(this,e,!1),this.listeners=new Map}addEventListener(t,i){D(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t)?.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){if(D(this,e))return;const r=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{D(this,e)||t(r)})}destroy(){O(this,e,!0),this.listeners.clear()}}function j(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const K=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},X=e=>e&&e[e.length-1],$=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-2**r)},Q=e=>{const t=$(e);return 0===(1&t)?-(t>>1):t+1>>1},Y=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),J=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Z=new TextDecoder,ee=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),te={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ie=ee(te),re={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ae=ee(re),se={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ne=ee(se),oe=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,ce={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},le=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class ue{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const he=/^[0-9a-fA-F]+$/,de=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),fe=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,me=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},ge=(e,t,i)=>{const r=pe(e,i(t),i);e.splice(r+1,0,t)},ke=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},ye=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},be=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},we=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Te=e=>{throw new Error(`Unexpected value: ${e}`)},Se=(e,t,i)=>{const r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},ve=(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)},Pe=(e,t)=>({async next(){const i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),Ie=(e,t,i)=>Math.max(t,Math.min(i,e)),xe="und",Ce=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Be=(e,t)=>Math.round(e/t)*t,Ee=(e,t)=>Math.round(e*t)/t,_e=(e,t)=>Math.floor(e/t)*t,Re=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},Fe=/^[a-z]{3}$/,Ae=e=>Fe.test(e),Me=1e6*(1+Number.EPSILON),De=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?Ne(e.headers):{},a=t.headers?Ne(t.headers):{},s={...r};Object.entries(a).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},Ne=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},Oe=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(n){if(a())throw n;s++;const e=r(s,n,t);if(null===e)throw n;if(ct._error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await at(1e3*e),a())throw n}};class Le{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ze=null;const Ue=()=>null!==ze?ze:ze=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let qe=null;const We=()=>null!==qe?qe:qe="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let He=null;const Ve=()=>null!==He?He:He=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),je=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,Ke=(async()=>{})().constructor,Xe=e=>e instanceof Ke||e instanceof Promise||"function"===typeof e?.then,$e=(e,t)=>-1!==e?e:t,Ge=(e,t,i,r)=>e<=r&&i<=t,Qe=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Je=e=>"number"===typeof e&&!Number.isNaN(e),Ze=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const a=e.indexOf("/",r+3);i=-1===a?e+t:e.slice(0,a)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const a=i.indexOf("://");if(-1!==a){const e=i.indexOf("/",a+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),n=[];for(const o of s)".."===o?n.pop():"."!==o&&n.push(o);return r+n.join("/")},et=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{j(Number.isInteger(e.num)),j(Number.isInteger(e.den)),j(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}},rt=(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.`)},at=e=>new Promise(t=>setTimeout(t,e));class st{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const r={fn:t,once:i?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(a){console.error(a)}s.once&&r.delete(s)}}}var nt,ot;(ot=nt||(nt={}))[ot.Silent=0]="Silent",ot[ot.Errors=1]="Errors",ot[ot.Warnings=2]="Warnings",ot[ot.Info=3]="Info";class ct{constructor(){}static get level(){return ct._level}static set level(e){if(e!==nt.Silent&&e!==nt.Errors&&e!==nt.Warnings&&e!==nt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ct._level=e}static get _emitter(){return ct._emitterInstance??(ct._emitterInstance=new st)}static on(e,t,i){return ct._emitter.on(e,t,i)}static _error(...e){ct._emitter._emit("error",e),ct._level>=nt.Errors&&console.error(...e)}static _warn(...e){ct._emitter._emit("warn",e),ct._level>=nt.Warnings&&console.warn(...e)}static _info(...e){ct._emitter._emit("info",e),ct._level>=nt.Info&&console.info(...e)}}ct._level=nt.Info,ct._emitterInstance=null;class lt{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 ut{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 ht={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class dt{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(7&this.pos),r=(t&1<>i;return this.pos++,r}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new dt(this.bytes);return e.pos=this.pos,e}}const ft=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],mt=[-1,1,2,3,4,5,6,8],pt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new dt(e),i=gt(t),{frequencyIndex:r,sampleRate:a}=kt(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=mt[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=kt(t).sampleRate,o=gt(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===gt(t)&&t.readBits(1)&&(l=kt(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(c=!!t.readBits(1)));break}t.pos=e+1}return null!==n&&n>1&&(c=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:c&&1===n?2:n}},gt=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},kt=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let a=0;t+3i&&(yield{offset:i,length:t-i}),i=t+a,t=i):t++}-1!==i&&i{if(t.description){const i=3&Y(t.description)[4];return It(e,i+1)}return Pt(e)},Ct=e=>31&e,Bt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Et.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Et,r),r+=Et.byteLength,i.set(a,r),r+=a.byteLength;return i},Rt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let a=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(a,s.byteLength);break;case 2:e.setUint16(a,s.byteLength,!1);break;case 3:ve(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Ft=e=>{try{const t=[],i=[],r=[];for(const o of Pt(e)){const a=e.subarray(o.offset,o.offset+o.length),s=Ct(a[0]);s===wt.SPS?t.push(a):s===wt.PPS?i.push(a):s===wt.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=Nt(a);j(null!==s);const n=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:n?s.chromaFormatIdc:null,bitDepthLumaMinus8:n?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:n?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:n?r:null}}catch(t){return ct._error("Error building AVC Decoder Configuration Record:",t),null}},At=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint8(i++),n=t.getUint8(i++),o=3&t.getUint8(i++),c=31&t.getUint8(i++),l=[];for(let f=0;f{try{const t=Bt(e),i=new dt(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();$(i);let n=1,o=0,c=0,l=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=$(i),3===n&&(l=i.readBits(1)),o=$(i),c=$(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==n?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,a=8;for(let e=0;ee.level>=s)??X(Ai),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);v=r,P=r}else v=0,P=0}return j(null!==P),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:S,colourPrimaries:y,matrixCoefficients:w,transferCharacteristics:b,fullRangeFlag:T,numReorderFrames:v,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:C,bitstreamRestrictionFlagBitOffset:I,bitstreamRestrictionFlag:x}}catch(t){return ct._error("Error parsing AVC SPS:",t),null}},Ot=e=>{const t=$(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)$(e),$(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Lt=e=>{j(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new dt(e.emulationUnpreventedBytes),r=new dt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(j(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),G(r,2),G(r,1),G(r,16),G(r,16),G(r,e.numReorderFrames),G(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return j(Number.isInteger(a)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,a))},zt=(e,t)=>{if(t.description){const i=3&Y(t.description)[21];return It(e,i+1)}return Pt(e)},Ut=e=>e>>1&63,qt=e=>{try{const t=new dt(Bt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Ht(t,i);$(t);const u=$(t);let h=0;3===u&&(h=t.readBits(1));const d=$(t),f=$(t);let m=d,p=f;if(t.readBits(1)){const e=$(t),i=$(t),r=$(t),a=$(t);let s=1,n=1;const o=0===h?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),m-=(e+i)*s,p-=(r+a)*n}const g=$(t),k=$(t);$(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)$(t),b=$(t),$(t);$(t),$(t),$(t),$(t),$(t),$(t),t.readBits(1)&&t.readBits(1)&&Vt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),$(t),$(t),t.skipBits(1));const w=$(t);if(jt(t,w),t.readBits(1)){const e=$(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of Pt(e)){const s=e.subarray(c.offset,c.offset+c.length),n=Ut(s[0]);n===St.VPS_NUT?t.push(s):n===St.SPS_NUT?i.push(s):n===St.PPS_NUT?r.push(s):n!==St.PREFIX_SEI_NUT&&n!==St.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=qt(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new dt(Bt(e));t.skipBits(16),$(t),$(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),$(t),$(t),Q(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&$(t),Q(t),Q(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType: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}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ut(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:n,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return ct._error("Error building HEVC Decoder Configuration Record:",t),null}},Ht=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let u=0;u<6;u++)n[u]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let u=0;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&Q(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){if(t===i){n=t-($(e)+1)}else n=t-1;e.readBits(1),$(e);const s=r[n]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=r[n]}else{const t=$(e),i=$(e);for(let r=0;r{let i=2,r=2,a=2,s=0,n=0,o={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{const e=Dt[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&($(e),$(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&($(e),$(e),$(e),$(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&$(e),e.readBits(1)&&$t(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=$(e),$(e),$(e),$(e),$(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},$t=(e,t,i)=>{let r=!1,a=!1,s=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?$(e):i=1===e.readBits(1);let n=1;if(!i){n=$(e)+1}r&&Gt(e,n,s),a&&Gt(e,n,s)}},Gt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=Qt.audAllowed;for(const s of zt(e,t)){if(r===Qt.noMoreDataAllowed){i.add(s.offset);continue}const t=Ut(e[s.offset]);if(r===Qt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>Qt.audAllowed?a=!0:r=Qt.beforeFirstVcl:t<=31?r>Qt.afterFirstVcl?a=!0:r=Qt.afterFirstVcl:36===t?r!==Qt.afterFirstVcl?a=!0:r=Qt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>Qt.beforeFirstVcl?a=!0:r=Qt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&Y(t.description)[21];return Rt(e,i+1)}return _t(e)})(a,t)},Zt={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},ei=e=>{const t=new dt(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(r>=2){a=t.readBits(1)?12:10}const s=t.readBits(3);let n=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);n=e||i?e&&!i?2:1:3,t.skipBits(1)}else n=1}else n=3,o=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let l=X(Mi).level;for(const h of Mi)if(c<=h.maxPictureSize){l=h.level;break}const u=Zt[s];return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:u?.colourPrimaries??2,transferCharacteristics:u?.transferCharacteristics??2,matrixCoefficients:u?.matrixCoefficients??2}},ti=function*(e){const t=new dt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*2**(7*i),!(128&r))break;if(7===i&&128&r)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),a=t.readBits(1),s=t.readBits(1);let n;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;n=e}else n=Math.floor(t.getBitsLeft()/8);j(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},ii=e=>{for(const{type:t,data:i}of ti(e)){if(1!==t)continue;const e=new dt(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const h=l+1;e.skipBits(h);let d=0;if(d=a?0:e.readBits(1),d&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},ri=e=>{if(e.length<36)return null;const t=J(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},ai=[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],si=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;u97;)if(1===r.readBits(1)){a=r.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;r.getBitsLeft()>=97;){const e=r.pos,t=r.readBits(8),i=r.readBits(16),a=r.readBits(16);if(t>63||0!==i||0!==a){r.pos=e;break}if(r.skipBits(1),s++,s>64)break;r.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;r.pos=0,r.skipBits(a);const l=Array(c).fill(0);for(let u=c-1;u>=0;u--)r.skipBits(40),l[u]=r.readBits(1);return{modeBlockflags:l}},ni=(e,t,i)=>{switch(e){case"avc":for(const e of xt(i,t)){const t=i[e.offset],r=Ct(t);if(r>=wt.NON_IDR_SLICE&&r<=wt.SLICE_DPC)return"delta";if(r===wt.IDR)return"key";if(r===wt.SEI&&!Ve()){const t=i.subarray(e.offset,e.offset+e.length),r=Bt(t);let a=1;do{let e=0;for(;;){const t=r[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new dt(r);e.pos=8*a;const t=$(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=J(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=Z.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(i=t.raw).vendor??(i.vendor=o));const c=a.getUint32(s,!0);s+=4;for(let l=0;l0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=l.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.discNumber??(t.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??(t.discsTotal=r))}break;case"DISCTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(l);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=l);break;case"METADATA_BLOCK_PICTURE":{const e=Qe(l),i=J(e),r=i.getUint32(0,!1),a=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=i.getUint32(8+a,!1),o=Z.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),u=e.subarray(a+n+32,a+n+32+c);t.images??(t.images=[]),t.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},ui=[2,1,2,3,3,4,4,5],hi=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),a=t.readBits(5);if(a>8)return null;const s=t.readBits(3),n=t.readBits(3);0!==(1&n)&&1!==n&&t.skipBits(2),0!==(4&n)&&t.skipBits(2),2===n&&t.skipBits(2);return{fscod:i,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},di=[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],fi=[1,2,3,6],mi=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),a=t.readBits(2);let s,n=0;3===a?(n=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;const u=fi[s];let h;h=a<3?yt[a]/1e3:bt[n]/1e3;return{dataRate:Math.round((r+1)*h/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},pi=e=>{const t=e.substreams[0];return j(t),t.fscod<3?yt[t.fscod]:null!==t.fscod2&&t.fscod2<3?bt[t.fscod2]:null},gi=e=>{const t=e.substreams[0];j(t);let i=ui[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},ki=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],yi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],bi=[16,16,20,20,0,24,24,0],wi=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ti=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Si=[32e3,44100,48e3,0],vi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Pi=[512,1024,2048,4096],Ii=e=>{const t=Ci(e),i=J(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Bi(e.subarray(r));if(!t)break;a??(a=t),r+=t.frameSize}if(t)return{frameSize:a?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==a};if(!a?.asset)return null;const{asset:s}=a;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},xi=e=>{const t=Ii(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Ci=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new dt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const a=t.readBits(14)+1;if(a<96)return null;const s=t.readBits(6);if(s>=wi.length)return null;const n=ki[t.readBits(4)];if(0===n)return null;const o=yi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const c=t.readBits(2);if(3===c)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const l=bi[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:wi[s]+(u?1:0),sampleCount:32*r,channelLayout:Ti[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Bi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new dt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),a=8+4*r,s=16+4*r;t.skipBits(a);const n=t.readBits(s)+1,o={frameSize:n,asset:null};if(!t.readBits(1))return o;const c=Si[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,h=t.readBits(3)+1,d=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===c||t.getBitsLeft()<0?o:{frameSize:n,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:f}}},Ei=e=>Re(e)+Re(44646&e),_i=["avc","hevc","vp9","av1","vp8","prores"],Ri=["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"],Fi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Ri],Ai=[{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}],Mi=[{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}],Di=".01.01.01.01.00",Ni=".0.110.01.01.01.0",Oi=["ap4x","ap4h","apch","apcn","apcs","apco"],Li=["dtsc","dtsh","dtsl","dtse"],zi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o,proresFormat:c}=e;if("avc"===t){if(j(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${de(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}.${de(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=fe(s.generalProfileCompatibilityFlags),a=s.generalTierFlag,n=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=J(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=fe(s.getUint32(2)),a=c>>5&1,n=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=r.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=n;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!n){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${n.profile.toString().padStart(2,"0")}.${n.level.toString().padStart(2,"0")}.${n.bitDepth.toString().padStart(2,"0")}.${n.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${n.colourPrimaries.toString().padStart(2,"0")}.${n.transferCharacteristics.toString().padStart(2,"0")}.${n.matrixCoefficients.toString().padStart(2,"0")}.${n.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Di)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),a=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),n=o.monochrome?"1":"0",c=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),l=r?.primaries?te[r.primaries]:1,u=r?.transfer?re[r.transfer]:1,h=r?.matrix?se[r.matrix]:1,d=r?.fullRange?1:0;let f=`av01.${t}.${i}${a}.${s}`;return f+=`.${n}.${c.toString().padStart(3,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${d}`,f.endsWith(Ni)&&(f=f.slice(0,-17)),f}if("prores"===t)return c??"apch";throw null!==t&&Te(t),new TypeError(`Unhandled codec '${t}'.`)},Ui=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Mt(e.codecDescription)?.sequenceParameterSets[0]),t){const e=Nt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===St.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),h=(15&t.getUint8(i++))<<8|t.getUint8(i++),d=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,w=k>>2&1,T=3&k,S=t.getUint8(i++),v=[];for(let P=0;P>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===St.SPS_NUT)?.nalUnits[0]),t){const e=qt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ie[e.vp9CodecInfo.colourPrimaries],transfer:ae[e.vp9CodecInfo.transferCharacteristics],matrix:ne[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ie[e.av1CodecInfo.colourPrimaries],transfer:ae[e.av1CodecInfo.transferCharacteristics],matrix:ne[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ie[e.proresCodecInfo.colourPrimaries],transfer:ae[e.proresCodecInfo.transferCharacteristics],matrix:ne[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},qi=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=pt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return a??"dtsc";if(t&&Ri.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Wi=48e3,Hi=/^pcm-([usf])(\d+)(be)?$/,Vi=e=>{if(j(Ri.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=Hi.exec(e);let i;j(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},ji=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":Oi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":Li.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Hi.test(e)?e:"webvtt"===e?"webvtt":null,Ki=[44100,48e3,32e3],Xi=[-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],$i=1483304551,Gi=1231971951,Qi=(e,t)=>3===e?3===t?21:36:3===t?13:21,Yi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,h=s>>6&3,d=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Xi[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=Ki[u]>>n+o,b=((e,t,i,r,a)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Zi,er;(er=Zi||(Zi={}))[er.FrameCount=1]="FrameCount",er[er.FileSize=2]="FileSize",er[er.Toc=4]="Toc";const tr=e=>3===e?1:2;class ir{constructor(e){this.input=e}dispose(){}}const rr=new Uint8Array(0);class ar{constructor(e,t,i,r,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=a,e===rr&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!==typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===rr}get microsecondTimestamp(){return Math.trunc(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new ar(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new ar(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const sr=e=>{const t=J(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=de(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=uc(e);const i=bc(e,4);let r=8;1===t&&(t=mc(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},cr=e=>dc(e)/65536,lr=e=>dc(e)/1073741824,ur=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=ac(e);if(t|=127&i,0===(128&i))break}return t},hr=e=>{let t=nc(e);return e.skip(2),t=Math.min(t,e.remainingLength),Z.decode(rc(e,t))},dr=e=>{const t=or(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=uc(e);e.skip(4);const r=rc(e,t.contentSize-8);switch(i){case 1:return Z.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new lt(r,"image/jpeg");case 14:return new lt(r,"image/png");case 27:return new lt(r,"image/bmp");default:return r}},fr=16,mr=new Uint32Array(256),pr=new Uint32Array(256),gr=new Uint32Array(256),kr=new Uint32Array(256),yr=new Uint32Array(256),br=new Uint32Array(256),wr=new Uint32Array(10);let Tr=!1;class Sr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(fr/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(fr),this.out=new Uint8Array(fr),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){j(16===e.byteLength),j(16===t.byteLength),Tr||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,n=1;s<256;s++)i[s]=n,t[n]=s,n=n^n<<1^(128&n?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let a=r^r<<1^r<<2^r<<3^r<<4;a=a>>>8^255&a^99,e[s]=a}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);mr[s]=t<<24|t<<16|t<<8|t,br[s]=i<<24|i<<16|i<<8|i;const a=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);pr[s]=a,gr[s]=a>>>8|a<<24,kr[s]=a>>>16|a<<16,yr[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)wr[s]=a<<24,a=a<<1^(128&a?283:0);Tr=!0})();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let a=4;a<44;a+=4){const e=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^4278190080&mr[e>>>16&255]^16711680&mr[e>>>8&255]^65280&mr[e>>>0&255]^255&mr[e>>>24&255]^wr[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a>>24&255]]^gr[255&mr[t>>>16&255]]^kr[255&mr[t>>>8&255]]^yr[255&mr[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,h;for(let g=1;g<10;g++){const a=4*g;c=pr[e>>>24]^gr[r>>>16&255]^kr[i>>>8&255]^yr[255&t]^this.roundkey[a],l=pr[t>>>24]^gr[e>>>16&255]^kr[r>>>8&255]^yr[255&i]^this.roundkey[a+1],u=pr[i>>>24]^gr[t>>>16&255]^kr[e>>>8&255]^yr[255&r]^this.roundkey[a+2],h=pr[r>>>24]^gr[i>>>16&255]^kr[t>>>8&255]^yr[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=h}const d=4278190080&br[e>>>24&255]^16711680&br[r>>>16&255]^65280&br[i>>>8&255]^255&br[t>>>0&255]^this.roundkey[40],f=4278190080&br[t>>>24&255]^16711680&br[e>>>16&255]^65280&br[r>>>8&255]^255&br[i>>>0&255]^this.roundkey[41],m=4278190080&br[i>>>24&255]^16711680&br[t>>>16&255]^65280&br[e>>>8&255]^255&br[r>>>0&255]^this.roundkey[42],p=4278190080&br[r>>>24&255]^16711680&br[i>>>16&255]^65280&br[t>>>8&255]^255&br[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,d^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class vr extends ir{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Xe(r)&&(r=await r),!r)break;const a=e,s=or(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=bc(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Xe(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>a+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=a+s.totalSize}if(!i&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){j(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Xe(e)&&(e=await e),j(e);const t=uc(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Xe(e)&&(e=await e),e){const t=or(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Xe(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==vr)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const i of t.tracks){const e={id:i.id,demuxer:this,trackBacking:null,disposition:i.disposition,timescale:i.timescale,durationInMediaTimescale:i.durationInMediaTimescale,durationInMovieTimescale:i.durationInMovieTimescale,rotation:i.rotation,internalCodecId:i.internalCodecId,name:i.name,languageCode:i.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:i.editListPreviousSegmentDurations,editListOffset:i.editListOffset,encryptionInfo:i.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:i.info};if(i.trackBacking)if(j(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ir(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new xr(t),this.tracks.push(e)}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,null===e.sampleTableByteOffset)return t;j(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(i),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Ri.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){j("audio"===e.info?.type);const i=Vi(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),u=t.sampleTimingEntries[l],h=pe(t.sampleTimingEntries,c,e=>e.startIndex),d=t.sampleTimingEntries[h],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta-f,p=X(r);p&&p.delta===m?p.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:f,count:1,delta:m});const g=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(g)}n.startSampleIndex=n.startChunkIndex,n.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let i=0;ie.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===a.moofOffset);if(i)Rr(s,i.timestamp);else{const e=pe(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Rr(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=pe(t,s.startTimestamp,e=>e.startTimestamp);if(-1!==i&&t[i].moofOffset===a.moofOffset||t.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:s.startTimestamp,endTimestamp:s.endTimestamp}),s.encryptionAuxInfo&&e.encryptionInfo){const t=await Dr(this.reader,e.encryptionInfo,s.encryptionAuxInfo);for(let e=0;e0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ae(t.languageCode)||(t.languageCode=xe)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=bc(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...ce},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=M,this.readContiguousBoxes(e.slice(N,D.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=ac(e);e.skip(3);const r=uc(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*uc(e),e.skip(8)):2===n&&(e.skip(4),l=yc(e),o=uc(e),e.skip(4),c=uc(e),u=uc(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const h="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===h);else if("opus"===h)t.info.codec="opus",t.info.sampleRate=Wi;else if("flac"===h)t.info.codec="flac";else if("ulaw"===h)t.info.codec="ulaw";else if("alaw"===h)t.info.codec="alaw";else if("ac-3"===h)t.info.codec="ac3";else if("ec-3"===h)t.info.codec="eac3";else if(Li.includes(h))t.info.codec="dts",t.info.dtsFormat=h;else if("twos"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ct._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(ct._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===h)t.info.codec="pcm-u8";else if("in24"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===h){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":(ct._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":(ct._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===h){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===h&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==ac(e),t.encryptionInfo.defaultPerSampleIvSize=ac(e),t.encryptionInfo.defaultKid=de(rc(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=ac(e),r=new Uint8Array(16);r.set(rc(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(4);const i=ac(e),r=ac(e),a=ac(e),s=a>>4,n=a>>1&7,o=1&a,c=ac(e),l=ac(e),u=ac(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case"av1C":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(1);const i=ac(e),r=i>>5,a=31&i,s=ac(e),n=s>>7,o=s>>6&1,c=s>>4&1,l=s>>3&1,u=s>>2&1,h=3&s,d=2===r&&o?s>>5&1?12:10:o?10:8;e.skip(1);const f=rc(e,D.contentSize-4),m=ii(f);t.info.av1CodecInfo={profile:r,level:a,tier:n,bitDepth:d,monochrome:c,chromaSubsamplingX:l,chromaSubsamplingY:u,chromaSamplePosition:h,videoFullRangeFlag:m?.videoFullRangeFlag??0,colourPrimaries:m?.colourPrimaries??2,transferCharacteristics:m?.transferCharacteristics??2,matrixCoefficients:m?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=bc(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=nc(e),a=nc(e),s=nc(e);let n;"nclx"===i&&(n=Boolean(128&ac(e))),t.info.colorSpace={primaries:ie[r],transfer:ae[a],matrix:ne[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=uc(e),r=uc(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==t.info?.type)break;e.skip(4);j(3===ac(e)),ur(e),e.skip(2);const i=ac(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=ac(e);e.skip(t)}a&&e.skip(2);j(4===ac(e));const s=ur(e),n=e.filePos,o=ac(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":ct._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-n){j(5===ac(e));const i=ur(e);if(t.info.codecDescription=rc(e,i),"aac"===t.info.codec){const e=pt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&nc(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=ac(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=ac(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(1);const i=ac(e),r=nc(e),a=uc(e),s=cc(e),n=ac(e);let o;o=0!==n?rc(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,i),l.setUint16(10,r,!0),l.setUint32(12,a,!0),l.setInt16(16,s,!0),l.setUint8(18,n),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=127,r=128,a=e.filePos;for(;e.filePos>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(a&r)break}const s=e.filePos;e.filePos=a;const n=rc(e,s-a),o=new Uint8Array(4+n.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(n,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=rc(e,3),r=new dt(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=yt[a]),t.info.numberOfChannels=ui[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new dt(e),i=t.readBits(13),r=t.readBits(3),a=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),n=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let c=0;o>0?c=t.readBits(9):t.skipBits(1),a.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:n,numDepSub:o,chanLoc:c})}return 0===a.length?null:{dataRate:i,substreams:a}})(rc(e,D.contentSize));if(!i){ct._warn("Invalid dec3 box contents, ignoring.");break}const r=pi(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=gi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=J(e),i=t.getUint32(0);if(0===i)return null;const r=new dt(e);r.seekToByte(13);const a=r.readBits(2);r.skipBits(5);const s=r.readBits(1),n=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return 0!==o?c=Ei(o):ne.id===i);if(!r)break;const a=uc(e),s=(12&a)>>2,n=3&a,o=[ac,nc,oc,uc],c=o[(48&a)>>4],l=o[s],u=o[n],h=uc(e);for(let d=0;de.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let a=0;ae.id===l);if(!u)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=mc(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=uc(e)),a&&(u.currentFragmentState.defaultSampleDuration=uc(e)),s&&(u.currentFragmentState.defaultSampleSize=uc(e)),n&&(u.currentFragmentState.defaultSampleFlags=uc(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;j(t.currentFragmentState);const i=ac(e);e.skip(3);const r=0===i?uc(e):mc(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;j(this.currentFragment),j(t.currentFragmentState);const i=ac(e),r=oc(e),a=Boolean(1&r),s=Boolean(4&r),n=Boolean(256&r),o=Boolean(512&r),c=Boolean(1024&r),l=Boolean(2048&r),u=uc(e);let h=null;a&&(h=dc(e));let d,f=null;s&&(f=uc(e)),this.currentFragment.trackData.has(t.id)?(d=this.currentFragment.trackData.get(t.id),null!==h&&(d.currentOffset=t.currentFragmentState.baseDataOffset+h)):(d={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(h??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,d));for(let m=0;m0&&(a=rc(e,r));const s=Mr(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=ac(e);if(1&oc(e)){const i=bc(e,4),r=uc(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=uc(e);if(0===r)break;r>1&&ct._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?uc(e):Number(mc(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Mr(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;j(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=oc(e),a=Boolean(2&r),s=uc(e),n=t.encryptionInfo.defaultPerSampleIvSize;j(null!==n);for(let o=0;o0?r.set(rc(e,n),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=nc(e);s=[];for(let i=0;i0&&((B=this.metadataTags).trackNumber??(B.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((E=this.metadataTags).tracksTotal??(E.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((_=this.metadataTags).trackNumber??(_.trackNumber=t)),i>0&&((R=this.metadataTags).tracksTotal??(R.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((F=this.metadataTags).discNumber??(F.discNumber=t)),i>0&&((A=this.metadataTags).discsTotal??(A.discsTotal=i))}}}}}return e.filePos=O,!0}}class Pr{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;j(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return(t?.timestamp??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ce(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Cr(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Ar(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=pe(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=we(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 j(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Er(i,e);if(!r)return null;let a;if(t.metadataOnly)a=rr;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Xe(t)&&(t=await t),!t)return null;if(a=rc(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Dr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),u=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,h=pe(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),d=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(u?.moofOffset??0,d?.moofOffset??0)||null;let m;for(e?null===f||e.moofOffset>=f?(m=e.moofOffset+e.moofSize,n=e):m=f:m=f??0;;){if(n){const e=n.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(m,8,16);if(Xe(e)&&(e=await e),!e)break;const i=m,l=or(e);if(!l)break;if("moof"===l.name){n=await s.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(n);if(r)return this.fetchPacketInFragment(n,e,a);-1!==e&&(o=n,c=e)}m=i+l.totalSize}if(u&&(!o||o.moofOffset{var e,t,i,r,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&ri(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&ii(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&ei(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else{const e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Wt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Ft(e.data)}if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(this.internalTrack.info);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const s={codec:zi(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(s.displayAspectWidth=this.internalTrack.info.squarePixelWidth,s.displayAspectHeight=this.internalTrack.info.squarePixelHeight),s})()):null}}class xr extends Pr{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Cr=(e,t)=>{if(e.presentationTimestamps){const i=pe(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=pe(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)}},Br=(e,t)=>{if(!e.keySampleIndices)return Cr(e,t);if(e.presentationTimestamps){const i=pe(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!==me(e.keySampleIndices,i,e=>e))return i}return-1}{const i=Cr(e,t),r=pe(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Er=(e,t)=>{const i=pe(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=pe(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),n=e.sampleCompositionTimeOffsets[s];n&&t-n.startIndexe.startSampleIndex),l=e.sampleToChunk[c];j(l);const u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),h=e.chunkOffsets[u],d=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk;let f=0,m=h;if(1===e.sampleSizes.length)m+=o*(t-d),f+=o*l.samplesPerChunk;else for(let g=d;ge)}},_r=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=pe(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Rr=(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},Fr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Ar=e=>0===e.sampleSizes.length,Mr=e=>{var t;return e.currentFragmentState?(t=e.currentFragmentState).encryptionAuxInfo??(t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):e.encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},Dr=async(e,t,i)=>{if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{j(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[o],r=new Uint8Array(16);s>0?r.set(rc(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=nc(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Or=async(e,t,i,r)=>{j(e.encryptionInfo);const a=e.encryptionInfo;j(null!==a.defaultKid);const s=a.defaultKid;let n;const o=e.demuxer.decryptionKeyCache.get(s);if(o)n=await o;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(s));for(let e=0;e{j(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const a=new Uint8Array(16);a.set(i.iv,0);const s=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),n=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:a,length:64},s,e);return new Uint8Array(t)};if(!i.subsamples)return n(r);j(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Ur(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let c=0;for(const m of o)for(const e of m.perSubsample)c+=e.length;const l=new Uint8Array(c);let u=0;for(const m of o)for(const e of m.perSubsample)l.set(r.subarray(e.offset,e.offset+e.length),u),u+=e.length;const h=await n(l),d=new Uint8Array(r);let f=0;for(const m of o)for(const e of m.perSubsample)d.set(h.subarray(f,f+e.length),e.offset),f+=e.length;return d},zr=(e,t,i,r)=>{const a=new Sr;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,n=t.defaultSkipByteBlock;if(j(null!==s&&null!==n),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{const r=[],a=0!==t||0!==i;let s=0;for(const n of e){s+=n.clearLen;const e=[];if(a){let r=n.protectedLen,a=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:a,length:s}),a+=s,r-=s;const n=Math.min(16*i,r);a+=n,r-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;r.push({perSubsample:e})}return r};var qr,Wr;(Wr=qr||(qr={}))[Wr.EBML=440786851]="EBML",Wr[Wr.EBMLVersion=17030]="EBMLVersion",Wr[Wr.EBMLReadVersion=17143]="EBMLReadVersion",Wr[Wr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Wr[Wr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Wr[Wr.DocType=17026]="DocType",Wr[Wr.DocTypeVersion=17031]="DocTypeVersion",Wr[Wr.DocTypeReadVersion=17029]="DocTypeReadVersion",Wr[Wr.Void=236]="Void",Wr[Wr.Segment=408125543]="Segment",Wr[Wr.SeekHead=290298740]="SeekHead",Wr[Wr.Seek=19899]="Seek",Wr[Wr.SeekID=21419]="SeekID",Wr[Wr.SeekPosition=21420]="SeekPosition",Wr[Wr.Duration=17545]="Duration",Wr[Wr.Info=357149030]="Info",Wr[Wr.TimestampScale=2807729]="TimestampScale",Wr[Wr.MuxingApp=19840]="MuxingApp",Wr[Wr.WritingApp=22337]="WritingApp",Wr[Wr.Tracks=374648427]="Tracks",Wr[Wr.TrackEntry=174]="TrackEntry",Wr[Wr.TrackNumber=215]="TrackNumber",Wr[Wr.TrackUID=29637]="TrackUID",Wr[Wr.TrackType=131]="TrackType",Wr[Wr.FlagEnabled=185]="FlagEnabled",Wr[Wr.FlagDefault=136]="FlagDefault",Wr[Wr.FlagForced=21930]="FlagForced",Wr[Wr.FlagOriginal=21934]="FlagOriginal",Wr[Wr.FlagHearingImpaired=21931]="FlagHearingImpaired",Wr[Wr.FlagVisualImpaired=21932]="FlagVisualImpaired",Wr[Wr.FlagCommentary=21935]="FlagCommentary",Wr[Wr.FlagLacing=156]="FlagLacing",Wr[Wr.Name=21358]="Name",Wr[Wr.Language=2274716]="Language",Wr[Wr.LanguageBCP47=2274717]="LanguageBCP47",Wr[Wr.CodecID=134]="CodecID",Wr[Wr.CodecPrivate=25506]="CodecPrivate",Wr[Wr.CodecDelay=22186]="CodecDelay",Wr[Wr.SeekPreRoll=22203]="SeekPreRoll",Wr[Wr.DefaultDuration=2352003]="DefaultDuration",Wr[Wr.Video=224]="Video",Wr[Wr.PixelWidth=176]="PixelWidth",Wr[Wr.PixelHeight=186]="PixelHeight",Wr[Wr.DisplayWidth=21680]="DisplayWidth",Wr[Wr.DisplayHeight=21690]="DisplayHeight",Wr[Wr.DisplayUnit=21682]="DisplayUnit",Wr[Wr.AlphaMode=21440]="AlphaMode",Wr[Wr.Audio=225]="Audio",Wr[Wr.SamplingFrequency=181]="SamplingFrequency",Wr[Wr.Channels=159]="Channels",Wr[Wr.BitDepth=25188]="BitDepth",Wr[Wr.SimpleBlock=163]="SimpleBlock",Wr[Wr.BlockGroup=160]="BlockGroup",Wr[Wr.Block=161]="Block",Wr[Wr.BlockAdditions=30113]="BlockAdditions",Wr[Wr.BlockMore=166]="BlockMore",Wr[Wr.BlockAdditional=165]="BlockAdditional",Wr[Wr.BlockAddID=238]="BlockAddID",Wr[Wr.BlockDuration=155]="BlockDuration",Wr[Wr.ReferenceBlock=251]="ReferenceBlock",Wr[Wr.Cluster=524531317]="Cluster",Wr[Wr.Timestamp=231]="Timestamp",Wr[Wr.Cues=475249515]="Cues",Wr[Wr.CuePoint=187]="CuePoint",Wr[Wr.CueTime=179]="CueTime",Wr[Wr.CueTrackPositions=183]="CueTrackPositions",Wr[Wr.CueTrack=247]="CueTrack",Wr[Wr.CueClusterPosition=241]="CueClusterPosition",Wr[Wr.Colour=21936]="Colour",Wr[Wr.MatrixCoefficients=21937]="MatrixCoefficients",Wr[Wr.TransferCharacteristics=21946]="TransferCharacteristics",Wr[Wr.Primaries=21947]="Primaries",Wr[Wr.Range=21945]="Range",Wr[Wr.Projection=30320]="Projection",Wr[Wr.ProjectionType=30321]="ProjectionType",Wr[Wr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Wr[Wr.Attachments=423732329]="Attachments",Wr[Wr.AttachedFile=24999]="AttachedFile",Wr[Wr.FileDescription=18046]="FileDescription",Wr[Wr.FileName=18030]="FileName",Wr[Wr.FileMediaType=18016]="FileMediaType",Wr[Wr.FileData=18012]="FileData",Wr[Wr.FileUID=18094]="FileUID",Wr[Wr.Chapters=272869232]="Chapters",Wr[Wr.Tags=307544935]="Tags",Wr[Wr.Tag=29555]="Tag",Wr[Wr.Targets=25536]="Targets",Wr[Wr.TargetTypeValue=26826]="TargetTypeValue",Wr[Wr.TargetType=25546]="TargetType",Wr[Wr.TagTrackUID=25541]="TagTrackUID",Wr[Wr.TagEditionUID=25545]="TagEditionUID",Wr[Wr.TagChapterUID=25540]="TagChapterUID",Wr[Wr.TagAttachmentUID=25542]="TagAttachmentUID",Wr[Wr.SimpleTag=26568]="SimpleTag",Wr[Wr.TagName=17827]="TagName",Wr[Wr.TagLanguage=17530]="TagLanguage",Wr[Wr.TagString=17543]="TagString",Wr[Wr.TagBinary=17541]="TagBinary",Wr[Wr.ContentEncodings=28032]="ContentEncodings",Wr[Wr.ContentEncoding=25152]="ContentEncoding",Wr[Wr.ContentEncodingOrder=20529]="ContentEncodingOrder",Wr[Wr.ContentEncodingScope=20530]="ContentEncodingScope",Wr[Wr.ContentCompression=20532]="ContentCompression",Wr[Wr.ContentCompAlgo=16980]="ContentCompAlgo",Wr[Wr.ContentCompSettings=16981]="ContentCompSettings",Wr[Wr.ContentEncryption=20533]="ContentEncryption";const Hr=[qr.EBML,qr.Segment],Vr=[qr.SeekHead,qr.Info,qr.Cluster,qr.Tracks,qr.Cues,qr.Attachments,qr.Chapters,qr.Tags],jr=[...Hr,...Vr],Kr=16,Xr=e=>{if(e.remainingLength<1)return null;const t=ac(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=ac(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=Xr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===ac(e))return;e.skip(-1);const t=$r(e);return null===t?null:72057594037927940!==t?t:void 0},Jr=e=>{j(e.remainingLength>=2);const t=Qr(e);if(null===t)return null;const i=Yr(e);return null===i?null:{id:t,size:i}},Zr=(e,t)=>{const i=rc(e,t);let r=0;for(;r{const i=rc(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?kc(e):yc(e)},ia=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},ra=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;se.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,Kr);if(Xe(t)&&(t=await t),!t)break;const i=Jr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===qr.EBML){ya(a);let e=this.reader.requestSlice(s,a);if(Xe(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===qr.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===qr.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await ia(this.reader,s,jr,this.reader.fileSize)).pos-s}const e=X(this.segments);e&&(e.elementEndPos=s+a)}ya(a),e=s+a}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;null===this.currentSegment.elementEndPos||ie.id===a);if(-1!==o){const e=Ia[o].flag;this.currentSegment[e]=!0,ya(s);let t=this.reader.requestSlice(n,s);Xe(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===qr.Tags||a===qr.Attachments){a===qr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ya(s);let e=this.reader.requestSlice(n,s);Xe(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===qr.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Ia.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,Kr);if(Xe(i)&&(i=await i),!i)continue;const r=Jr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;ya(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);Xe(o)&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const n of this.currentSegment.tracks)null!==n.defaultDurationNs&&(n.defaultDuration=this.currentSegment.timestampFactor*n.defaultDurationNs/1e9);const r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const n of this.currentSegment.cuePoints){const e=r.get(n.trackId);e&&e.cuePoints.push(n)}for(const n of this.currentSegment.tracks){n.cuePoints.sort((e,t)=>e.time-t.time);for(let e=0;es&&(s=n.cuePoints.length,a=n);for(const n of this.currentSegment.tracks)0===n.cuePoints.length&&(n.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,2,Kr);Xe(i)&&(i=await i),j(i);const r=e,a=Jr(i);j(a);j(a.id===qr.Cluster);let s=a.size;const n=i.filePos;if(void 0===s){s=(await ia(this.reader,n,jr,t.elementEndPos)).pos-n}let o=this.reader.requestSlice(n,s);Xe(o)&&(o=await o);const c={segment:t,elementStartPos:r,elementEndPos:n+s,dataStartPos:n,timestamp:-1,trackData:new Map};if(this.currentCluster=c,o){const e=this.readContiguousElements(o,jr);c.elementEndPos=e}for(const[,l]of c.trackData){const e=l.track;j(l.blocks.length>0);let t=!1;for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const i=l.blocks[l.presentationTimestamps[0].blockIndex],a=l.blocks[X(l.presentationTimestamps).blockIndex];l.startTimestamp=i.timestamp,l.endTimestamp=a.timestamp+a.duration;const s=pe(e.clusterPositionCache,l.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:l.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=Jr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(ya(a),r){case qr.DocType:this.isWebM="webm"===Zr(e,a);break;case qr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case qr.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Gr(e,a)}break;case qr.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Gr(e,a)}break;case qr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Gr(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case qr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=ta(e,a);break;case qr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ht,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,a)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Ta.Block||e.data.algorithm!==va.HeaderStripping)&&(ct._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===aa)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===sa)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===na)this.currentTrack.info.codec="vp8";else if(t===oa)this.currentTrack.info.codec="vp9";else if(t===ca)this.currentTrack.info.codec="av1";else if(t===la){const e=this.currentTrack.codecPrivate?Z.decode(this.currentTrack.codecPrivate):"";Oi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Ea(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===ua?(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===ha?this.currentTrack.info.codec="mp3":t===da?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Wi):t===fa?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ma?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===pa?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ga?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ka?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new _a(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case qr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Gr(e,a);break;case qr.TrackType:{if(!this.currentTrack)break;const t=Gr(e,a);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...ce},alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case qr.FlagEnabled:if(!this.currentTrack)break;Gr(e,a)||(this.currentTrack=null);break;case qr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Gr(e,a);break;case qr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Gr(e,a);break;case qr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Gr(e,a);break;case qr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Gr(e,a);break;case qr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Gr(e,a);break;case qr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Gr(e,a);break;case qr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Zr(e,a);break;case qr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=rc(e,a);break;case qr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Gr(e,a);break;case qr.Name:if(!this.currentTrack)break;this.currentTrack.name=ea(e,a);break;case qr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Zr(e,a),Ae(this.currentTrack.languageCode)||(this.currentTrack.languageCode=xe);break;case qr.LanguageBCP47:{if(!this.currentTrack)break;const t=Zr(e,a).split("-")[0];this.currentTrack.languageCode=t||xe,this.currentTrack.hasLanguageBcp47=!0}break;case qr.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Gr(e,a);break;case qr.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Gr(e,a);break;case qr.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Gr(e,a);break;case qr.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Gr(e,a);break;case qr.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Gr(e,a);break;case qr.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Gr(e,a);break;case qr.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ne[t];this.currentTrack.info.colorSpace.matrix=i}break;case qr.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case qr.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ae[t];this.currentTrack.info.colorSpace.transfer=i}break;case qr.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ie[t];this.currentTrack.info.colorSpace.primaries=i}break;case qr.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-ta(e,a);try{this.currentTrack.info.rotation=K(t)}catch{}}break;case qr.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=ta(e,a);break;case qr.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Gr(e,a);break;case qr.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Gr(e,a);break;case qr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case qr.CueTime:this.currentCueTime=Gr(e,a);break;case qr.CueTrackPositions:{if(null===this.currentCueTime)break;j(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case qr.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Gr(e,a)}break;case qr.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;j(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Gr(e,a)}break;case qr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Gr(e,a);break;case qr.SimpleBlock:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=rc(e,a-(e.filePos-s)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case qr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case qr.Block:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e)>>1&3,o=rc(e,a-(e.filePos-s)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case qr.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case qr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case qr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=rc(e,a);break;case qr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Gr(e,a);break;case qr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Gr(e,a);break;case qr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case qr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case qr.Targets:this.readContiguousElements(e.slice(s,a));break;case qr.TargetTypeValue:50!==Gr(e,a)&&(this.currentTagTargetIsMovie=!1);break;case qr.TagTrackUID:case qr.TagEditionUID:case qr.TagChapterUID:case qr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case qr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case qr.TagName:this.currentSimpleTagName=ea(e,a);break;case qr.TagString:{if(!this.currentSimpleTagName)break;const t=ea(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.TagBinary:{if(!this.currentSimpleTagName)break;const t=rc(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new ut(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case qr.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;rt.order-e.order);break;case qr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ta.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case qr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Gr(e,a);break;case qr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Gr(e,a);break;case qr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:va.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case qr.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Gr(e,a);break;case qr.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=rc(e,a);break;case qr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){j(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(j(r.data),"decompress"===r.data.type)if(r.data.algorithm===va.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var i;if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??(r.raw={}),(i=r.raw)[e]??(i[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":r.title??(r.title=t);break;case"description":r.description??(r.description=t);break;case"artist":r.artist??(r.artist=t);break;case"album":r.album??(r.album=t);break;case"album_artist":r.albumArtist??(r.albumArtist=t);break;case"genre":r.genre??(r.genre=t);break;case"comment":r.comment??(r.comment=t);break;case"lyrics":r.lyrics??(r.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??(r.date=e))}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??(r.trackNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??(r.tracksTotal=a))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??(r.discNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??(r.discsTotal=a))}}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){j(r.trackBacking);const e=await r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=t??0,i}}class Ba{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ce(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=pe(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=we(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 j(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(-1===t)return null;const r=e.trackData.get(this.internalTrack.id).blocks[t];if(j(r),r.decoded||(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),r.decoded=!0),!r.postProcessed){if("prores"===this.internalTrack.info?.codec){if(!(r.data.length>=8&&105===r.data[4]&&99===r.data[5]&&112===r.data[6]&&102===r.data[7])){const e=new Uint8Array(r.data.length+8);J(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(r.data,8),r.data=e}}r.postProcessed=!0}const a=i.metadataOnly?rr:r.data,s=r.timestamp/this.internalTrack.segment.timestampFactor,n=r.duration/this.internalTrack.segment.timestampFactor,o={};r.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(o.alpha=i.metadataOnly?rr:r.mainAdditional,o.alphaByteLength=r.mainAdditional.byteLength);const c=new ar(a,r.isKeyFrame?"key":"delta",s,n,e.dataStartPos+t,r.data.byteLength,o);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,i,r,a){const{demuxer:s,segment:n}=this.internalTrack;let o=null,c=null,l=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(c=e,l=i)}const u=pe(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==u?this.internalTrack.cuePoints[u]:null,d=pe(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),f=-1!==d?this.internalTrack.clusterPositionCache[d]:null,m=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let p;for(e?null===m||e.elementStartPos>=m?(p=e.elementEndPos,o=e):p=m:p=m??n.clusterSeekStartPos;null===n.elementEndPos||p<=n.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,2,Kr);if(Xe(e)&&(e=await e),!e)break;const i=p,u=Jr(e);if(!u||!Vr.includes(u.id)&&u.id!==qr.Void){const e=await ra(s.reader,i,Vr,Math.min(n.elementEndPos??1/0,i+xa));if(e){p=e;continue}break}const h=u.id;let d=u.size;const f=e.filePos;if(h===qr.Cluster){o=await s.readCluster(i,n),d=o.elementEndPos-f;const{blockIndex:e,correctBlockFound:r}=t(o);if(r)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,l=e)}if(void 0===d){j(h!==qr.Cluster);d=(await ia(s.reader,f,jr,n.elementEndPos)).pos-f}const m=f+d;if(null===n.elementEndPos){let e=s.reader.requestSliceRange(m,2,Kr);if(Xe(e)&&(e=await e),!e)break;if(Qr(e)===qr.Segment){n.elementEndPos=m;break}}p=m}if(h&&(!c||c.elementStartPos{var e,t,i,r;let a=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(a=await this.getFirstPacket({}));const s={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&a?Ft(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?Wt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?ei(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?ii(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?ri(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(s);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const n={codec:zi(s),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})()):null}}class _a extends Ba{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Ra=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=uc(s),n=null!==e.fileSize?e.fileSize-a:null,o=Yi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&tr(o.header.channel)===tr(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Fa extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Aa(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Ra(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Qi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Xe(r)&&(r=await r),r){const a=uc(r);if(a===$i||a===Gi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Xe(t)&&(t=await t),t){const e=rc(t,12),i=J(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Zi.FrameCount?i.getUint32(4,!1):null,fileSize:r&Zi.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(Xe(a)&&(a=await a),!a)break;Rc(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Ic){let e=this.reader.requestSlice(this.reader.fileSize-Ic,Ic);Xe(e)&&(e=await e),j(e);"TAG"===bc(e,3)&&Bc(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Aa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(j(null!==e.firstFrameHeader),j(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,a=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(a<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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>>0&4294967295}const Na=e=>{const t=J(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let a=0;a>>24^t])>>>0}return t.setUint32(22,i,!0),r},Oa=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){j(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,n=(e[0]&s)>>1;if(n>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const c=t.vorbisInfo.modeBlockflags[n];if(a=t.vorbisInfo.blocksizes[c],1===c){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+a>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:ai[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},La=27,za=282,Ua=e=>{const t=e.filePos;if(hc(e)!==Ma)return null;e.skip(1);const i=ac(e),r=gc(e),a=hc(e),s=hc(e),n=hc(e),o=ac(e),c=new Uint8Array(o);for(let h=0;he+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},qa=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Ma)return!0;e.skip(1)}}return!1};class Wa extends ir{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,La,za);if(Xe(t)&&(t=await t),!t)break;const i=Ua(t);if(!i)break;if(!!!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const e=await this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?await this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&await this.readOpusMetadata(e,t),null!==t.codecInfo.codec&&this.trackBackings.push(new Ha(t,this)))}})())}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=await this.findNextPacketStart(r),!i)return;const a=await this.readPacket(i.startPage,i.startSegmentIndex);if(!a)return;if(3!==r.data[0]||5!==a.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const c=J(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&l),1<<(l>>4)],modeBlockflags:si(a.data).modeBlockflags},li(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const a=(e=>{const t=J(e),i=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}})(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=Wi,t.codecInfo.opusInfo={preSkip:a.preSkip},li(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){j(te+t.length,0);if(0===o)return null;const c=new Uint8Array(o);let l=0;for(let u=0;u{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Ha{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ue,this.internalSampleRate="opus"===e.codecInfo.codec?Wi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return j(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return j(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(j(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=Oa(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new ar(i.metadataOnly?rr:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),s}async getFirstPacket(e){j(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(j(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=await this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const a=i.timestampInSamples+i.durationInSamples,s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const i=Ce(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;j(this.bitstream.lastMetadataPacket);const r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let a=r.startPage,s=this.demuxer.reader.fileSize;const n=[a];e:for(;a.headerStartPos+a.totalSizei?s=l.headerStartPos:(a=l,n.push(l));continue e}r=l.headerStartPos+l.totalSize}}let o=r.startPage;for(const k of n){if(k.granulePosition===a.granulePosition)break;(!o||k.headerStartPos>o.headerStartPos)&&(o=k)}let c=o;const l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,La,za);Xe(t)&&(t=await t),j(t);const i=Ua(t);j(i),c=i,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}j(-1!==c.granulePosition);let u,h,d=null,f=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{u=0,h=!1;for(let t=c.lacingValues.length-1;t>=0;t--){if(c.lacingValues[t]<255){d=t+1;break}}if(null===d)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const e={data:rr,endPage:f,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){const e=ja(l,c,d);j(e);const t=Va(l,e.page,e.segmentIndex);t&&(c=t.page,d=t.segmentIndex)}else for(;;){const e=ja(l,c,d);if(!e)break;const t=Va(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,d=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,m=e.segmentIndex;break}}}let p=null,g=null;for(;null!==c;){j(null!==d);const e=await this.demuxer.readPacket(c,d);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&di||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,d=a.startSegmentIndex}return p}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=Ce(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=pe(this.sequentialScanCache,i,e=>e.timestampInSamples);let a;if(-1!==r){const e=this.sequentialScanCache[r];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let s=0;for(;a&&a.timestampe)break;if(a=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(a);j(e),this.sequentialScanCache.length>0&&j(X(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Va=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}j(-1===a);if(!(1&r.headerType)){a=0;break}const t=be(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=be(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);Xe(e)&&(e=await e),j(e);const t=bc(e,4),i="RIFX"!==t,r="RF64"===t,a=lc(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==bc(e,4))throw new Error("Invalid WAVE file - wrong format");let n=0,o=null,c=e.filePos;for(;null===s||c=18&&357!==a){const e=sc(r,i),s=t-18;if(Math.min(s,e)>=22&&a===Ka.EXTENSIBLE){r.skip(6);const e=rc(r,16);a=e[0]|e[1]<<8}}if(a!==Ka.MULAW&&a!==Ka.ALAW||(c=8),a!==Ka.PCM&&a!==Ka.IEEE_FLOAT&&a!==Ka.ALAW&&a!==Ka.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===Ka.PCM&&![8,16,24,32].includes(c))throw new Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(a===Ka.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,h,d,f;let m=this.reader.requestSlice(e,t);if(Xe(m)&&(m=await m),!m)return;const p=bc(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=bc(m,4),t=lc(m,i),p=rc(m,t);let k=0;for(let i=0;i0&&((c=this.metadataTags).trackNumber??(c.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((l=this.metadataTags).tracksTotal??(l.tracksTotal=i))}break;case"ICRD":case"IDIT":{const e=new Date(y);Number.isNaN(e.getTime())||((u=this.metadataTags).date??(u.date=e))}break;case"YEAR":{const e=Number.parseInt(y,10);Number.isInteger(e)&&e>0&&((h=this.metadataTags).date??(h.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(d=this.metadataTags).genre??(d.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(Xe(i)&&(i=await i),!i)return;const r=_c(i);if(r){const a=t-xc;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+xc,r.size);Rc(t,r,this.metadataTags)}}}getCodec(){if(j(this.audioInfo),this.audioInfo.format===Ka.MULAW)return"ulaw";if(this.audioInfo.format===Ka.ALAW)return"alaw";if(this.audioInfo.format===Ka.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===Ka.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}j(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Ga=2048;class Qa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(j(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht}}async getPacketAtIndex(e,t){j(e>=0),j(this.demuxer.audioInfo);const i=e*Ga*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(Ga*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(Xe(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=rr;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Xe(e)&&(e=await e),j(e),a=rc(e,r)}const s=e*Ga/this.demuxer.audioInfo.sampleRate,n=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new ar(a,"key",s,n,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){j(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ga,(this.demuxer.dataSize-1)/(Ga*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=await this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;j(null===this.demuxer.reader.fileSize);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){const e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){j(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ga);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ya=e=>{const t=e.filePos,i=rc(e,9),r=new dt(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const a=r.readBits(1),s=r.readBits(2)+1,n=r.readBits(4);if(15===n)return null;r.skipBits(1);const o=r.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const c=r.readBits(13);r.skipBits(11);const l=r.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===a?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:n,channelConfiguration:o,frameLength:c,numberOfAacFrames:l,crcCheck:u,startPos:t}},Ja=1024;class Za extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();j(this.firstFrameHeader),this.trackBackings=[new es(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ya(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=ft[t.samplingFrequencyIndex];j(void 0!==i);const r=Ja/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=Ja,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,xc);if(Xe(t)&&(t=await t),!t)break;const i=_c(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Xe(r)&&(r=await r),!r)break;Rc(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class es{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Ja}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getCodec(){return"aac"}getInternalCodecId(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){j(this.demuxer.firstFrameHeader);const e=mt[this.demuxer.firstFrameHeader.channelConfiguration];return j(void 0!==e),e}getSampleRate(){j(this.demuxer.firstFrameHeader);const e=ft[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return j(void 0!==e),e}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.dataSize)}return new ar(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=me(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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{var e;let t=0;for(;;){let e=this.reader.requestSlice(t,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=_c(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Xe(r)&&(r=await r),j(r),Rc(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:s.end-e,isLastFrame:!0};if(255===ac(s)){const t=s.filePos;if(ac(s)!==(1===this.blockingBit?249:248)){s.filePos=t;continue}s.skip(-2);const i=s.filePos-e,r=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!r){s.filePos=t;continue}if(0===this.blockingBit){if(r.num-n.num!==1){s.filePos=t;continue}}else if(r.num-n.num!==n.blockSize){s.filePos=t;continue}return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=rc(e,4),a=new dt(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){j(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){j(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");j(!t);if(0!==a.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(a.readBits(4));if(!s)return null;j(this.audioInfo);const n=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(a.readBits(4),this.audioInfo.sampleRate);if(!n)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const o=(e=>{let t=0;const i=new dt(rc(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new dt(rc(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?nc(e)+1:"uncommon-u8"===t?ac(e)+1:"number"===typeof t?t:(Te(t),void j(!1)))(e,s),l=((e,t)=>"uncommon-u16"===t?nc(e):"uncommon-u16-10"===t?10*nc(e):"uncommon-u8"===t?ac(e):"number"===typeof t?t:null)(e,n);if(null===l)return null;if(l!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,h=ac(e);e.skip(-u),e.skip(-1);const d=(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})(rc(e,u));return h!==d?null:{num:o,blockSize:c,sampleRate:l}}async advanceReader(){await this.readMetadata(),j(null!==this.lastLoadedPos),j(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class is{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return xe}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(j(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){await this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],a=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.byteSize)}j(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new ar(r,"key",a,s,e,i.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const rs=9e4,as=2**33,ss=188,ns="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.",os=new Set([133,134,162]),cs=new Set;class ls extends ir{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,205);Xe(e)&&(e=await e),j(e);const t=rc(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ss;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,r=null,a=!1,s=!1;for(;;){const e=await this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){i+=this.packetStride;continue}const t=await this.readSection(i,!0,!s);if(!t)break;const n=3,o=32;let c=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i);c=2===e.readBits(8)}}if(0!==t.pid||a)if(t.pid!==r&&!c||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=hs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(await this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const r=new gs(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,await r.markNextPacket(),"avc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=Ft(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];j(t);const i=Nt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const a=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;a>0&&s>0&&(a>s?(e.info.squarePixelWidth=Math.round(e.info.width*a/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/a))),e.info.colorSpace={primaries:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[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=Wt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===St.SPS_NUT).nalUnits[0];j(t);const i=qt(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:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:zi({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await r.markNextPacket(),!r.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=tc.tempFromBytes(r.suppliedPacket.data),i=Ya(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=mt[i.channelConfiguration],e.info.sampleRate=ft[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=uc(tc.tempFromBytes(r.suppliedPacket.data)),i=Yi(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=tr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=hi(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=ui[t.acmod]+t.lfeon,e.info.sampleRate=yt[t.fscod]}else if("eac3"===e.info.codec){const t=mi(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=pi(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=gi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ii(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:qi({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const a=e.readBits(10),c=e.pos+8*a;let l=!1;for(;e.pos=4){const t=e.readBits(32);l||(l=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=c;8*(r+n)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),a=e.pos+8*r;let s=!1,n=!1,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let c=null;const u=l&&os.has(t)?130:t;switch(u){case 27:case 36:c={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",c={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:n?c={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?c={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(c={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:cs.has(t)||(ct._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),cs.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}s=!0}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+n)-e.pos>o;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==r)throw new Error("Only files with a single program are supported.");r=i}}if(null===r)throw new Error("Program Association Table must link to a Program Map Table.");a=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!a)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const n of this.elementaryStreams)n.initialized&&("video"===n.info.type?this.trackBackingEntries.push(new fs(n)):this.trackBackingEntries.push(new ms(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),h=!!(1&e.adaptationFieldControl);let d=0;if(n&&(d=1+e.body[0],e===c&&d>1&&(u=e.body[1]>>6&1)),h&&(0===d?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(d)),o+=e.body.byteLength-d)),r=a,!t&&o>=64){l=!1;break}if(-1!==me(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=pe(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!c)return null;if(1===s.length)n=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);n=new Uint8Array(e);let t=0;for(const i of s)n.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:c.pid,payload:n,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(Xe(t)&&(t=await t),!t)return null;if(71!==ac(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=nc(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:ac(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,ss);if(Xe(t)&&(t=await t),!t)return null;const i=rc(t,ss);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=as-t?-8589934592:as}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new dt(t.payload);if(1!==r.readBits(24))return null;const a=r.readBits(8);if(r.skipBits(16),188===a||190===a||191===a||240===a||241===a||255===a||242===a||248===a)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let n=null;if(2===s||3===s)n=0,r.skipBits(4),n+=r.readBits(3)*(1<<30),r.skipBits(1),n+=32768*r.readBits(15),r.skipBits(1),n+=r.readBits(15),n=e.normalizeTimestamp(n);else if(i)throw new Error(ns);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},hs=(e,t,i)=>{j(null!==t.endPos);const r=us(e,t,i);if(!r)return null;const a=new dt(t.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const n=a.readBits(8),o=a.pos+8*n;a.pos=o;const c=o/8;j(Number.isInteger(c));const l=t.payload.subarray(c,s>0?6+s:t.payload.byteLength);return{...r,data:l}};class ds{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++,j(r instanceof ds),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 xe}getDisposition(){return{...ht,primary:!1}}getTimeResolution(){return rs}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new ar(i.metadataOnly?rr:e.data,r,e.pts/rs,Math.max(t/rs,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;j(t);const i=hs(this.elementaryStream.demuxer,t,!0);j(i);const r=new gs(this.elementaryStream,i),a=new ks(this,r),s=await a.readNext();if(!s)return null;const n=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(n,a),this.packetSectionStarts.set(n,s.packet.sectionStartPos),n}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const r=await i.readNext();if(!r)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(a,i),this.packetSectionStarts.set(a,r.packet.sectionStartPos),a}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const a=this.elementaryStream.demuxer,s=await a.readSection(r,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n);i=new ks(this,o);const c=e.sequenceNumber;for(;;){const e=await i.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){const r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){const r=Ce(e*rs),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:n}=a,o=this.elementaryStream.pid,c=async(e,t,i)=>{let r=e;for(;re.pts),m=-1!==f?d[f]:null;if(m&&r-m.pts<45e3)h=m.sectionStartPos;else{let e=0;if(null!==s.fileSize){const t=Math.ceil(s.fileSize/n);if(t>1){let i=0,s=t-1;for(e=i;i<=s;){const t=Math.floor((i+s)/2),o=_e(t*n,a.packetStride)+u.sectionStartPos,l=o+n,h=await c(o,l,!1);h?h.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}h=_e(e*n,a.packetStride)+u.sectionStartPos}const p=await c(h,s.fileSize??1/0,!1);let g=p?.pesPacketHeader??null;g||(g=u);const k=this.getReorderSize(),y=async(e,t)=>{const s=await a.readSection(e,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n),c=new ks(this,o);for(;;){if((X(c.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await c.readNextPacket()))break}const l=we(c.presentationOrderPackets,t);if(-1===l)return null;const u=c.presentationOrderPackets[l],h=0===l?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=h;const d=await c.readNext();j(d);const f=this.createEncodedPacket(d.packet,d.duration,i);return this.packetBuffers.set(f,c),this.packetSectionStarts.set(f,d.packet.sectionStartPos),f};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=g.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;g=e,ps(this.elementaryStream,g);break}}}e+=a.packetStride}}e:for(let e=0;e=a.packetOffset;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){g=e;break}}}e-=a.packetStride}}return y(g.sectionStartPos,e=>e.pts<=r)}{let e=h,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let h=null;const d=e<=u.sectionStartPos;let f,m=null;if(d)f=u,m=l;else{const t=await c(e,s.fileSize??1/0,i);f=t?.pesPacketHeader??null,m=t?.section??null}let p=!1,g=0;e:for(;f&&!(null!==t&&f.sectionStartPos>=t);){if(f.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===f.randomAccessIndicator;else{j(m);const t=hs(a,m,!0);j(t);const i=new gs(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(h=f)}if(f.pts>r&&(p=!0),p&&(g++,g>k))break;let e=f.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,i);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){f=e,m=t,ps(this.elementaryStream,f);break}}}e+=a.packetStride}}if(h){let e=h;if(0===g)e:for(let r=0;r=a.packetOffset;){const r=await a.readPacketHeader(t);if(!r)break e;if(r.pid===o&&1===r.payloadUnitStartIndicator){const r=await a.readSection(t,i);if(r){const t=us(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await y(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return j(t),t}if(d)return null;t=e,e=Math.max(_e(e-u.sectionStartPos-n,a.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}}class fs extends ds{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class ms extends ds{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const ps=(e,t)=>{const i=e.referencePesPackets,r=pe(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const a=i[r];if(t.pts<=a.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return j(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=l)break;u=e;const i=o+u;if(u+3>=l){this.seekTo(i);break}const h=c[u+1],d=c[u+2],f=c[u+3];let m=0;if(0===h&&0===d&&1===f?m=4:0===h&&1===d&&(m=3),0===m){u++;continue}const p=i;a??(a=p);const g=u+m,k=g+r,y=6;if(k+("avc"===t?y:1)>l){this.seekTo(i);break}const b=c[g];let w,T,S;if("avc"===t)w=Ct(b),T=w===wt.NON_IDR_SLICE||w===wt.SLICE_DPA||w===wt.IDR,S=w===wt.SEI||w===wt.SPS||w===wt.PPS||w===wt.AUD;else{w=Ut(b);if(((1&b)<<5|c[g+1]>>3)>0){u+=m;continue}T=w<=St.RASL_R||w>=St.BLA_W_LP&&w<=21,S=w>=St.VPS_NUT&&w<=37||w===St.PREFIX_SEI_NUT||w>=41&&w<=44||w>=48&&w<=55}let v=!1;if(T){let e;if("avc"===t){const t=c.subarray(k,k+y),i=$(new dt(t));e=!s||i<=n,n=i}else e=c[k]>>7===1;e&&(s?v=!0:s=!0)}else S&&s&&(v=!0);if(v){const e=p-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=m}if(ea){const e=this.endPos-a;return this.seekTo(a),this.supplyPacket(e,0)}}else{const t=e.info.codec,i=128;for(;;){let r=this.ensureBuffered(i);Xe(r)&&(r=await r);const a=this.currentPos;for(;this.currentPos-a>6,n=63&a[4];if(3===s||n>37){this.seekTo(t+1);continue}const o=di[3*n+s];j(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),Xe(r)&&(r=await r);const c=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,c)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(Xe(r)&&(r=await r),r<5)return;const a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}const s=2*(((7&a[2])<<8|a[3])+1),n=3===a[4]>>6?3:a[4]>>4&3,o=fi[n];this.seekTo(t),r=this.ensureBuffered(s),Xe(r)&&(r=await r);const c=256*o,l=Math.round(c*rs/e.info.sampleRate);return this.supplyPacket(r,l)}if("dts"===t){if(127!==i&&100!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(18);if(Xe(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=Ci(a);let n=s?null:Bi(a);if(!s&&!n){this.seekTo(t+1);continue}if(n&&!n.asset){this.seekTo(t);const e=Math.min(n.frameSize,4096);let i=this.ensureBuffered(e);Xe(i)&&(i=await i),n=Bi(this.readBytes(i))??n}let o=s?s.frameSize:n.frameSize;if(s){let e=4*Math.ceil(s.frameSize/4);for(;;){this.seekTo(t);const i=e+10;let r=this.ensureBuffered(i);if(Xe(r)&&(r=await r),r=0)}async readNext(){if(0===this.decodeOrderPackets.length){if(!(await this.readNextPacket()))return null}await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(j(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(j(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(await this.readNextPacket()))break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const ys="application/vnd.apple.mpegurl",bs="#EXT-X-STREAM-INF:",ws="#EXT-X-I-FRAME-STREAM-INF:",Ts="#EXT-X-MEDIA:",Ss="#EXTINF:",vs="#EXT-X-MAP:",Ps="#EXT-X-KEY:",Is="#EXT-X-MEDIA-SEQUENCE:",xs="#EXT-X-BYTERANGE:",Cs="#EXT-X-PROGRAM-DATE-TIME:",Bs="#EXT-X-TARGETDURATION:",Es="#EXT-X-PLAYLIST-TYPE:",_s=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Rs{constructor(e){this._attributes={};let t="",i="",r=!1,a=!1;for(let s=0;s{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,t,i))}else if("audio"===t.type){const i=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=await t.getTracks();for(const r of i)if("video"===r.type){const t=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,{id:e.length+1,type:"audio"},t))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let r;if(this.firstSegmentFirstTimestamps.has(i))r=this.firstSegmentFirstTimestamps.get(i);else{const e=this.getInputForSegment(i);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(i,r)}if(i===e)return i.timestamp-r;const a=await this.getFirstTimestampForInput(t),s=e.timestamp-i.timestamp,n=a-r-s;return Math.abs(n)<=Math.min(.25,s)?i.timestamp-r:e.timestamp-a}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class As{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var e;if((e=this.segmentedInput).firstSegment??(e.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let t=this.segmentedInput.firstSegment,i=null;for(;t;){const e=this.segmentedInput.getInputForSegment(t);if(i=(await e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,i)break;t=await this.segmentedInput.getNextSegment(t,{})}if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i,this.firstSegment=t})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),j(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){j(e.sequenceNumber>=0),j(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:Ee(e.timestamp+r,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s}async getFirstPacket(e){await this.hydrate(),j(this.firstInputTrack),j(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){const r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,i,t)}if(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait}),!i)break;const r=this.segmentedInput.getInputForSegment(i);t=(await r.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,i){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const a=i?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(a)return this.createAdjustedPacket(a,r.segment,r.track);let s=r.segment;for(;;){const e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),a=(await i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!a){s=e;continue}const n=await a._backing.getFirstPacket(t);return n?this.createAdjustedPacket(n,e,a):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){const a=this.segmentedInput.getInputForSegment(r),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const n=e-await this.segmentedInput.getMediaOffset(r,a),o=i?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(o)return this.createAdjustedPacket(o,r,s);r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null}}class Ms extends As{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Ds extends As{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}Ye();const Ns=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class Os extends st{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Zo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Ns),e=this._getFileSize(),j(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new Zo;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Js(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Ls(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Ls{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;j(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class zs extends Os{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 Os||e instanceof Ls))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof Os?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Xe(t)?t.then(i):i(t)}}const Us=(e,t)=>e.path===t.path;class qs extends zs{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 Os?e.ref():e;return this._root=t,this._rootRequest=null,t};Xe(e)?this._rootRequest=e.then(t):(t(e),j(this._root))}if(this._rootRequest)return this._rootRequest.then(a=>a.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const Ws="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class Hs extends Os{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),Ws?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Qs.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){j(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Ue()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),Ws?.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch{}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return ct._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)},js=new Set;class Ks extends zs{constructor(e,t={}){if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new Ks(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Vs,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...Ne(t.requestInit.headers)},r=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==r&&(i=e[r],delete e[r],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){i??(i=t);const r=new Request(e);r.headers.delete("Range"),this._url=r}}if(null!==i){const e=$s(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:Qs.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:Ie(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const a=this._offset,s=this._sequentialBacking?this._sequentialBacking._read(a+e,a+t):this._orchestrator.read(a+e,a+t,Math.max(a+i,a),a+Math.min(r,this._length??1/0)),n=e=>e?(e.offset-=this._offset,e):null;return Xe(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);r.redirected&&(this.rootPath=r.url);e:if(null===this._orchestrator.fileSize&&(206===r.status||"basic"===r.type&&!r.headers.has("Content-Encoding"))){const t=r.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=r.headers.get("Content-Length");if(i){const t=206===r.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==r.status){if(this._sequentialBacking)return void r.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||js.has(e.origin)||(ct._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),js.add(e.origin))}return void this._transitionToSequentialMode(r.body)}const a=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return i.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let r;try{r=await a.read()}catch(t){if(this._disposed)throw t;const e=this._getRetryDelay(1,t,this._url);if(null!==e){ct._error("Error while reading response stream. Attempting to resume.",t),await at(1e3*e);break}throw t}if(e.aborted)continue;const{done:s,value:n}=r;if(s){if(e.currentPos>=e.targetPos)return void this._orchestrator.onWorkerFinished(e);if(e.strictTarget)break;return void this._orchestrator.onWorkerFinished(e)}this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const a=new ReadableStream({pull:async e=>{for(;;){let s;try{s=await t.read()}catch(a){if(this._disposed)throw a;const e=this._getRetryDelay(1,a,this._url);if(null===e)throw a;ct._error("Error while reading response stream. Attempting to resume.",a),await at(1e3*e);const s=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=s.body.getReader(),r=206===s.status?0:i;continue}if(s.done)return void e.close();let n=s.value;if(r>0){const e=Math.min(r,n.length);r-=e,n=n.subarray(e)}if(0!==n.length)return i+=n.length,void e.enqueue(n)}},cancel:()=>t.cancel()}),s=new Gs(a,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const n=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)n.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)n.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of n){const e=s._read(o.start,o.start+o.bytes.length);Xe(e)?e.then(e=>{e?(j(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(j(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Xs=/^bytes=(\d+)-(\d*)$/,$s=e=>{const t=Xs.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=pe(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let a=e;const s=new Uint8Array(t-e);if(-1!==i)for(let l=i;l=t)break;const r=Math.max(e,i.start);r>a&&this._throwDueToCacheMiss();const n=Math.min(t,i.end);ra&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:c}=ke();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),n}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex0;){const e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new Zo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Qs={fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(Ge(e,t,r,a.targetPos)){const e=a.targetPos-a.startPos,r=Math.ceil((e+1)/i)*i,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,r);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+524288)}}};class Ys{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){j(!this.disposed);const a=this.options.prefetchProfile(e,t,this.workers),s=Math.max(a.start,i),n=Math.min(a.end,this.fileSize??1/0,r);j(s<=e&&t<=n);let o=null;const c=pe(this.cache,e,e=>e.start),l=-1!==c?this.cache[c]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,o={bytes:l.bytes,view:l.view,offset:l.start});const u=pe(this.cache,s,e=>e.start),h=o?null:new Uint8Array(t-e);let d=0,f=s;const m=[];if(-1!==u){for(let i=u;i=n)break;if(r.end<=s)continue;const a=Math.max(s,r.start),o=Math.min(n,r.end);if(j(a<=o),f=h.length&&(o={bytes:h,view:J(h),offset:e}),0===m.length)return j(o),o;const{promise:p,resolve:g,reject:k}=ke(),y=[];for(const w of m){const i=Math.max(e,w.start),r=Math.min(t,w.end);i===w.start&&r===w.end?y.push(w):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&w.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,w.end),i.strictTarget&&(i.strictTarget=e),b&&i.pendingSlices.push(b)):(t++,i={hole:{start:w.start,end:w.end},strictTarget:e,pendingSlices:b?[b]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.hole.end)break;i.hole.end=Math.max(i.hole.end,e.hole.end),i.pendingSlices.push(...e.pendingSlices),i.strictTarget&&(i.strictTarget=e.strictTarget),i.age=Math.min(i.age,e.age),this.queuedReads.splice(t+1,1)}}}return o?p.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(j(h),o=p.then(t=>t&&{bytes:t,view:J(t),offset:e})),o}checkHoleAgainstWorker(e,t,i){if(Ge(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=r),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const t=this.workers.indexOf(e);j(-1!==t),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=pe(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=J(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=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=J(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;ithis._length)return null;const a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return Xe(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var Zs=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},en=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const tn=/^0[xX][0-9a-fA-F]+$/,rn=/^data:.*;base64,/i;class an extends Fs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await at(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new ec(i.source),a=await r.requestEntireFile();j(a),e=wc(a,a.length,{ignore:_s}),i.source instanceof zs&&(this.rootPath=i.source.rootPath)}catch(y){t.error=y,t.hasError=!0}finally{en(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,n=null,o=0,c=null,l=null,u=null,h=null,d=null,f=null,m=!1,p=X(this.segments)??null;const g=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},k=e=>{o=e,p&&(j(null!==p.sequenceNumber),p.sequenceNumber0&&null!==f&&(r=o*f),m=!0);const e=y.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);s=a}else if(y.startsWith(vs)){const e=new Rs(y.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let o=null;if(null!==i&&(o=g(i)),o&&null===o.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!p){const e={path:Ze(this.rootPath,t),offset:o?.offset??0,length:o?.length??null};if("AES-128"===n?.method&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:d}}s=null,null===h?u=null:h=null}else if(y.startsWith(Ps)){const e=new Rs(y.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!tn.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(fr);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=J(t).getUint32(0);r=sr(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(y.startsWith(Is)){const e=y.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);k(t)}else if(y.startsWith(xs)){const e=g(y.slice(17));if(null===e.offset){if(null===u)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=u}h=e,u=e.offset+e.length}else if(y.startsWith(Cs)){if(p)continue;const e=y.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(d===s)continue;if(null===d&&this.segments.length>0){const e=X(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}d=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===y)c=null;else if(y.startsWith(Bs)){const e=y.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,f=t}else{if("#EXT-X-ENDLIST"===y){this.streamHasEnded=!0;break}if(y.startsWith(Es)){"vod"===y.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==y)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0}}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return 0===this.segments.length&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){0===this.segments.length&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=pe(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let r=null;(t.initSegment||t.firstSegment)&&(r=this.getInputForSegment(t.initSegment??t.firstSegment));const a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let i=e.psshBoxes;const{psshBox:r}=t.encryption;return null!==r.keyIds&&!r.keyIds.includes(e.keyId)||i.some(e=>nr(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new Yo({source:new qs(t.location.path,async e=>{j(e.isRoot);const i={...e,isRoot:!1};let r;const a=t.location.offset>0||null!==t.location.length;if(t.encryption&&"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method)if("AES-128"===t.encryption.method){const e=t.encryption;j(e.iv);let s=await this.input._getSourceCached(i);if(a){const e=s.source.slice(t.location.offset,t.location.length??void 0).ref();s.free(),s=e}const n=((e,t,i)=>{let r=!1,a=0;const s=new Sr;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(Xe(o)&&(o=await o),!o||0===o.length)throw new Error("Invalid ciphertext.");const c=o.length;if(c%16!==0)throw new Error("Invalid ciphertext.");const l=65552===c?c-16:c,u=rc(o,l),h=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=h.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new ec(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},Qo),!1),r=new ec(i.source),a=await r.requestSlice(0,fr);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:rc(a,fr),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{en(t)}},()=>{s.free()});r=new Gs(n).ref()}else j(!1);else if(r=await this.input._getSourceCached(i),a){const e=r.source.slice(t.location.offset,t.location.length??void 0).ref();r.free(),r=e}return r}),formats:this.input._formats.filter(e=>!(e instanceof Pn)),initInput:r??void 0,formatOptions:a});s._onFormatDetermined=e=>{if(("SAMPLE-AES"===t.encryption?.method||"SAMPLE-AES-CTR"===t.encryption?.method)&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:s,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=tt(this.inputCache,e=>e.age);j(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class sn extends ir{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{j(this.input._rootSource instanceof zs);const e=await this.input._reader.requestEntireFile();j(e);const t=wc(e,e.length,{ignore:_s}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let u=1;u"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],n=[...new Set(a.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=await Promise.all(r.map(async(e,t)=>{const r=[],o=e.attributes.get("codecs");let c;if(o)c=o.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=await t.getTrackBackings(),r=await Promise.all(i.map(async e=>({track:e,codec:await e.getCodec()})));c=await Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const l=e.attributes.get("video"),u=e.attributes.get("audio"),h=c.some(e=>_i.includes(ji(e))),d=c.some(e=>Fi.includes(ji(e)));if(null!==l&&!h){if(!s.includes(l))throw new Error(`Invalid M3U8 file; variant stream references video group "${l}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===l&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}if(null!==u&&!d){if(!n.includes(u))throw new Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}c=[...new Set(c)];let f=null,m=null;const p=e.attributes.getAsNumber("bandwidth");j(null!==p);const g=e.attributes.getAsNumber("average-bandwidth"),k=e.attributes.get("name");for(const i of c){const o=ji(i);if(null!==o)if(_i.includes(o)){if(null!==f)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");f=i;const n=e.attributes.get("video");if(null===n){const i=e.attributes.get("resolution");let a=null,s=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(a=Number(e[1]),s=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:xe,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:f,pairingMask:1n<0?a:null}})}else{if(!n.includes(s))throw new Error(`Invalid M3U8 file; variant stream references audio group "${s}" which is not defined in any #EXT-X-MEDIA tags.`);for(const i of a){const a=i.attributes.get("group-id"),n=i.attributes.get("type");if(a!==s||"audio"!==n.toLowerCase())continue;const o=i.attributes.get("channels")??e.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;r.push({id:-1,demuxer:this,backingTrack:null,default:ln(i.attributes),autoselect:ln(i.attributes)||un(i.attributes),languageCode:hn(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<0?c:null}})}}}}return r})),c=[],l=e=>{const t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||(t.default=e.default),t.autoselect||(t.autoselect=e.autoselect),t.lineNumber=Math.min(t.lineNumber,e.lineNumber),null!==e.peakBitrate&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),null!==e.averageBitrate&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===xe&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(const u of o)for(const e of u)l(e);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of c)"video"===u.info.type?this.trackBackings.push(new on(u)):this.trackBackings.push(new cn(u));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),j(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 an(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ys}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class nn{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof on){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{j(this instanceof cn);for(const e of i)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...ht,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(){j(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class on extends nn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ji(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class cn extends nn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ji(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const ln=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}".`)},un=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}".`)},hn=e=>{if(null===e)return xe;const t=e.split("-")[0];return t||xe};class dn{constructor(){this._isIsobmff=!1}}class fn extends dn{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return null;t.skip(4);const i=bc(t,4);return"ftyp"!==i&&"styp"!==i?null:bc(t,4)}_createDemuxer(e){return new vr(e)}}class mn extends fn{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(Xe(t)&&(t=await t),!t)return!1;let r=uc(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Xe(t)&&(t=await t),!t)return!1;r=mc(t),a=16}if(r8)return!1;if(Gr(i,r)!==qr.EBML)return!1;const a=Yr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(Xe(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Jr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case qr.EBMLVersion:if(1!==Gr(s,r))return!1;break;case qr.EBMLReadVersion:if(1!==Gr(s,r))return!1;break;case qr.DocType:if(Zr(s,r)!==t)return!1;break;case qr.DocTypeVersion:if(Gr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Ca(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class kn extends gn{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class yn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}const i=await Ra(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=Qi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(Xe(s)&&(s=await s),!s)return!1;const n=uc(s);if(n===$i||n===Gi)return!0;t=i.startPos+i.header.totalSize;const o=await Ra(e._reader,t,t+4);if(!o)return!1;const c=o.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new Fa(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class bn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return!1;const i=bc(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===bc(t,4)}_createDemuxer(e){return new $a(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class wn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return Xe(t)&&(t=await t),!!t&&"OggS"===bc(t,4)}_createDemuxer(e){return new Wa(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Tn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Xe(i)&&(i=await i),!!i&&"fLaC"===bc(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ts(e)}}class Sn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Xe(i)&&(i=await i),!i)return!1;const r=Ya(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Xe(i)&&(i=await i),!i)return!1;const a=Ya(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new Za(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class vn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(Xe(t)&&(t=await t),!t)return!1;const i=rc(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 ls(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Pn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(Xe(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===bc(t,7)))return!1;if(!(e._rootSource instanceof zs))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 sn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return ys}}const In=new mn,xn=new pn,Cn=new gn,Bn=new kn,En=new yn,_n=new bn,Rn=new wn,Fn=new Sn,An=new Tn,Mn=new vn,Dn=new Pn,Nn=[Dn,In,xn,Cn,Bn,_n,Rn,An,En,Fn,Mn],On=[Dn,In,xn,En,Fn,Mn];var Ln=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});Ye();let zn=-1/0,Un=-1/0,qn=null;"undefined"!==typeof FinalizationRegistry&&(qn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-zn>=1e3&&(ct._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."),zn=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Un>=1e3&&(ct._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."),Un=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Wn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Hn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Vn=new Set(Hn);class jn{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(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!Vn.has(t.format))throw new TypeError("init.format must be one of: "+Hn.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&&rt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??to(t.format,t.codedWidth,t.codedHeight);let r=t.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?Y(e):Y(e).slice(),this._layout=i,this.colorSpace=new Qn(r)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==t?.visibleRect&&rt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Qn(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&rt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new jn(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Me),duration:Math.trunc((t.duration??0)*Me)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const a=t.visibleRect??{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(a.width,a.height),n=s.getContext("2d",{alpha:We(),willReadFrequently:!0});if(!n)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");n.drawImage(e,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Qn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Wn))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!Hn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=it({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),qn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return j(null!==this._data),this._data instanceof Wn?new jn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Yn(this._data)?new jn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(j(this._layout),new jn(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new jn(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(qn?.unregister(this),this._data instanceof Wn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Yn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(eo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(e.format??this.format))throw new Error("Cannot get allocation size when format is null.");if(Yn(this._data))return this._data.allocationSize(e);return ro(this,e).allocationSize}async copyTo(e,t={}){if(!le(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(eo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(j(null!==this._data),Yn(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof Wn)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(i,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(r instanceof jn))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(r.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${r.format}' instead.`);return await r.copyTo(e,t)}catch(c){i.error=c,i.hasError=!0}finally{Ln(i)}}}const i=ro(this,t);j(this.format);const r=Y(e);if(r.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=e}else if(this._data instanceof Uint8Array)j(this._layout),j(this._layout.length===a.length),s=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");j(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:Y(t.data),stride:4*this.codedWidth}]}const n=[],o=a.length;for(let l=0;la.byteLength)throw new Error("Source buffer OOB read.");if(c+u>r.byteLength)throw new Error("Destination buffer OOB write.");const i=a.subarray(o,o+u);r.set(i,c),o+=t,c+=e.destinationStride}n.push(h)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const a=[];for(const s of e)i.set(s.data,r),a.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:a[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Yn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(j(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,h=this.displayWidth,d=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,h=r,d=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=h,g=d)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:h,sHeight:d}=this._rotateSourceRegion(l,u,h,d,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,h,d,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Zn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,h=t.crop;h&&(h=Jn(h,s,n));const{sx:d,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],h="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*h,u=a*h,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?Gn(u,h):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,h)):m||f.clearRect(0,0,u,h),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(d,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(d,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(j(null!==this._data),this._data instanceof Wn||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(e){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&Zn(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=K(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=Jn(a,i,r));const s=a?a.width:i,n=a?a.height:r,o=s/n;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/o):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*o):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=n),c=Be(c,e.roundDimensionsTo??1),l=Be(l,e.roundDimensionsTo??1);const u={width:c,height:l,fit:e.fit??"fill",rotation:t,crop:a??{left:0,top:0,width:i,height:r},alpha:e.alpha??"keep"};for(const m of Kn){let e=m(this,u);if(Xe(e)&&(e=await e),null!==e)return e}const{canvas:h,context:d,isNew:f}=Gn(u.width,u.height);return this._drawWithFitAndMipmapping(h,d,{fit:u.fit,rotation:u.rotation,crop:u.crop,targetIsFresh:f,fillBlack:"discard"===u.alpha}),new jn(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Kn=[],Xn=[];let $n=0;const Gn=(e,t)=>{for(const a of Xn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=$n++,{canvas:a.canvas,context:a.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Xn.length>=3&&Xn.splice(tt(Xn,e=>e.age),1),Xn.push({canvas:i,context:r,age:$n++}),{canvas:i,context:r,isNew:!0}};class Qn{constructor(e){if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(te);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(re);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(se);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!==typeof e.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Yn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Jn=(e,t,i)=>{const r=Math.min(e.left,t),a=Math.min(e.top,i),s=Math.min(e.width,t-r),n=Math.min(e.height,i-a);return j(s>=0),j(n>=0),{left:r,top:a,width:s,height:n}},Zn=(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.")},eo=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.")}},to=(e,t,i)=>{const r=io(e),a=[];let s=0;for(const n of r){const e=Math.ceil(t/n.widthDivisor),r=Math.ceil(i/n.heightDivisor),o=e*n.sampleBytes,c=o*r;a.push({offset:s,stride:o}),s+=c}return a},io=e=>{const t=(e,t,i,r,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Te(e),j(!1)}},ro=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=ao(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let n;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");n=t.format}else n=e.format;return no(a,n,s)},ao=(e,t,i,r,a)=>{const s={...e};if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!so(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},so=(e,t)=>{if(null===e)return!0;const i=io(e);for(let r=0;r{const r=io(t),a=r.length;if(void 0!==i&&i.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const n=[],o=[];for(let c=0;c4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(d),s=Math.max(s,d);for(let e=0;e 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(uo(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*uo(this.format);if(i.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const a=uo(t),s=ho(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?r:r*this.numberOfChannels)*a}copyTo(e,t){if(!le(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&&!oo.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:a}=t;let{planeIndex:s}=t,n=this.format;const o=i??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:c-u;if(h>c-u)throw new RangeError("frameCount out of range");const d=uo(o),f=ho(o);if(f&&s>=l)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?h:h*l)*d;if(e.byteLength2&&o!==n)return void go(this._data,p,n,o,l,s,u,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:h,format:o})}catch(S){if("f32-planar"===o)throw S;n="f32-planar"}}const k=fo(n),y=uo(n),b=ho(n);let w;if(this._data instanceof co){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=c*y*(b?1:l);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)w=e(s),s=0;else{w=new Uint8Array(c*y*l);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new lo({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(qn?.unregister(this),this._data instanceof co?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof co?this._createAudioDataFromData():po(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(ho(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const a=Math.min(s,o),c=new Float32Array(i*a);for(let t=0;t0;){const a=Math.min(s,o),l=new Float32Array(i*a);for(let t=0;t{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")}},ho=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},fo=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)}},mo=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,Ie(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,Ie(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,Ie(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},po=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,go=(e,t,i,r,a,s,n,o)=>{const c=fo(i),l=mo(r),u=uo(i),h=uo(r),d=ho(i);if(ho(r))if(d){const r=new ArrayBuffer(o*u),a=J(r);e.copyTo(r,{planeIndex:s,frameOffset:n,frameCount:o,format:i});for(let e=0;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.")},wo=e=>{if(!Je(e))throw new TypeError("timestamp must be a number.")},To=(e,t,i)=>i.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const i=await e.determinePacketType(t);return i&&(t.type=i),t}):t;class So{constructor(e){if(!(e instanceof Oo))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(bo(e),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){bo(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i}async getNextKeyPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,t):i}packets(e,t,i={}){if(void 0!==e&&!(e instanceof ar))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof ar))throw new TypeError("endPacket must be an EncodedPacket.");if(bo(i),this._track.input._disposed)throw new Zo;const r=[];let{promise:a,resolve:s}=ke(),{promise:n,resolve:o}=ke(),c=!1,l=!1,u=null,h=!1;const d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=ke()),await n):(r.push(u),s(),({promise:a,resolve:s}=ke()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{h||(u=e,h=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Zo;if(l)return{value:void 0,done:!0};if(h)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class vo{constructor(e,t){this.onSample=e,this.onError=t}}class Po{mediaSamplesInRange(e=-1/0,t=1/0,i){wo(e),wo(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=ke(),{promise:c,resolve:l}=ke(),u=!1,h=!1,d=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(h=!0),h?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=ke())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!h&&!this._track.input._disposed;){const e=Io(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=ke()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),d||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,h=!0,y(),new Zo;if(d)return{value:void 0,done:!0};if(p)throw d=!0,h=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,h=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:n}=ke(),{promise:o,resolve:c}=ke(),l=!1,u=!1,h=null,d=null,f=!1;const m=e=>{a.push(e),n(),({promise:s,resolve:n}=ke())},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(d=e,f=!0,n())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=async()=>{j(s),j(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:c}=ke()),await o;if(u)break;const r=await e.getNextPacket(t,p);j(r),h.decode(r),t=r}g=-1},y=async()=>{j(h),await h.flush();for(let e=0;e{f||(d=e,f=!0,n())}).finally(()=>{h?.close()});const g=this._track,k=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(g.input._disposed)throw u=!0,k(),new Zo;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),d;if(a.length>0){const e=a.shift();return j(void 0!==e),c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await s}},return:async()=>(u=!0,c(),n(),k(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Io=e=>0===e?40:8;class xo extends vo{constructor(e,t,i,r,a,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=a,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const n=ko.find(e=>e.supports(i,r));if(n)this.customDecoder=new n,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof jn))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();j(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(Ve()){if("avc"===i&&this.decoderConfig.description){const e=Mt(Y(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Nt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Lt(t),this.decoderConfig={...this.decoderConfig,description:At(e)}))}}oe(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(j(this.decoder),Ue()||ge(this.inputTimestamps,e.timestamp,e=>e),Ve()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of xt(e.data,this.decoderConfig)){const r=Ct(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===wt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(a.offset,a.offset+a.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&Y(t.description)[4];return Rt(e,i+1)}return _t(e)})(t,this.decoderConfig);e=new ar(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Jt(e.data,this.decoderConfig);t&&(e=new ar(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new Bo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();j(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();j(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=ni(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of zt(e,this.decoderConfig)){const i=Ut(e[t.offset]);if(i===St.RASL_N||i===St.RASL_R)return!0}return!1}sampleHandler(e){if(Ue()){if(this.sampleQueue.length>0&&e.timestamp>=X(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ge(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();j(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){const i=ke();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){j(this.merger);const i=await this.merger.merge(e,t);r.sample=new jn(i)}else r.sample=new jn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){ye(this.finalSamples,r),this.onError(a)}finally{ye(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Ue()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let Co=null;class Bo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Co){const e=new Blob([`(${Eo.toString()})()`],{type:"application/javascript"});Co=URL.createObjectURL(e)}const e=Ie(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=ke();this.pendingRequests.set(i,r);const a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Eo=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:a,alpha:s}=e.data;i=i.then(async()=>{try{const e=await r(a,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{a.close(),s.close()}})});const r=async(e,t)=>{const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),c=i.includes("P12"),l=r.includes("P10"),u=r.includes("P12");if(l!==o||u!==c)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return await a(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return await s(e,t,i);if("NV12"===i)return await n(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)},a=async(e,t,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=new Uint8Array(4*s);await e.copyTo(n);const c=await o(t,r,a,1);for(let o=0,u=3;o{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=i.includes("P10"),n=i.includes("P12"),c=s||n?2:1;let l,u;i.startsWith("I420")?(l=Math.ceil(r/2),u=Math.ceil(a/2)):i.startsWith("I422")?(l=Math.ceil(r/2),u=a):(l=r,u=a);const h=r*a,d=h*c,f=l*u*c,m=new Uint8Array(d+2*f+h*c);await e.copyTo(m);const p=await o(t,r,a,c),g=d+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,h=s+n,d=s;for(let o=0;o{const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e);const n=t.format;if("RGBA"===n||"BGRA"===n||"RGBX"===n||"BGRX"===n){const t="RGBA"===n||"RGBX"===n?0:2,a=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class Ro extends Po{constructor(e,t={}){if(!(e instanceof Uo))throw new TypeError("videoTrack must be an InputVideoTrack.");_o(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(je("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getRotation();let a=await this._track.getDecoderConfig();const s=await this._track.getTimeResolution();return j(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new xo(e,t,i,a,r,s)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Fo{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Uo))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&&Zn(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&_o(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ro(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[s,n]=i%180===0?[r,a]:[a,r];let o=e.crop;o&&(o=Jn(o,s,n));let[c,l]=o?[o.width,o.height]:[s,n];const u=c/l;void 0!==e.width&&void 0===e.height?(c=e.width,l=Math.round(c/u)):void 0===e.width&&void 0!==e.height?(l=e.height,c=Math.round(l*u)):void 0!==e.width&&void 0!==e.height&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=i,this._crop=o})())}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],a=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||We()});j(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&We()});const n={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e,t){wo(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*Pe(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Pe(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Ao extends vo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const a=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=yo.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 lo))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new lo(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(j(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Mo extends vo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,j(Ri.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=Vi(this.codec);switch(this.inputSampleSize=a,a){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const a=(1<(e=>{let t=0,i=0,r=85^e;128&r&&(r&=-129,t=-1),i=4+((240&r)>>4);let a=0;return a=4!==i?1<e.getUint16(t,s)-32768:"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):j(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Se(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Se(e,t,i)<<8>>8)(e,t,s):j(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-2**31:"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):j(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):j(!1);break;default:Te(a),j(!1)}switch(a){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:Te(a),j(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=J(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(r),s=new DataView(a);for(let l=0;l=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const c=new lo({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Do extends Po{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(je("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getDecoderConfig();return j(i&&r),Ri.includes(r.codec)?new Mo(e,t,r):new Ao(e,t,i,r)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class No{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Do(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){wo(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return Pe(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Pe(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Oo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Uo}isAudioTrack(){return this instanceof qo}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Lo(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Lo(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Lo(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Lo(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return null!==await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Lo(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return Ee((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new So(this);let r=1/0,a=-1/0,s=0,n=0;for await(const o of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-r)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-r)).toPrecision(16)):0}}async isLive(){return null!==await this._backing.getLiveRefreshInterval()}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Oo))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&0n!==(this._backing.getPairingMask()&e._backing.getPairingMask())}async getPairableTracks(e){return this.input.getTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=zo(e));const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Lo=(e,t,i)=>{if(Xe(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},zo=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 Xe(r)?r.then(i):i(r)}:void 0};class Uo extends Oo{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??"prores"===await this._backing.getCodec()}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Lo(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Lo(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Lo(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Lo(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Lo(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:Lo(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Lo(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){const e=await(this._backing.getMetadataDisplayWidth?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(void 0!==e){const t=Lo(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Lo(t,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await(this._backing.getMetadataDisplayHeight?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(void 0!==e){const t=Lo(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Lo(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),ko.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(null===t)return null;const i=await this.getDecoderConfig();return j(i),ni(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!Je(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,r=new So(this),a=[];let s=-1/0,n=0;for await(const I of r.packets(void 0,void 0,{metadataOnly:!0})){if(a.length>=i&&I.timestamp>=s)break;a.push(I.timestamp),s=Math.max(s,I.timestamp),n++}const o=new Float64Array(a.length);for(let I=0;Ie-t),b=k-1>>1,w=k>>1;let T=0,S=0,v=0;for(const I of y)if(v+=f.get(I),0===T&&v>b&&(T=I),v>w){S=I;break}const P=(h/T+h/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:Go(P),minFrameRate:h/p,maxFrameRate:h/m,averageFrameRate:h*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class qo extends Oo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Lo(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Lo(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),yo.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Wo=e=>-(e??-1/0),Ho=e=>-e,Vo=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 Xe(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return Xe(r)?r.then(i):i(r)}:void 0}},jo=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return Xe(r)?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Xe(r)||Xe(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),Ko=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>Xe(e))){const t=await Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!t?.sortBy)return i;const r=i.map(e=>t.sortBy(e)),a=r.some(e=>Xe(e))?await Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{const i=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(i.length,r.length);for(let s=0;se.track)},Xo=(e,t)=>{const i=1e6,r=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let T=1;T0))return null;s[T-1]=t}const n=s.slice();n.sort();let o=n[Math.floor(.05*n.length)];for(let T=0;T<6;T++){let e=0,t=0;for(const a of s){const i=Math.max(1,Math.round(a/o));Math.abs(a-i*o)>=r||(e+=a,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let c=0,l=0,u=0;for(const T of s){const e=Math.max(1,Math.round(T/o));Math.abs(T-e*o)>=r||(c++,l+=T,u+=e)}if(c/s.length<.98)return null;o=l/u;const h=1/Math.min(u,1e3),d=Math.max(Number.EPSILON,o-h),f=o+h,m=t/f,p=t/d,g=t/o;let k=null,y=1/0;for(const T of a){if(Tp)continue;const e=Math.abs(T/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,a=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof dn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Os||e.source instanceof Ls))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Os&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Yo))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Os?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){j(this._rootSource instanceof zs);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){const i=this._sourceCache.find(i=>i.cacheGroup===t&&Us(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Us(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(et(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=tt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);j(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),ye(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);j(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:a}),a.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new ec(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)}throw new Jo})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),j(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Jo)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=await Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e),r=(await Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)}async getTracks(e){e&&(e=Vo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Ko(t,e)}async getVideoTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return Ko(t,e)}async getAudioTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return Ko(t,e)}async getPrimaryVideoTrack(e){e&&(e=Vo(e));const t=jo(e,{sortBy:async e=>[Ho((await e.getDisposition()).default),Ho(await e.hasPairableAudioTrack()),Ho(!(await e.hasOnlyKeyPackets())),Wo(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Vo(e));const t=await this.getPrimaryVideoTrack(),i=jo(e,{sortBy:async e=>[Ho(!t||e.canBePairedWith(t)),Ho((await e.getDisposition()).default),Wo(await e.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new Uo(this,e):new qo(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class Jo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Zo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class ec{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new Zo;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 tc(t,J(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Ns);return Xe(r)?r.then(t=>t?new tc(t.bytes,t.view,t.offset,e,i):null):r?new tc(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Zo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(j(null!==this.fileSizeNonStrict),this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i)));return Xe(r)?r.then(a):a(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(async()=>{const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(Xe(i)&&(i=await i),!i||0===i.length)break;const r=rc(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new tc(i,J(i),0,0,t)})()}}class tc{constructor(e,t,i,r,a){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=a,this.bufferPos=r-i}static tempFromBytes(e){return new tc(e,J(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new tc(this.bytes,this.view,this.offset,e,e+t)}}const ic=(e,t)=>{if(e.filePose.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.`)},rc=(e,t)=>{ic(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},ac=e=>(ic(e,1),e.view.getUint8(e.bufferPos++)),sc=(e,t)=>{ic(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},nc=e=>{ic(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},oc=e=>{ic(e,3);const t=Se(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},cc=e=>{ic(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},lc=(e,t)=>{ic(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},uc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},hc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},dc=e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},fc=(e,t)=>{let i,r;return t?(i=lc(e,!0),r=lc(e,!0)):(r=lc(e,!1),i=lc(e,!1)),4294967296*r+i},mc=e=>4294967296*uc(e)+uc(e),pc=e=>4294967296*dc(e)+uc(e),gc=e=>{const t=hc(e),i=(e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},kc=e=>{ic(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},yc=e=>{ic(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},bc=(e,t)=>{ic(e,t);let i="";for(let r=0;rZ.decode(rc(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Tc,Sc,vc,Pc;(Sc=Tc||(Tc={}))[Sc.Unsynchronisation=128]="Unsynchronisation",Sc[Sc.ExtendedHeader=64]="ExtendedHeader",Sc[Sc.ExperimentalIndicator=32]="ExperimentalIndicator",Sc[Sc.Footer=16]="Footer",(Pc=vc||(vc={}))[Pc.ISO_8859_1=0]="ISO_8859_1",Pc[Pc.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Pc[Pc.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Pc[Pc.UTF_8=3]="UTF_8";const Ic=128,xc=10,Cc=["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"],Bc=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=rc(e,Ic-3)),e.filePos=r;const a=Ec(e,30);a&&(t.title??(t.title=a));const s=Ec(e,30);s&&(t.artist??(t.artist=s));const n=Ec(e,30);n&&(t.album??(t.album=n));const o=Ec(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=rc(e,30);let u;if(0===l[28]&&0!==l[29]){const i=l[29];i>0&&(t.trackNumber??(t.trackNumber=i)),e.skip(-30),u=Ec(e,28),e.skip(2)}else e.skip(-30),u=Ec(e,30);u&&(t.comment??(t.comment=u));const h=ac(e);h{const i=rc(e,t),r=$e(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=bc(e,3),r=ac(e),a=ac(e),s=ac(e),n=uc(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=Ji(n);return s&Tc.Footer&&(o+=xc),{majorVersion:r,revision:a,flags:s,size:o}},Rc=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void ct._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Tc.Footer?t.size-xc:t.size,l=rc(e,c),u=new Fc(t,l);if(t.flags&Tc.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Tc.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let h=!1,d=!1,f=!1;if(3===t.majorVersion?(h=!!(64&e.flags),d=!!(128&e.flags)):4===t.majorVersion&&(h=!!(4&e.flags),d=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&Tc.Unsynchronisation)),h)ct._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(d)ct._warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=l;else{if(f&&u.ununsynchronizeRegion(u.pos,l),i.raw??(i.raw={}),"TXXX"===e.id){const e=(r=i.raw).TXXX??(r.TXXX={}),t=u.readId3V2TextEncoding(),a=u.readId3V2Text(t,l),s=u.readId3V2Text(t,l);e[a]??(e[a]=s)}else"T"===e.id[0]?(a=i.raw)[s=e.id]??(a[s]=u.readId3V2EncodingAndText(l)):(n=i.raw)[o=e.id]??(n[o]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":i.title??(i.title=u.readId3V2EncodingAndText(l));break;case"TIT3":case"TT3":i.description??(i.description=u.readId3V2EncodingAndText(l));break;case"TPE1":case"TP1":i.artist??(i.artist=u.readId3V2EncodingAndText(l));break;case"TALB":case"TAL":i.album??(i.album=u.readId3V2EncodingAndText(l));break;case"TPE2":case"TP2":i.albumArtist??(i.albumArtist=u.readId3V2EncodingAndText(l));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.trackNumber??(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.tracksTotal??(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.discNumber??(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.discsTotal??(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(l);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}i.genre??(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(l),t=new Date(e);Number.isNaN(t.getTime())||(i.date??(i.date=t))}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(l),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.lyrics??(i.lyrics=u.readId3V2Text(e,l))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.comment??(i.comment=u.readId3V2Text(e,l))}break;case"APIC":case"PIC":{const e=u.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=u.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=u.readId3V2Text(e,l);const a=u.readU8(),s=u.readId3V2Text(e,l).trimEnd(),n=l-u.pos;if(n>=0){const e=u.readBytes(n);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===a?"coverFront":4===a?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=l}}};class Fc{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{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:Ji(t);s(e)&&(i=e)}return this.pos=a,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case vc.ISO_8859_1:{let e="";for(let t=0;t0===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=$e(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=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}case vc.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=$e(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 vc.UTF_8:{const e=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ac{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch{i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(a){try{r?.disconnect()}catch(s){console.warn("MediaBunny gain setup cleanup:",s)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),a}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{t?.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Mc{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(a){r=!0,i=a}try{e.disconnect()}catch(a){r||(r=!0,i=a)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const a=function(e,t,i,r){const a=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(a+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(a,r),offset:a=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===a.offset?s.start(a.startAt):s.start(a.startAt,a.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,a.endMediaTime)}catch(n){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw n}}}const Dc=Symbol("cancelled");class Nc{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Dc);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function Oc(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class Lc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}async stopIterator(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),await t}cancel(){this.task?.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}async run(e){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Nc;this.task=r;let a=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!a||this.host.audioIterator===a);try{for(a=t.buffers(this.host.currentTime),this.host.audioIterator=a;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=await r.wait(a.next());if(i===Dc||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if(await r.wait(this.contexts.resume(i))===Dc||!s())return;Oc(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(await r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(await r.delay(50))||!s())return}}catch(n){if(s())throw n}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}}}class zc{constructor(e,h){N(this,u),N(this,t,!1),N(this,i,0),N(this,r),N(this,a),N(this,s),N(this,n,null),N(this,o,null),N(this,c,null),N(this,l),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,O(this,r,new Ac(this)),O(this,a,new Mc(this)),O(this,s,new Lc(this,D(this,r),D(this,a))),O(this,l,h)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){D(this,r).ensure(e)}updateGain(){D(this,r).updateGain()}stopQueuedNodes(){D(this,a).stop()}async stopIterator(){await D(this,s).stopIterator()}handleNoAudioTrack(){D(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){z(this,i)._++;try{this.pause()}finally{O(this,c,null),this.input=null,this.audioSink=null}}async load(e,r){if(D(this,t))return;this.cancelPending();const a=D(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>L(this,u,h).call(this,e,a,r));O(this,c,s);try{await s}finally{D(this,c)===s&&O(this,c,null)}}async runIterator(e){D(this,t)||await D(this,s).run(e)}async play(){if(D(this,t))return;if(D(this,o))return D(this,o);if(!this.paused)return;const e=new Nc;O(this,n,e);const r=D(this,i),a=L(this,u,f).call(this,e,r);O(this,o,a);try{await a}finally{D(this,n)===e&&(O(this,n,null),O(this,o,null))}}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,D(this,n)?.cancel(),O(this,n,null),O(this,o,null),D(this,s).cancel(),this.stopQueuedNodes()}async seek(e){if(D(this,t))return;const i=!this.paused;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext?.currentTime??0,this.latestScheduledEndTime=this.playbackTimeAtStart;const r=++this.asyncId;i&&L(this,u,d).call(this,r)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(D(this,t)||e===this.playbackRate)return;const i=this.currentTime;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=i,this.audioContextStartTime=this.audioContext?.currentTime??0,this.playbackRate=e,this.latestScheduledEndTime=i;const r=++this.asyncId;this.paused||L(this,u,d).call(this,r)}destroy(){if(D(this,t))return;O(this,t,!0),z(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>D(this,r).destroy()])try{t()}catch(a){e.push(a)}if(this.input=null,this.audioSink=null,O(this,c,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,a=new WeakMap,s=new WeakMap,n=new WeakMap,o=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakSet,h=async function({input:e,audioTrack:r,duration:a},s,n){const o=()=>!D(this,t)&&D(this,i)===s;if(o()){this.input=e,this.duration=a;try{const e=r&&null!==r.codec&&await r.canDecode();if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new No(r)}else this.handleNoAudioTrack();o()&&n?.()}catch(c){if(o())throw c}}},d=function(e){this.runIterator(e).catch(i=>{if(!D(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{D(this,l)?D(this,l).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=async function(e,a){const s=()=>!D(this,t)&&!e.cancelled&&D(this,i)===a;try{const t=D(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if(await e.wait(D(this,r).resume(t))===Dc||!s())return}if(D(this,c)){if(await e.wait(D(this,c))===Dc||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,L(this,u,d).call(this,++this.asyncId)}catch(n){if(s())throw n}};const Uc=new WeakMap;async function qc(e,t,i){const{input:r,loadSeq:a}=e;if(!e.media?.isHls||!r||e.destroyed)return;const s={};Uc.set(e,s);const n=()=>!e.destroyed&&e.loadSeq===a&&e.input===r&&Uc.get(e)===s;for(;n();){const a=e.media;if(!a?.isHls)return;let s;try{s=await i(r,a,t,n)}catch(o){if(!n())return;if(e.media===a)throw o;continue}if(!n())return;if(e.media===a){if(s)try{await e.replaceTracks(s)}catch(o){if(n())throw o}return}}}async function Wc(e,t,i,r){const a=await e.getVideoTracks();if(!r())return null;const s="auto"===i?await e.getPrimaryVideoTrack():a.find(e=>e.id===i)??t.videoTrack;if(!r()||!s)return null;let n=t.audioTrack,o=t.audioMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableAudioTrack(),o="auto"),{videoTrack:s,audioTrack:n,videoMode:"auto"===i?"auto":"manual",audioMode:o}}async function Hc(e,t,i,r){const a=await e.getAudioTracks();if(!r())return null;const s="auto"===i?t.videoTrack?await t.videoTrack.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack():a.find(e=>e.id===i)??t.audioTrack;if(!r()||!s)return null;let n=t.videoTrack,o=t.videoMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableVideoTrack(),o="auto"),{videoTrack:n,audioTrack:s,videoMode:o,audioMode:"auto"===i?"auto":"manual"}}async function Vc(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const jc=/\.m3u8(?:$|[?#])/i;function Kc(e){return"string"===typeof e&&jc.test(e)}function Xc(e){const t=function(e){return"string"===typeof e?new Ks(e):e instanceof Blob?new Hs(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Gs(e):e??null}(e);return t?new Yo({source:t,formats:Kc(e)?On:Nn}):null}class $c{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){return this.controller?.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}async wait(e,t){try{await Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,e?.dispose()}cancel(){if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),this.controller?.abort(),this.disposeInput()}}}async function Gc({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),a=t||i,s=Boolean(a&&await a.isLive());let n=Number.NaN;return r.length>0&&(n=await e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==n||s||(n=await e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:n??Number.NaN}function Qc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class Yc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return{...Qc(),source:this.host.loadSeq,complete:Qc()}}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,e?.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,e?.complete.resolve(),e?.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}async runPlay(e){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(await this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,await this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),Oc(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}}seek(e,t){return this.position(async t=>{const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();await Promise.all([i,r])},["seeked"],!1,t)}replace(e,t){return this.position(async i=>{e.duration=await Gc(e),i()&&(this.host.media=e,await Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(await Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))},["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=r??(this.seeking?this.wanted:!this.host.paused),this.cancelPlay();const a=this.seeking,s=this.operation();return this.seeking=s,a?.complete.resolve(),a?.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}async runPosition(e,t,i,r){const a=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!a())return;if(this.host.ended=!1,this.host.seeking=!0,Oc(this.host.events,a,["seeking","waiting"]),!a())return;if(r||this.stop(),!a())return;if(await t(a),!a())return;if(this.host.seeking=!1,e.complete.resolve(),Oc(this.host.events,a,i),!a())return;this.seeking=null,s=this.wanted}catch(n){if(!a())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(n),n}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&await this.play()}}const Jc=new WeakMap,Zc=new WeakMap;function el(e){const t=Zc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>e.value??null);Zc.set(e,i);const r=()=>{Zc.get(e)===i&&Zc.delete(e)};return i.then(r,r),i}function tl(e,t,i,r,a){const s=i?Math.max(.06,r/Math.max(1,a)):0;return i&&e{if(this.image===a&&t()){this.cancel();try{i(a)}catch(e){r(e)}}},a.onerror=()=>{this.image===a&&this.cancel()},a.src=e}}class rl{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}async update(e){const t=this.host.videoIterator;if(!t||!this.ready()||!this.current(e)||this.host.isFetching)return;const i={};this.fetching=i,this.host.isFetching=!0;const r=()=>this.current(e)&&this.host.videoIterator===t;try{for(;r();){const e=await el(t);if(!r()||!e)return;const i=this.host.audioClock?.currentTime;if(void 0===i)return;const a=tl(e.timestamp,i,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==a){if("draw"!==a)return void(this.host.nextFrame=e);this.draw(e)}}}catch(a){if(r())throw a}finally{this.fetching===i&&(this.fetching=null,this.host.isFetching=!1)}}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void Oc(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(Oc(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!D(this,w),e=>L(this,P,E).call(this,e,!0),e=>L(this,P,C).call(this,e)))}async preflight(e,t,i){return async function(e,t,i,r,a=()=>!0){if(r?.aborted||!a())return!1;if(!t||"string"!==typeof e||Kc(e))return!0;try{const t=await fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if(r?.aborted||!a())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!(r?.aborted||!a())&&(console.warn("Preflight check failed:",s),!0)}}(e,this.preflightRange,this.events,t,i)}drawPoster(){if(D(this,b)||!this.poster||this.posterDrawn)return;const e=D(this,m);D(this,T).draw(this.poster,()=>L(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,L(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>L(this,P,C).call(this,e))}async stopIterator(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,await function(e){if(!e)return Promise.resolve();const t=Jc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return Jc.set(e,i),i}(e)}clear(){L(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){z(this,m)._++,z(this,p)._++,this.stop(),L(this,P,B).call(this),D(this,T).cancel(),O(this,w,!1),O(this,g,null),O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null}async load(e,t){if(D(this,b))return;this.cancelPending();const i=D(this,m),r=D(this,p);O(this,w,!0);const a=Promise.resolve().then(()=>L(this,P,_).call(this,e,i,r,t));O(this,g,a);try{await a}finally{D(this,g)===a&&O(this,g,null)}}handleNoVideoTrack(){D(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}async resetIterator(e){if(D(this,b))return;const t=D(this,m),i=++z(this,p)._,r=D(this,g);this.stop(),D(this,T).cancel(),O(this,w,!0);try{r&&await r,await L(this,P,R).call(this,e,t,i)}catch(a){if(L(this,P,I).call(this,t)&&D(this,p)===i)throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}}async updateNextFrame(e){await D(this,S).update(e)}render(){D(this,S).render()}start(e){D(this,S).start(e)}stop(){D(this,S).stop()}async seek(e){await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){D(this,b)||(O(this,b,!0),z(this,m)._++,D(this,S).destroy(),D(this,T).cancel(),L(this,P,B).call(this),this.posterDrawn=!1,O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,w=new WeakMap,T=new WeakMap,S=new WeakMap,v=new WeakMap,P=new WeakSet,I=function(e){return!D(this,b)&&D(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){D(this,b)||(L(this,P,B).call(this),D(this,v)?D(this,v).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){D(this,T).cancel(),t&&this.clear(),L(this,P,x).call(this).drawImage(e.canvas,0,0)},_=async function(e,t,i,r){if(L(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:a,videoTrack:s,duration:n}=e;if(this.input=a,this.duration=n,!s)return this.handleNoVideoTrack(),void r?.();const o=null!==s.codec&&await s.canDecode();if(!L(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void r?.();const c=await s.canBeTransparent();if(!L(this,P,I).call(this,t))return;O(this,k,()=>new Fo(s,{poolSize:2,fit:"contain",alpha:c})),this.videoSink=D(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,r?.(),L(this,P,I).call(this,t)&&await L(this,P,R).call(this,0,t,i)}catch(a){if(L(this,P,I).call(this,t))throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}},R=async function(e,t,i){if(!L(this,P,I).call(this,t)||D(this,p)!==i)return;L(this,P,B).call(this),D(this,k)&&this.videoSink===D(this,y)&&(this.videoSink=D(this,k).call(this));const r=this.videoSink;if(!r||!L(this,P,I).call(this,t))return;O(this,y,r);const a=r.canvases(e);this.videoIterator=a;const s=()=>L(this,P,I).call(this,t)&&D(this,p)===i&&this.videoIterator===a,n=await el(a);if(!s())return;const o=await el(a);s()&&(this.nextFrame=o,n?L(this,P,E).call(this,n,!1):this.drawPoster())};class sl{constructor({canvas:e,ctx:t,events:i,option:r={}}){N(this,F),this.events=i,this.option=r,this.audio=new zc(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new al({canvas:e,ctx:t,events:i,timeupdateInterval:r.timeupdateInterval??250,avSyncTolerance:r.avSyncTolerance??.12,dropLateFrames:r.dropLateFrames??!1,poster:r.poster??"",preflightRange:r.preflightRange??!1,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,O(this,F,new Yc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,D(this,F).ended(),this.audio.pause())})}async load(e){if(this.destroyed)return;const t=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),this.loadSession?.cancel(),t!==this.loadSeq||this.destroyed)return;if(this.pause(),t!==this.loadSeq||this.destroyed)return;this.disposeInput();const i=new $c;this.loadSession=i,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,i.defer(()=>this.events.emit("waiting")),i.defer(()=>this.events.emit("loadstart"));const r=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout??0:0;try{await i.wait(this.performLoad(e,t,i),r)}catch(a){if(t!==this.loadSeq)return;const e=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),i.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}}async performLoad(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(await this.video.preflight(e,i.signal,r))||!r())return;const a=Xc(e);if(!a)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(a);const s=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await Gc({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Kc(t);return{input:e,videoTrack:i,audioTrack:r,duration:a,isLive:!Number.isFinite(a)&&Boolean(s&&await s.isLive()),isHls:n,videoMode:n?"auto":"manual",audioMode:n?"auto":"manual"}}(a,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=a,this.media=s;const n=function(e,t){let i=!1,r=!1,a=!1;function s(s){t()&&!a&&("video"===s?i=!0:r=!0,i&&r&&(a=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,Oc(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,n.video),t=r()?this.audio.load(s,n.audio):Promise.resolve();if(await Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,Oc(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){this.loadSession?.disposeInput(),this.input=null,this.media=null}async replaceTracks(e){if(this.media&&!this.destroyed)return D(this,F).replace({...this.media,...e},this.currentTime)}async selectHlsQuality(e){return function(e,t){return qc(e,t,Wc)}(this,e)}async selectHlsAudio(e){return function(e,t){return qc(e,t,Hc)}(this,e)}async getHlsState(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=await async function(e){if(!e?.isHls||!e.input)return null;const[t,i]=await Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[r,a]=await Promise.all([Promise.all(t.map(async(e,t)=>({id:e.id,track:e,index:t,name:await e.getName(),height:await e.getDisplayHeight(),bitrate:await Vc(e)}))),Promise.all(i.map(async(e,t)=>{const i=await e.getName(),r=await e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:await Vc(e)}}))]);return{levels:r,audios:a,currentLevel:e.videoTrack?r.find(t=>t.id===e.videoTrack?.id)??null:null,currentAudio:e.audioTrack?a.find(t=>t.id===e.audioTrack?.id)??null:null,videoMode:e.videoMode??"auto",audioMode:e.audioMode??"auto"}}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}}async play(){return D(this,F).play()}pause(){D(this,F).pause()}async seek(e){return D(this,F).seek(e)}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,D(this,F).invalidate();const e=[];for(const i of[()=>this.loadSession?.cancel(),()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){return this.media?.duration??this.audio.duration??this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}F=new WeakMap;const nl=new WeakMap;function ol(e){let t=nl.get(e);return t||(t={closed:!1,frames:new Set},nl.set(e,t)),t}class cl{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new V,this.engine=new sl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=r.volume??.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:e.option?.url&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=ol(e);if(i.closed)return 0;const r=requestAnimationFrame(a=>{i.frames.delete(r),i.closed||t(a,{presentationTime:e.engine.currentTime,expectedDisplayTime:a+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:a,receiveTime:a,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){ol(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=ol(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}function ll(e={}){return t=>{const i=t,{createElement:r}=i.constructor.utils,a=r("canvas"),s=new cl({art:i,canvas:a,ctx:a.getContext("2d"),option:e}),n=function(e,t,i,r){let a,s=!1;function n(){s||!e.template?.$player||e.option.autoSize||Object.assign(t.style,{width:"100%",height:"100%",objectFit:"contain"})}function o(){s||(s=!0,U([()=>a?.destroy(),()=>{e.mediabunny===i&&delete e.mediabunny},()=>i.destroy(),()=>e.off?.("resize",n),()=>e.off?.("video:loadedmetadata",n),()=>e.off?.("destroy",o)]))}return{install:function(){e.on("resize",n),e.on("video:loadedmetadata",n),a=H({art:e,shim:i,option:r}),e.on("destroy",o)},destroy:o}}(i,a,s,e);try{i.mediabunny=s,function(e,t){const i=new Map,r=e,a=t;for(const n in e)if("function"===typeof r[n]){const t=r[n];i.set(n,t.bind(e))}const s=new Set([...Object.getOwnPropertyNames(t),...Object.getOwnPropertyNames(Object.getPrototypeOf(t))]);for(const n of s)"constructor"===n||n in e||Object.defineProperty(e,n,{get(){const e=a[n];return"function"===typeof e?e.bind(t):e},set(e){a[n]=e},configurable:!0,enumerable:!0});for(const[n,o]of i)r[n]=(...e)=>o(...e)}(a,s),n.install()}catch(o){try{n.destroy()}catch(c){console.warn("MediaBunny entry setup cleanup:",c)}throw o}return a}}return Object.defineProperty(ll,"default",{value:ll,writable:!0,configurable:!0}),ll}); diff --git a/docs/compiled/artplayer-proxy-mediabunny.legacy.js b/docs/compiled/artplayer-proxy-mediabunny.legacy.js index 81d49c745..d8f8db571 100644 --- a/docs/compiled/artplayer-proxy-mediabunny.legacy.js +++ b/docs/compiled/artplayer-proxy-mediabunny.legacy.js @@ -4,4 +4,4 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A=Object.defineProperty,M=Object.defineProperties,D=Object.getOwnPropertyDescriptors,N=Object.getOwnPropertySymbols,O=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable,z=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),U=e=>{throw TypeError(e)},q=Math.pow,W=(e,t,i)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,H=(e,t)=>{for(var i in t||(t={}))O.call(t,i)&&W(e,i,t[i]);if(N)for(var i of N(t))L.call(t,i)&&W(e,i,t[i]);return e},V=(e,t)=>M(e,D(t)),j=(e,t,i)=>t.has(e)||U("Cannot "+i),K=(e,t,i)=>(j(e,t,"read from private field"),i?i.call(e):t.get(e)),X=(e,t,i)=>t.has(e)?U("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),$=(e,t,i,r)=>(j(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),G=(e,t,i)=>(j(e,t,"access private method"),i),Q=(e,t,i,r)=>({set _(r){$(e,t,r,i)},get _(){return K(e,t,r)}}),Y=(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())}),J=function(e,t){this[0]=e,this[1]=t},Z=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof J,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?n("return"===e?e:"next",t[1]?{done:i.done,value:i.value}:i,r,s):r({value:i,done:l})).catch(e=>n("throw",e,r,s))}catch(c){s(c)}},s=(e,t,i,s)=>a[e]=a=>(t=new Promise((t,i,s)=>(s=()=>n(e,a,t,i),r?r.then(s):s())),s=()=>r===i&&(r=0),r=i=t.then(s,s),t),a={};return i=i.apply(e,t),a[z("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},ee=e=>{var t,i=e[z("asyncIterator")],r=!1,n={};return null==i?(i=e[z("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 J(new Promise(r=>{var n=i[e](t);n instanceof Object||U("Object expected"),r(n)}),1)}}),n[z("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},te=(e,t,i)=>(t=e[z("asyncIterator")])?t.call(e):(e=e[z("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 ie(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function re(e,t,i){const r={control:!1,setting:!1};let n=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function a(){n=null,ie([()=>s("control"),()=>s("setting")])}return{update:function(o,l,c,u){if(!o)return void a();n=o;const d=()=>n===o&&c(),h=e=>Y(null,null,function*(){return d()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html});l.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:h})):s("control"),d()&&(l.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:h})):s("setting"))},clear:a}}function ne(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function se({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,n=0,s=0;const a=re(e,"mediabunny-quality",''),o=re(e,"mediabunny-audio",''),l=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;function c(){return Y(this,null,function*(){var e,s;if(r||t.engine.destroyed)return;const c=++n,d=t.engine.loadSeq,h=()=>c===n&&l(d);try{const r=yield t.getM3u8State();if(!h())return;const n=(null==(e=i.m3u8)?void 0:e.quality)||{},c=function(e,t,i){var r;if(!t.control&&!t.setting||!(null==e?void 0:e.levels.length))return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||`${e.height}P`),a=e.currentLevel?s(e.currentLevel):n,o=[];for(const u of e.levels){if(!i())return null;o.push({html:s(u),value:u.id,default:(null==(r=e.currentLevel)?void 0:r.id)===u.id})}const l=new Map(e.levels.map(e=>[e.id,e.height])),c=ne(o).sort((e,t)=>("auto"===t.value?0:l.get(t.value)||0)-("auto"===e.value?0:l.get(e.value)||0));return c.push({html:n,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:a,selector:c}}(r,n,h);if(!h())return;if(a.update(c,n,()=>l(d),(e,t)=>u("quality",e,t)),!h())return;const f=(null==(s=i.m3u8)?void 0:s.audio)||{},m=function(e,t,i){var r;if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||e.lang||e.language),a=e.currentAudio?s(e.currentAudio):n,o=[];for(const c of e.audios){if(!i())return null;o.push({html:s(c),value:c.id,default:(null==(r=e.currentAudio)?void 0:r.id)===c.id})}const l=ne(o);return l.push({html:n,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:a,selector:l}}(r,f,h);h()&&o.update(m,f,()=>l(d),(e,t)=>u("audio",e,t))}catch(f){if(h())throw f}})}function u(i,r,a){return Y(this,null,function*(){const o=++s,u=t.engine.loadSeq;n++;const h=()=>o===s&&l(u);try{"quality"===i?yield t.switchM3u8Quality(r.value):yield t.switchM3u8Audio(r.value),h()&&(yield c(),h()&&(e.notice.show=`${a}: ${r.html}`))}catch(f){if(h()&&(yield d(),h()))throw f}return r.html})}function d(){return c().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function h(){n++,s++;try{ie([a.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}return e.on("video:loadedmetadata",d),e.on("restart",d),e.on("video:loadstart",h),e.on("video:error",h),e.on("destroy",function t(){if(!r){r=!0,h();try{ie([()=>e.off("video:loadedmetadata",d),()=>e.off("restart",d),()=>e.off("video:loadstart",h),()=>e.off("video:error",h),()=>e.off("destroy",t)])}catch(i){console.warn("MediaBunny HLS listener cleanup:",i)}}}),{update:c}}class ae{constructor(){X(this,e,!1),this.listeners=new Map}addEventListener(t,i){var r;K(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),null==(r=this.listeners.get(t))||r.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){var r;if(K(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{K(this,e)||t(n)})}destroy(){$(this,e,!0),this.listeners.clear()}}function oe(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const le=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},ce=e=>e&&e[e.length-1],ue=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-q(2,r))},he=e=>{const t=ue(e);return 0===(1&t)?-(t>>1):t+1>>1},fe=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),me=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),pe=new TextDecoder,ge=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),ke={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ye=ge(ke),be={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Te=ge(be),ve={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},we=ge(ve),Se=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,Pe={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Ie=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class xe{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return Y(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 Ce=/^[0-9a-fA-F]+$/,Be=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),Ee=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,_e=(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{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},Fe=(e,t,i)=>{const r=Re(e,i(t),i);e.splice(r+1,0,t)},Ae=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},Me=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},De=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},Ne=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Oe=e=>{throw new Error(`Unexpected value: ${e}`)},Le=(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},ze=(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)},Ue=(e,t)=>({next(){return Y(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}}),qe=(e,t,i)=>Math.max(t,Math.min(i,e)),We="und",He=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Ve=(e,t)=>Math.round(e/t)*t,je=(e,t)=>Math.round(e*t)/t,Ke=(e,t)=>Math.floor(e/t)*t,Xe=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},$e=/^[a-z]{3}$/,Ge=e=>$e.test(e),Qe=1e6*(1+Number.EPSILON),Ye=(e,t)=>{const i=H(H({},e),t);if(e.headers||t.headers){const r=e.headers?Je(e.headers):{},n=t.headers?Je(t.headers):{},s=H({},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},Je=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},Ze=(e,t,i,r,n)=>Y(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(Pt._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 Tt(1e3*e)),n())throw a}});class et{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let tt=null;const it=()=>{var e;return null!==tt?tt:tt=!("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 rt=null;const nt=()=>{var e;return null!==rt?rt:rt="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let st=null;const at=()=>{var e;return null!==st?st:st=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},ot=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,lt=Y(null,null,function*(){}).constructor,ct=e=>e instanceof lt||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),ut=(e,t)=>-1!==e?e:t,dt=(e,t,i,r)=>e<=r&&i<=t,ht=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},mt=e=>"number"===typeof e&&!Number.isNaN(e),pt=(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("/")},gt=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{oe(Number.isInteger(e.num)),oe(Number.isInteger(e.den)),oe(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}},bt=(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.`)},Tt=e=>new Promise(t=>setTimeout(t,e));class vt{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)}}}var wt,St;(St=wt||(wt={}))[St.Silent=0]="Silent",St[St.Errors=1]="Errors",St[St.Warnings=2]="Warnings",St[St.Info=3]="Info";class Pt{constructor(){}static get level(){return Pt._level}static set level(e){if(e!==wt.Silent&&e!==wt.Errors&&e!==wt.Warnings&&e!==wt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Pt._level=e}static get _emitter(){var e;return null!=(e=Pt._emitterInstance)?e:Pt._emitterInstance=new vt}static on(e,t,i){return Pt._emitter.on(e,t,i)}static _error(...e){Pt._emitter._emit("error",e),Pt._level>=wt.Errors&&console.error(...e)}static _warn(...e){Pt._emitter._emit("warn",e),Pt._level>=wt.Warnings&&console.warn(...e)}static _info(...e){Pt._emitter._emit("info",e),Pt._level>=wt.Info&&console.info(...e)}}Pt._level=wt.Info,Pt._emitterInstance=null;class It{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 xt{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 Ct={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Bt{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;return this.pos++,n}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}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 Bt(this.bytes);return e.pos=this.pos,e}}const Et=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],_t=[-1,1,2,3,4,5,6,8],Rt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Bt(e),i=Ft(t),{frequencyIndex:r,sampleRate:n}=At(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=_t[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=At(t).sampleRate,o=Ft(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Ft(t)&&t.readBits(1)&&(c=At(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(l=!!t.readBits(1)));break}t.pos=e+1}return null!==a&&a>1&&(l=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:c,outputNumberOfChannels:l&&1===a?2:a}},Ft=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},At=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let n=0;t+3i&&(yield{offset:i,length:t-i}),i=t+n,t=i):t++}-1!==i&&i{if(t.description){const i=3&fe(t.description)[4];return qt(e,i+1)}return Ut(e)},Ht=e=>31&e,Vt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+jt.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(jt,r),r+=jt.byteLength,i.set(n,r),r+=n.byteLength;return i},Xt=(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:ze(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},$t=e=>{try{const t=[],i=[],r=[];for(const o of Ut(e)){const n=e.subarray(o.offset,o.offset+o.length),s=Ht(n[0]);s===Nt.SPS?t.push(n):s===Nt.PPS?i.push(n):s===Nt.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=Jt(n);oe(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 Pt._error("Error building AVC Decoder Configuration Record:",t),null}},Gt=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=me(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{var t;try{const i=Vt(e),r=new Bt(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();ue(r);let o=1,l=0,c=0,u=0;if(100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n){o=ue(r),3===o&&(u=r.readBits(1)),l=ue(r),c=ue(r),r.skipBits(1);if(r.readBits(1))for(let e=0;e<(3!==o?8:12);e++){if(r.readBits(1)){const t=e<6?16:64;let i=8,n=8;for(let e=0;ee.level>=a))?t:ce(Gi),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);P=n,I=n}else P=0,I=0}return oe(null!==I),{emulationUnpreventedBytes:i,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:o,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:k,pixelAspectRatio:S,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:w,numReorderFrames:P,maxDecFrameBuffering:I,vuiParametersFlagBitOffset:B,bitstreamRestrictionFlagBitOffset:x,bitstreamRestrictionFlag:C}}catch(i){return Pt._error("Error parsing AVC SPS:",i),null}},Zt=e=>{const t=ue(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)ue(e),ue(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},ei=e=>{oe(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Bt(e.emulationUnpreventedBytes),r=new Bt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(oe(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),de(r,2),de(r,1),de(r,16),de(r,16),de(r,e.numReorderFrames),de(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return oe(Number.isInteger(n)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,n))},ti=(e,t)=>{if(t.description){const i=3&fe(t.description)[21];return qt(e,i+1)}return Ut(e)},ii=e=>e>>1&63,ri=e=>{try{const t=new Bt(Vt(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}=si(t,i);ue(t);const u=ue(t);let d=0;3===u&&(d=t.readBits(1));const h=ue(t),f=ue(t);let m=h,p=f;if(t.readBits(1)){const e=ue(t),i=ue(t),r=ue(t),n=ue(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=ue(t),k=ue(t);ue(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)ue(t),b=ue(t),ue(t);ue(t),ue(t),ue(t),ue(t),ue(t),ue(t),t.readBits(1)&&t.readBits(1)&&ai(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),ue(t),ue(t),t.skipBits(1));const T=ue(t);if(oi(t,T),t.readBits(1)){const e=ue(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of Ut(e)){const s=e.subarray(l.offset,l.offset+l.length),a=ii(s[0]);a===Lt.VPS_NUT?t.push(s):a===Lt.SPS_NUT?i.push(s):a===Lt.PPS_NUT?r.push(s):a!==Lt.PREFIX_SEI_NUT&&a!==Lt.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=ri(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Bt(Vt(e));t.skipBits(16),ue(t),ue(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),ue(t),ue(t),he(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&ue(t),he(t),he(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:Lt.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Lt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Lt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ii(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 Pt._error("Error building HEVC Decoder Configuration Record:",t),null}},si=(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;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&he(e);for(let t=0;t{const i=[];for(let r=0;r{var n;let s=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){if(t===i){o=t-(ue(e)+1)}else o=t-1;e.readBits(1),ue(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=ue(e),i=ue(e);for(let r=0;r{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=Yt[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)&&(ue(e),ue(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(ue(e),ue(e),ue(e),ue(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&ue(e),e.readBits(1)&&ui(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=ue(e),ue(e),ue(e),ue(e),ue(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},ui=(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?ue(e):i=1===e.readBits(1);let a=1;if(!i){a=ue(e)+1}r&&di(e,a,s),n&&di(e,a,s)}},di=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=hi.audAllowed;for(const s of ti(e,t)){if(r===hi.noMoreDataAllowed){i.add(s.offset);continue}const t=ii(e[s.offset]);if(r===hi.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>hi.audAllowed?n=!0:r=hi.beforeFirstVcl:t<=31?r>hi.afterFirstVcl?n=!0:r=hi.afterFirstVcl:36===t?r!==hi.afterFirstVcl?n=!0:r=hi.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>hi.beforeFirstVcl?n=!0:r=hi.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&fe(t.description)[21];return Xt(e,i+1)}return Kt(e)})(n,t)},pi={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},gi=e=>{var t,i,r;const n=new Bt(e);if(2!==n.readBits(2))return null;const s=n.readBits(1),a=(n.readBits(1)<<1)+s;3===a&&n.skipBits(1);if(1===n.readBits(1))return null;if(0!==n.readBits(1))return null;n.skipBits(2);if(4817730!==n.readBits(24))return null;let o=8;if(a>=2){o=n.readBits(1)?12:10}const l=n.readBits(3);let c=0,u=0;if(7!==l){if(u=n.readBits(1),1===a||3===a){const e=n.readBits(1),t=n.readBits(1);c=e||t?e&&!t?2:1:3,n.skipBits(1)}else c=1}else c=3,u=1;const d=(n.readBits(16)+1)*(n.readBits(16)+1);let h=ce(Qi).level;for(const m of Qi)if(d<=m.maxPictureSize){h=m.level;break}const f=pi[l];return{profile:a,level:h,bitDepth:o,chromaSubsampling:c,videoFullRangeFlag:u,colourPrimaries:null!=(t=null==f?void 0:f.colourPrimaries)?t:2,transferCharacteristics:null!=(i=null==f?void 0:f.transferCharacteristics)?i:2,matrixCoefficients:null!=(r=null==f?void 0:f.matrixCoefficients)?r:2}},ki=function*(e){const t=new Bt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*q(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>q(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);oe(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},yi=e=>{for(const{type:t,data:i}of ki(e)){if(1!==t)continue;const e=new Bt(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{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let n=0;n<=r;n++){e.skipBits(12);const r=e.readBits(5);if(0===n&&(s=r),r>7){const t=e.readBits(1);0===n&&(a=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const 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=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,T=1,v=1,w=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,T=0,v=0):(b=e.readBits(1),0===r?(T=1,v=1):1===r?(T=0,v=0):12===m?(T=e.readBits(1),v=T?e.readBits(1):0):(T=1,v=0),T&&v&&(w=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:w,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},bi=e=>{if(e.length<36)return null;const t=me(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},Ti=[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],vi=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;u97;)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}},wi=(e,t,i)=>{switch(e){case"avc":for(const e of Wt(i,t)){const t=i[e.offset],r=Ht(t);if(r>=Nt.NON_IDR_SLICE&&r<=Nt.SLICE_DPC)return"delta";if(r===Nt.IDR)return"key";if(r===Nt.SEI&&!at()){const t=i.subarray(e.offset,e.offset+e.length),r=Vt(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 Bt(r);e.pos=8*n;const t=ue(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=me(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=pe.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;c0&&(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=ht(c),i=me(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=pe.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})}}}},xi=[2,1,2,3,3,4,4,5],Ci=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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)}},Bi=[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],Ei=[1,2,3,6],_i=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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=Ei[s];let d;d=n<3?Mt[n]/1e3:Dt[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}]}},Ri=e=>{const t=e.substreams[0];return oe(t),t.fscod<3?Mt[t.fscod]:null!==t.fscod2&&t.fscod2<3?Dt[t.fscod2]:null},Fi=e=>{const t=e.substreams[0];oe(t);let i=xi[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},Ai=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Mi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Di=[16,16,20,20,0,24,24,0],Ni=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Oi=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Li=[32e3,44100,48e3,0],zi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ui=[512,1024,2048,4096],qi=e=>{const t=Hi(e),i=me(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Vi(e.subarray(r));if(!t)break;null!=n||(n=t),r+=t.frameSize}if(t)return{frameSize:n?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==n};if(!(null==n?void 0:n.asset))return null;const{asset:s}=n;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Wi=e=>{const t=qi(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},Hi=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new Bt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const n=t.readBits(14)+1;if(n<96)return null;const s=t.readBits(6);if(s>=Ni.length)return null;const a=Ai[t.readBits(4)];if(0===a)return null;const o=Mi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const l=t.readBits(2);if(3===l)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const c=Di[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Ni[s]+(u?1:0),sampleCount:32*r,channelLayout:Oi[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},Vi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new Bt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),n=8+4*r,s=16+4*r;t.skipBits(n);const a=t.readBits(s)+1,o={frameSize:a,asset:null};if(!t.readBits(1))return o;const l=Li[t.readBits(2)],c=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===l||t.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(c*m/l),channelLayout:g,pcmResolution:f}}},ji=e=>Xe(e)+Xe(44646&e),Ki=["avc","hevc","vp9","av1","vp8","prores"],Xi=["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"],$i=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Xi],Gi=[{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}],Qi=[{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}],Yi=".01.01.01.01.00",Ji=".0.110.01.01.01.0",Zi=["ap4x","ap4h","apch","apcn","apcs","apco"],er=["dtsc","dtsh","dtsl","dtse"],tr=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(oe(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${Be(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}.${Be(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=Ee(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=me(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=Ee(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=ce(Qi).level;for(const e of Qi)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(Yi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=ce(Qi).level;for(const e of Qi)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)?ke[r.primaries]:1,u=(null==r?void 0:r.transfer)?be[r.transfer]:1,d=(null==r?void 0:r.matrix)?ve[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(Ji)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&Oe(t),new TypeError(`Unhandled codec '${t}'.`)},ir=e=>{var t,i,r,n,s,a;switch(e.codec){case"avc":{let r=null==(t=e.avcCodecInfo)?void 0:t.sequenceParameterSets[0];if(!r&&e.codecDescription&&(r=null==(i=Qt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=Jt(r);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=me(e);let i=0;const r=t.getUint8(i++),n=t.getUint8(i++),s=n>>6&3,a=n>>5&1,o=31&n,l=t.getUint32(i,!1);i+=4;const c=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,T=k>>2&1,v=3&k,w=t.getUint8(i++),S=[];for(let P=0;P>7&1,s=63&r,a=t.getUint16(i,!1);i+=2;const o=[];for(let l=0;le.nalUnitType===Lt.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=ri(t);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ye[e.vp9CodecInfo.colourPrimaries],transfer:Te[e.vp9CodecInfo.transferCharacteristics],matrix:we[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ye[e.av1CodecInfo.colourPrimaries],transfer:Te[e.av1CodecInfo.transferCharacteristics],matrix:we[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ye[e.proresCodecInfo.colourPrimaries],transfer:Te[e.proresCodecInfo.transferCharacteristics],matrix:we[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},rr=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:n}=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=Rt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return null!=n?n:"dtsc";if(t&&Xi.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},nr=48e3,sr=/^pcm-([usf])(\d+)(be)?$/,ar=e=>{if(oe(Xi.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=sr.exec(e);let i;oe(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?q(2,7):0}},or=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":Zi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":er.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":sr.test(e)?e:"webvtt"===e?"webvtt":null,lr=[44100,48e3,32e3],cr=[-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],ur=1483304551,dr=1231971951,hr=(e,t)=>3===e?3===t?21:36:3===t?13:21,fr=(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=cr[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=lr[u]>>a+o,b=((e,t,i,r,n)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var pr,gr;(gr=pr||(pr={}))[gr.FrameCount=1]="FrameCount",gr[gr.FileSize=2]="FileSize",gr[gr.Toc=4]="Toc";const kr=e=>3===e?1:2;class yr{constructor(e){this.input=e}dispose(){}}const br=new Uint8Array(0);class Tr{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===br&&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===br}get microsecondTimestamp(){return Math.trunc(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){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 Tr(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 Tr(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 vr=e=>{const t=me(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=Be(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=Cl(e);const i=Nl(e,4);let r=8;1===t&&(t=Rl(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Pr=e=>El(e)/65536,Ir=e=>El(e)/1073741824,xr=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=vl(e);if(t|=127&i,0===(128&i))break}return t},Cr=e=>{let t=Sl(e);return e.skip(2),t=Math.min(t,e.remainingLength),pe.decode(Tl(e,t))},Br=e=>{const t=Sr(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Cl(e);e.skip(4);const r=Tl(e,t.contentSize-8);switch(i){case 1:return pe.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new It(r,"image/jpeg");case 14:return new It(r,"image/png");case 27:return new It(r,"image/bmp");default:return r}},Er=16,_r=new Uint32Array(256),Rr=new Uint32Array(256),Fr=new Uint32Array(256),Ar=new Uint32Array(256),Mr=new Uint32Array(256),Dr=new Uint32Array(256),Nr=new Uint32Array(10);let Or=!1;class Lr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Er/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Er),this.out=new Uint8Array(Er),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){oe(16===e.byteLength),oe(16===t.byteLength),Or||(()=>{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);_r[s]=t<<24|t<<16|t<<8|t,Dr[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);Rr[s]=n,Fr[s]=n>>>8|n<<24,Ar[s]=n>>>16|n<<16,Mr[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Nr[s]=n<<24,n=n<<1^(128&n?283:0);Or=!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&_r[e>>>16&255]^16711680&_r[e>>>8&255]^65280&_r[e>>>0&255]^255&_r[e>>>24&255]^Nr[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>>24&255]]^Fr[255&_r[t>>>16&255]]^Ar[255&_r[t>>>8&255]]^Mr[255&_r[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=Rr[e>>>24]^Fr[r>>>16&255]^Ar[i>>>8&255]^Mr[255&t]^this.roundkey[n],c=Rr[t>>>24]^Fr[e>>>16&255]^Ar[r>>>8&255]^Mr[255&i]^this.roundkey[n+1],u=Rr[i>>>24]^Fr[t>>>16&255]^Ar[e>>>8&255]^Mr[255&r]^this.roundkey[n+2],d=Rr[r>>>24]^Fr[i>>>16&255]^Ar[t>>>8&255]^Mr[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Dr[e>>>24&255]^16711680&Dr[r>>>16&255]^65280&Dr[i>>>8&255]^255&Dr[t>>>0&255]^this.roundkey[40],f=4278190080&Dr[t>>>24&255]^16711680&Dr[e>>>16&255]^65280&Dr[r>>>8&255]^255&Dr[i>>>0&255]^this.roundkey[41],m=4278190080&Dr[i>>>24&255]^16711680&Dr[t>>>16&255]^65280&Dr[e>>>8&255]^255&Dr[r>>>0&255]^this.roundkey[42],p=4278190080&Dr[r>>>24&255]^16711680&Dr[i>>>16&255]^65280&Dr[t>>>8&255]^255&Dr[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 zr extends yr{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 Y(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return Y(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 Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(ct(r)&&(r=yield r),!r)break;const n=e,s=Sr(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Nl(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(ct(e)&&(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>n+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');yield this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=n+s.totalSize}if(!i&&this.input._initInput&&(yield this.copyMetadataFromInitInput(this.input._initInput)),t){oe(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ct(e)&&(e=yield e),oe(e);const t=Cl(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(ct(e)&&(e=yield e),e){const t=Sr(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ct(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return Y(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==zr)throw new Error("Init input must match the input's format.");yield t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const e of t.tracks){const t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};if(e.trackBacking)if(oe(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new qr(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new Wr(e),this.tracks.push(t)}}})}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;oe(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&&Xi.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){oe("audio"===(null==(i=e.info)?void 0:i.type));const t=ar(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=Re(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=ce(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;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)Xr(e,r.timestamp);else{const t=Re(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];Xr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=Re(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 Yr(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ge(t.languageCode)||(t.languageCode=We)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Nl(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:H({},Pe),avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=re,this.readContiguousBoxes(e.slice(se,ne.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=vl(e);e.skip(3);const r=Cl(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Cl(e),e.skip(8)):2===a&&(e.skip(4),c=Dl(e),o=Cl(e),e.skip(4),l=Cl(e),u=Cl(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=nr;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(er.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Pt._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":(Pt._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":(Pt._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":(Pt._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":(Pt._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(Pt._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<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==vl(e),t.encryptionInfo.defaultPerSampleIvSize=vl(e),t.encryptionInfo.defaultKid=Be(Tl(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=vl(e),r=new Uint8Array(16);r.set(Tl(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;oe("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=vl(e),n=vl(e),s=vl(e),a=s>>4,o=s>>1&7,l=1&s,c=vl(e),u=vl(e),d=vl(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;oe("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=vl(e),l=o>>5,c=31&o,u=vl(e),d=u>>7,h=u>>6&1,f=u>>4&1,m=u>>3&1,p=u>>2&1,g=3&u,k=2===l&&h?u>>5&1?12:10:h?10:8;e.skip(1);const y=Tl(e,ne.contentSize-4),b=yi(y);t.info.av1CodecInfo={profile:l,level:c,tier:d,bitDepth:k,monochrome:f,chromaSubsamplingX:m,chromaSubsamplingY:p,chromaSamplePosition:g,videoFullRangeFlag:null!=(r=null==b?void 0:b.videoFullRangeFlag)?r:0,colourPrimaries:null!=(n=null==b?void 0:b.colourPrimaries)?n:2,transferCharacteristics:null!=(s=null==b?void 0:b.transferCharacteristics)?s:2,matrixCoefficients:null!=(a=null==b?void 0:b.matrixCoefficients)?a:2}}break;case"colr":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(o=t.info)?void 0:o.type));const i=Nl(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Sl(e),n=Sl(e),s=Sl(e);let a;"nclx"===i&&(a=Boolean(128&vl(e))),t.info.colorSpace={primaries:ye[r],transfer:Te[n],matrix:we[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(l=t.info)?void 0:l.type));const i=Cl(e),r=Cl(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==(null==(c=t.info)?void 0:c.type))break;e.skip(4);oe(3===vl(e)),xr(e),e.skip(2);const i=vl(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=vl(e);e.skip(t)}n&&e.skip(2);oe(4===vl(e));const s=xr(e),a=e.filePos,o=vl(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":Pt._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){oe(5===vl(e));const i=xr(e);if(t.info.codecDescription=Tl(e,i),"aac"===t.info.codec){const e=Rt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&Sl(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=vl(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=vl(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(h=t.info)?void 0:h.type)),e.skip(1);const i=vl(e),r=Sl(e),n=Cl(e),s=Il(e),a=vl(e);let o;o=0!==a?Tl(e,2+i):new Uint8Array(0);const l=new Uint8Array(19+o.byteLength),c=new DataView(l.buffer);c.setUint32(0,1332770163,!1),c.setUint32(4,1214603620,!1),c.setUint8(8,1),c.setUint8(9,i),c.setUint16(10,r,!0),c.setUint32(12,n,!0),c.setInt16(16,s,!0),c.setUint8(18,a),l.set(o,19),t.info.codecDescription=l,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=127,r=128,n=e.filePos;for(;e.filePos>>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=Tl(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;oe("audio"===(null==(m=t.info)?void 0:m.type));const i=Tl(e,3),r=new Bt(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Mt[n]),t.info.numberOfChannels=xi[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(p=t.info)?void 0:p.type));const i=(e=>{if(e.length<2)return null;const t=new Bt(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}})(Tl(e,ne.contentSize));if(!i){Pt._warn("Invalid dec3 box contents, ignoring.");break}const r=Ri(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Fi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(g=t.info)?void 0:g.type));const i=(e=>{if(e.length<20)return null;const t=me(e),i=t.getUint32(0);if(0===i)return null;const r=new Bt(e);r.seekToByte(13);const n=r.readBits(2);r.skipBits(5);const s=r.readBits(1),a=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let l=null;return 0!==o?l=ji(o):ae.id===i);if(!r)break;const n=Cl(e),s=(12&n)>>2,a=3&n,o=[vl,Sl,Pl,Cl],l=o[(48&n)>>4],c=o[s],u=o[a],d=Cl(e);for(let h=0;he.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let n=0;ne.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!=(y=null==d?void 0:d.defaultSampleDescriptionIndex)?y:null,defaultSampleDuration:null!=(b=null==d?void 0:d.defaultSampleDuration)?b:null,defaultSampleSize:null!=(T=null==d?void 0:d.defaultSampleSize)?T:null,defaultSampleFlags:null!=(v=null==d?void 0:d.defaultSampleFlags)?v:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Rl(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Cl(e)),n&&(u.currentFragmentState.defaultSampleDuration=Cl(e)),s&&(u.currentFragmentState.defaultSampleSize=Cl(e)),a&&(u.currentFragmentState.defaultSampleFlags=Cl(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;oe(t.currentFragmentState);const i=vl(e);e.skip(3);const r=0===i?Cl(e):Rl(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;oe(this.currentFragment),oe(t.currentFragmentState);const i=vl(e),r=Pl(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=Cl(e);let d=null;n&&(d=El(e));let h,f=null;s&&(f=Cl(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));for(let m=0;m0&&(n=Tl(e,r));const s=Qr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=vl(e);if(1&Pl(e)){const i=Nl(e,4),r=Cl(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Cl(e);if(0===r)break;r>1&&Pt._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Cl(e):Number(Rl(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);Qr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;oe(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Pl(e),n=Boolean(2&r),s=Cl(e),a=t.encryptionInfo.defaultPerSampleIvSize;oe(null!==a);for(let o=0;o0?r.set(Tl(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Sl(e);s=[];for(let i=0;i0&&(null!=(Y=this.metadataTags).trackNumber||(Y.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(J=this.metadataTags).tracksTotal||(J.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(Z=this.metadataTags).trackNumber||(Z.trackNumber=t)),i>0&&(null!=(ee=this.metadataTags).tracksTotal||(ee.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(te=this.metadataTags).discNumber||(te.discNumber=t)),i>0&&(null!=(ie=this.metadataTags).discsTotal||(ie.discsTotal=i))}}}}}return e.filePos=ae,!0}}class Ur{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;oe(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 Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return Y(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Hr(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return Gr(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=Re(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=Ne(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 oe(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=jr(i,e);if(!r)return null;let n;if(t.metadataOnly)n=br;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ct(t)&&(t=yield t),!t)return null;if(n=Tl(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield Yr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=Re(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(ct(e)&&(e=yield e),!e)break;const i=k,s=Sr(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.moofOffsetY(this,null,function*(){var e,t,i,r,n,s,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=yield this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&bi(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&yi(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&gi(t.data);i&&(this.internalTrack.info.vp9CodecInfo=V(H({},null!=(e=this.internalTrack.info.vp9CodecInfo)?e:i),{videoFullRangeFlag:i.videoFullRangeFlag,colourPrimaries:i.colourPrimaries,transferCharacteristics:i.transferCharacteristics,matrixCoefficients:i.matrixCoefficients}))}else{const e=yield this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&ni(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&$t(e.data)}if(!Se(this.internalTrack.info.colorSpace)){const e=ir(this.internalTrack.info);null!=(t=this.internalTrack.info.colorSpace).primaries||(t.primaries=e.primaries),null!=(i=this.internalTrack.info.colorSpace).transfer||(i.transfer=e.transfer),null!=(r=this.internalTrack.info.colorSpace).matrix||(r.matrix=e.matrix),null!=(n=this.internalTrack.info.colorSpace).fullRange||(n.fullRange=e.fullRange)}const o={codec:tr(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(s=this.internalTrack.info.codecDescription)?s:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Wr extends Ur{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr(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 Hr=(e,t)=>{if(e.presentationTimestamps){const i=Re(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=Re(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)}},Vr=(e,t)=>{var i;if(!e.keySampleIndices)return Hr(e,t);if(e.presentationTimestamps){const i=Re(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!==_e(e.keySampleIndices,i,e=>e))return i}return-1}{const r=Hr(e,t),n=Re(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},jr=(e,t)=>{const i=Re(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=Re(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];oe(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;ge)}},Kr=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=Re(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},Xr=(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},$r=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Gr=e=>0===e.sampleSizes.length,Qr=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}},Yr=(e,t,i)=>Y(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{oe(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Tl(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Sl(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Zr=(e,t,i,r)=>Y(null,null,function*(){var n;oe(e.encryptionInfo);const s=e.encryptionInfo;oe(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=Y(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{oe(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;iY(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=>Y(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);oe(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=rn(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 d=yield a(c),h=new Uint8Array(r);let f=0;for(const e of o)for(const t of e.perSubsample)h.set(d.subarray(f,f+t.length),t.offset),f+=t.length;return h}),tn=(e,t,i,r)=>{const n=new Lr;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(oe(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;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 nn,sn;(sn=nn||(nn={}))[sn.EBML=440786851]="EBML",sn[sn.EBMLVersion=17030]="EBMLVersion",sn[sn.EBMLReadVersion=17143]="EBMLReadVersion",sn[sn.EBMLMaxIDLength=17138]="EBMLMaxIDLength",sn[sn.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",sn[sn.DocType=17026]="DocType",sn[sn.DocTypeVersion=17031]="DocTypeVersion",sn[sn.DocTypeReadVersion=17029]="DocTypeReadVersion",sn[sn.Void=236]="Void",sn[sn.Segment=408125543]="Segment",sn[sn.SeekHead=290298740]="SeekHead",sn[sn.Seek=19899]="Seek",sn[sn.SeekID=21419]="SeekID",sn[sn.SeekPosition=21420]="SeekPosition",sn[sn.Duration=17545]="Duration",sn[sn.Info=357149030]="Info",sn[sn.TimestampScale=2807729]="TimestampScale",sn[sn.MuxingApp=19840]="MuxingApp",sn[sn.WritingApp=22337]="WritingApp",sn[sn.Tracks=374648427]="Tracks",sn[sn.TrackEntry=174]="TrackEntry",sn[sn.TrackNumber=215]="TrackNumber",sn[sn.TrackUID=29637]="TrackUID",sn[sn.TrackType=131]="TrackType",sn[sn.FlagEnabled=185]="FlagEnabled",sn[sn.FlagDefault=136]="FlagDefault",sn[sn.FlagForced=21930]="FlagForced",sn[sn.FlagOriginal=21934]="FlagOriginal",sn[sn.FlagHearingImpaired=21931]="FlagHearingImpaired",sn[sn.FlagVisualImpaired=21932]="FlagVisualImpaired",sn[sn.FlagCommentary=21935]="FlagCommentary",sn[sn.FlagLacing=156]="FlagLacing",sn[sn.Name=21358]="Name",sn[sn.Language=2274716]="Language",sn[sn.LanguageBCP47=2274717]="LanguageBCP47",sn[sn.CodecID=134]="CodecID",sn[sn.CodecPrivate=25506]="CodecPrivate",sn[sn.CodecDelay=22186]="CodecDelay",sn[sn.SeekPreRoll=22203]="SeekPreRoll",sn[sn.DefaultDuration=2352003]="DefaultDuration",sn[sn.Video=224]="Video",sn[sn.PixelWidth=176]="PixelWidth",sn[sn.PixelHeight=186]="PixelHeight",sn[sn.DisplayWidth=21680]="DisplayWidth",sn[sn.DisplayHeight=21690]="DisplayHeight",sn[sn.DisplayUnit=21682]="DisplayUnit",sn[sn.AlphaMode=21440]="AlphaMode",sn[sn.Audio=225]="Audio",sn[sn.SamplingFrequency=181]="SamplingFrequency",sn[sn.Channels=159]="Channels",sn[sn.BitDepth=25188]="BitDepth",sn[sn.SimpleBlock=163]="SimpleBlock",sn[sn.BlockGroup=160]="BlockGroup",sn[sn.Block=161]="Block",sn[sn.BlockAdditions=30113]="BlockAdditions",sn[sn.BlockMore=166]="BlockMore",sn[sn.BlockAdditional=165]="BlockAdditional",sn[sn.BlockAddID=238]="BlockAddID",sn[sn.BlockDuration=155]="BlockDuration",sn[sn.ReferenceBlock=251]="ReferenceBlock",sn[sn.Cluster=524531317]="Cluster",sn[sn.Timestamp=231]="Timestamp",sn[sn.Cues=475249515]="Cues",sn[sn.CuePoint=187]="CuePoint",sn[sn.CueTime=179]="CueTime",sn[sn.CueTrackPositions=183]="CueTrackPositions",sn[sn.CueTrack=247]="CueTrack",sn[sn.CueClusterPosition=241]="CueClusterPosition",sn[sn.Colour=21936]="Colour",sn[sn.MatrixCoefficients=21937]="MatrixCoefficients",sn[sn.TransferCharacteristics=21946]="TransferCharacteristics",sn[sn.Primaries=21947]="Primaries",sn[sn.Range=21945]="Range",sn[sn.Projection=30320]="Projection",sn[sn.ProjectionType=30321]="ProjectionType",sn[sn.ProjectionPoseRoll=30325]="ProjectionPoseRoll",sn[sn.Attachments=423732329]="Attachments",sn[sn.AttachedFile=24999]="AttachedFile",sn[sn.FileDescription=18046]="FileDescription",sn[sn.FileName=18030]="FileName",sn[sn.FileMediaType=18016]="FileMediaType",sn[sn.FileData=18012]="FileData",sn[sn.FileUID=18094]="FileUID",sn[sn.Chapters=272869232]="Chapters",sn[sn.Tags=307544935]="Tags",sn[sn.Tag=29555]="Tag",sn[sn.Targets=25536]="Targets",sn[sn.TargetTypeValue=26826]="TargetTypeValue",sn[sn.TargetType=25546]="TargetType",sn[sn.TagTrackUID=25541]="TagTrackUID",sn[sn.TagEditionUID=25545]="TagEditionUID",sn[sn.TagChapterUID=25540]="TagChapterUID",sn[sn.TagAttachmentUID=25542]="TagAttachmentUID",sn[sn.SimpleTag=26568]="SimpleTag",sn[sn.TagName=17827]="TagName",sn[sn.TagLanguage=17530]="TagLanguage",sn[sn.TagString=17543]="TagString",sn[sn.TagBinary=17541]="TagBinary",sn[sn.ContentEncodings=28032]="ContentEncodings",sn[sn.ContentEncoding=25152]="ContentEncoding",sn[sn.ContentEncodingOrder=20529]="ContentEncodingOrder",sn[sn.ContentEncodingScope=20530]="ContentEncodingScope",sn[sn.ContentCompression=20532]="ContentCompression",sn[sn.ContentCompAlgo=16980]="ContentCompAlgo",sn[sn.ContentCompSettings=16981]="ContentCompSettings",sn[sn.ContentEncryption=20533]="ContentEncryption";const an=[nn.EBML,nn.Segment],on=[nn.SeekHead,nn.Info,nn.Cluster,nn.Tracks,nn.Cues,nn.Attachments,nn.Chapters,nn.Tags],ln=[...an,...on],cn=16,un=e=>{if(e.remainingLength<1)return null;const t=vl(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=vl(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=un(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===vl(e))return;e.skip(-1);const t=dn(e);return null===t?null:72057594037927940!==t?t:void 0},pn=e=>{oe(e.remainingLength>=2);const t=fn(e);if(null===t)return null;const i=mn(e);return null===i?null:{id:t,size:i}},gn=(e,t)=>{const i=Tl(e,t);let r=0;for(;r{const i=Tl(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Ml(e):Dl(e)},bn=(e,t,i,r)=>Y(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Tn=(e,t,i,r)=>Y(null,null,function*(){const n=q(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return Y(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 Y(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=H(H({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,cn);if(ct(t)&&(t=yield t),!t)break;const i=pn(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===nn.EBML){Dn(n);let e=this.reader.requestSlice(s,n);if(ct(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===nn.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===nn.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield bn(this.reader,s,ln,this.reader.fileSize)).pos-s}const e=ce(this.segments);e&&(e.elementEndPos=s+n)}Dn(n),e=s+n}}))()}readSegment(e,t){return Y(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||re.id===s);if(-1!==l){const e=Wn[l].flag;this.currentSegment[e]=!0,Dn(a);let t=this.reader.requestSlice(o,a);ct(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===nn.Tags||s===nn.Attachments){s===nn.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Dn(a);let e=this.reader.requestSlice(o,a);ct(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===nn.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=Wn.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,cn);if(ct(r)&&(r=yield r),!r)continue;const n=pn(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Dn(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);ct(o)&&(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;ta&&(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 Y(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,cn);ct(r)&&(r=yield r),oe(r);const n=e,s=pn(r);oe(s);oe(s.id===nn.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield bn(this.reader,o,ln,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);ct(l)&&(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,ln);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;oe(e.blocks.length>0);let i=!1;for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[ce(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=Re(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=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,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A,M,D,N,O,L,z,U,q,W,j,K,X,$,G,Q,Y,J,Z,ee;const te=pn(e);if(!te)return!1;if(t&&t.includes(te.id))return!1;const{id:ie,size:re}=te,ne=e.filePos;switch(Dn(re),ie){case nn.DocType:this.isWebM="webm"===gn(e,re);break;case nn.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case nn.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=hn(e,re)}break;case nn.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=hn(e,re)}break;case nn.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=hn(e,re),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case nn.Duration:if(!this.currentSegment)break;this.currentSegment.duration=yn(e,re);break;case nn.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:V(H({},Ct),{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(ne,re)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==Ln.Block||e.data.algorithm!==Un.HeaderStripping})&&(Pt._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===vn)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===wn)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Sn)this.currentTrack.info.codec="vp8";else if(t===Pn)this.currentTrack.info.codec="vp9";else if(t===In)this.currentTrack.info.codec="av1";else if(t===xn){const e=this.currentTrack.codecPrivate?pe.decode(this.currentTrack.codecPrivate):"";Zi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Kn(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Cn?(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===Bn?this.currentTrack.info.codec="mp3":t===En?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=nr):t===_n?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Rn?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fn?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===An?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Mn?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Xn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case nn.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=hn(e,re);break;case nn.TrackType:{if(!this.currentTrack)break;const t=hn(e,re);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:H({},Pe),alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case nn.FlagEnabled:if(!this.currentTrack)break;hn(e,re)||(this.currentTrack=null);break;case nn.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!hn(e,re);break;case nn.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!hn(e,re);break;case nn.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!hn(e,re);break;case nn.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!hn(e,re);break;case nn.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!hn(e,re);break;case nn.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!hn(e,re);break;case nn.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=gn(e,re);break;case nn.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Tl(e,re);break;case nn.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=hn(e,re);break;case nn.Name:if(!this.currentTrack)break;this.currentTrack.name=kn(e,re);break;case nn.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=gn(e,re),Ge(this.currentTrack.languageCode)||(this.currentTrack.languageCode=We);break;case nn.LanguageBCP47:{if(!this.currentTrack)break;const t=gn(e,re).split("-")[0];this.currentTrack.languageCode=t||We,this.currentTrack.hasLanguageBcp47=!0}break;case nn.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=hn(e,re);break;case nn.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=hn(e,re);break;case nn.DisplayWidth:if("video"!==(null==(d=null==(u=this.currentTrack)?void 0:u.info)?void 0:d.type))break;this.currentTrack.info.displayWidth=hn(e,re);break;case nn.DisplayHeight:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayHeight=hn(e,re);break;case nn.DisplayUnit:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayUnit=hn(e,re);break;case nn.AlphaMode:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.alphaMode=1===hn(e,re);break;case nn.Colour:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.MatrixCoefficients:{if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;const t=hn(e,re),i=we[t];this.currentTrack.info.colorSpace.matrix=i}break;case nn.Range:{if("video"!==(null==(S=null==(w=this.currentTrack)?void 0:w.info)?void 0:S.type))break;const t=hn(e,re);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case nn.TransferCharacteristics:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=hn(e,re),i=Te[t];this.currentTrack.info.colorSpace.transfer=i}break;case nn.Primaries:{if("video"!==(null==(C=null==(x=this.currentTrack)?void 0:x.info)?void 0:C.type))break;const t=hn(e,re),i=ye[t];this.currentTrack.info.colorSpace.primaries=i}break;case nn.Projection:if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.ProjectionPoseRoll:{if("video"!==(null==(R=null==(_=this.currentTrack)?void 0:_.info)?void 0:R.type))break;const t=-yn(e,re);try{this.currentTrack.info.rotation=le(t)}catch(se){}}break;case nn.Audio:if("audio"!==(null==(A=null==(F=this.currentTrack)?void 0:F.info)?void 0:A.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.SamplingFrequency:if("audio"!==(null==(D=null==(M=this.currentTrack)?void 0:M.info)?void 0:D.type))break;this.currentTrack.info.sampleRate=yn(e,re);break;case nn.Channels:if("audio"!==(null==(O=null==(N=this.currentTrack)?void 0:N.info)?void 0:O.type))break;this.currentTrack.info.numberOfChannels=hn(e,re);break;case nn.BitDepth:if("audio"!==(null==(z=null==(L=this.currentTrack)?void 0:L.info)?void 0:z.type))break;this.currentTrack.info.bitDepth=hn(e,re);break;case nn.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(ne,re)),this.currentCueTime=null;break;case nn.CueTime:this.currentCueTime=hn(e,re);break;case nn.CueTrackPositions:{if(null===this.currentCueTime)break;oe(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case nn.CueTrack:{const t=null==(U=this.currentSegment)?void 0:U.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=hn(e,re)}break;case nn.CueClusterPosition:{const t=null==(q=this.currentSegment)?void 0:q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;oe(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+hn(e,re)}break;case nn.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=hn(e,re);break;case nn.SimpleBlock:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(W=i.track.info)?void 0:W.type)&&i.track.info.codec&&(a=!0);const o=Tl(e,re-(e.filePos-ne)),l=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,postProcessed:!1,mainAdditional:null})}break;case nn.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(ne,re)),this.currentBlock=null;break;case nn.Block:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e)>>1&3,s=Tl(e,re-(e.filePos-ne)),a=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case nn.BlockAdditions:this.readContiguousElements(e.slice(ne,re));break;case nn.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case nn.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Tl(e,re);break;case nn.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=hn(e,re);break;case nn.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=hn(e,re);break;case nn.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case nn.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(ne,re));break;case nn.Targets:this.readContiguousElements(e.slice(ne,re));break;case nn.TargetTypeValue:50!==hn(e,re)&&(this.currentTagTargetIsMovie=!1);break;case nn.TagTrackUID:case nn.TagEditionUID:case nn.TagChapterUID:case nn.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case nn.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(ne,re));break;case nn.TagName:this.currentSimpleTagName=kn(e,re);break;case nn.TagString:{if(!this.currentSimpleTagName)break;const t=kn(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.TagBinary:{if(!this.currentSimpleTagName)break;const t=Tl(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(ne,re));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new xt(this.currentAttachedFile.fileData,null!=(j=this.currentAttachedFile.fileMediaType)?j:void 0,null!=(K=this.currentAttachedFile.fileName)?K:void 0,null!=(X=this.currentAttachedFile.fileDescription)?X:void 0)),(null==($=this.currentAttachedFile.fileMediaType)?void 0:$.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!=(G=this.currentAttachedFile.fileName)?G:void 0,description:null!=(Q=this.currentAttachedFile.fileDescription)?Q:void 0})}this.currentAttachedFile=null}break;case nn.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;rt.order-e.order);break;case nn.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ln.Block,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case nn.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=hn(e,re);break;case nn.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=hn(e,re);break;case nn.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Un.Zlib,settings:null},this.readContiguousElements(e.slice(ne,re));break;case nn.ContentCompAlgo:if("decompress"!==(null==(J=null==(Y=this.currentDecodingInstruction)?void 0:Y.data)?void 0:J.type))break;this.currentDecodingInstruction.data.algorithm=hn(e,re);break;case nn.ContentCompSettings:if("decompress"!==(null==(ee=null==(Z=this.currentDecodingInstruction)?void 0:Z.data)?void 0:ee.type))break;this.currentDecodingInstruction.data.settings=Tl(e,re);break;case nn.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=ne+re,!0}decodeBlockData(e,t){oe(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(oe(r.data),"decompress"===r.data.type)if(r.data.algorithm===Un.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))}}}getDurationFromMetadata(e){return Y(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){oe(r.trackBacking);const e=yield r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(null!=t?t:1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=null!=t?t:0,i})}}class jn{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return Y(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=Re(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=Ne(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 oe(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return Y(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(oe(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if("prores"===(null==(r=this.internalTrack.info)?void 0:r.codec)){if(!(s.data.length>=8&&105===s.data[4]&&99===s.data[5]&&112===s.data[6]&&102===s.data[7])){const e=new Uint8Array(s.data.length+8);me(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(s.data,8),s.data=e}}s.postProcessed=!0}const a=i.metadataOnly?br:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,l=s.duration/this.internalTrack.segment.timestampFactor,c={};s.mainAdditional&&"video"===(null==(n=this.internalTrack.info)?void 0:n.type)&&this.internalTrack.info.alphaMode&&(c.alpha=i.metadataOnly?br:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Tr(a,s.isKeyFrame?"key":"delta",o,l,e.dataStartPos+t,s.data.byteLength,c);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u})}performClusterLookup(e,t,i,r,n){return Y(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=Re(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=Re(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,y=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let b;for(e?null===y||e.elementStartPos>=y?(b=e.elementEndPos,d=e):b=y:b=null!=y?y:u.clusterSeekStartPos;null===u.elementEndPos||b<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(b,2,cn);if(ct(e)&&(e=yield e),!e)break;const i=b,s=pn(e);if(!s||!on.includes(s.id)&&s.id!==nn.Void){const e=yield Tn(c.reader,i,on,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+Hn));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===nn.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){oe(a!==nn.Cluster);l=(yield bn(c.reader,m,ln,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,cn);if(ct(e)&&(e=yield e),!e)break;if(fn(e)===nn.Segment){u.elementEndPos=p;break}}b=p}if(p&&(!h||h.elementStartPosY(this,null,function*(){var e,t,i,r,n;let s=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(s=yield this.getFirstPacket({}));const a={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&&s?$t(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?ni(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?gi(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?yi(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?bi(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!Se(this.internalTrack.info.colorSpace)){const n=ir(a);null!=(e=this.internalTrack.info.colorSpace).primaries||(e.primaries=n.primaries),null!=(t=this.internalTrack.info.colorSpace).transfer||(t.transfer=n.transfer),null!=(i=this.internalTrack.info.colorSpace).matrix||(i.matrix=n.matrix),null!=(r=this.internalTrack.info.colorSpace).fullRange||(r.fullRange=n.fullRange)}const o={codec:tr(a),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(n=this.internalTrack.info.codecDescription)?n:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Xn extends jn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}}))():null})}}const $n=(e,t,i,r=null)=>Y(null,null,function*(){const n=q(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Cl(a),n=null!==e.fileSize?e.fileSize-s:null,o=fr(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&kr(o.header.channel)===kr(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class Gn extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Qn(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield $n(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=hr(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ct(r)&&(r=yield r),r){const n=Cl(r);if(n===ur||n===dr){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ct(t)&&(t=yield t),t){const e=Tl(t,12),i=me(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&pr.FrameCount?i.getUint32(4,!1):null,fileSize:r&pr.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);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 Y(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(ct(n)&&(n=yield n),!n)break;$l(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Wl){let e=this.reader.requestSlice(this.reader.fileSize-Wl,Wl);ct(e)&&(e=yield e),oe(e);"TAG"===Nl(e,3)&&jl(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class Qn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){const e=this.demuxer;if(oe(null!==e.firstFrameHeader),oe(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<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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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>>0&4294967295}const Zn=e=>{const t=me(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n>>24^t])>>>0}return t.setUint32(22,i,!0),r},es=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){oe(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,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:Ti[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},ts=27,is=282,rs=e=>{const t=e.filePos;if(Bl(e)!==Yn)return null;e.skip(1);const i=vl(e),r=Al(e),n=Bl(e),s=Bl(e),a=Bl(e),o=vl(e),l=new Uint8Array(o);for(let d=0;de+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}},ns=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Yn)return!0;e.skip(1)}}return!1};class ss extends yr{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,ts,is);if(ct(t)&&(t=yield t),!t)break;const i=rs(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 as(t,this)))}}))()})}readVorbisMetadata(e,t){return Y(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=me(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:vi(n.data).modeBlockflags},Ii(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return Y(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=me(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=nr,t.codecInfo.opusInfo={preSkip:n.preSkip},Ii(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return Y(this,null,function*(){oe(te+t.length,0);if(0===o)return null;const l=new Uint8Array(o);let c=0;for(let e=0;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 Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class as{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new xe,this.internalSampleRate="opus"===e.codecInfo.codec?nr:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return oe(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return Y(this,null,function*(){var e;return oe(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 We}getDisposition(){return V(H({},Ct),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(oe(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=es(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Tr(i.metadataOnly?br: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 Y(this,null,function*(){oe(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(oe(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 Y(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 Y(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=He(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;oe(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.totalSizen?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,ts,is);ct(t)&&(t=yield t),oe(t);const i=rs(t);oe(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}oe(-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:br,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=ls(d,u,m);oe(e);const t=os(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=ls(d,u,m);if(!e)break;const t=os(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,y=null;for(;null!==u;){oe(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&mn||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 Y(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=He(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=Re(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.timestampe)break;if(n=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);oe(e),this.sequentialScanCache.length>0&&oe(ce(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 os=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}oe(-1===n);if(!(1&r.headerType)){n=0;break}const t=De(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=De(e,e=>e.headerStartPosY(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);ct(i)&&(i=yield i),oe(i);const r=Nl(i,4),n="RIFX"!==r,s="RF64"===r,a=xl(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Nl(i,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=i.filePos;for(;null===o||u=18&&357!==n){const e=wl(r,i),s=t-18;if(Math.min(s,e)>=22&&n===cs.EXTENSIBLE){r.skip(6);const e=Tl(r,16);n=e[0]|e[1]<<8}}if(n!==cs.MULAW&&n!==cs.ALAW||(l=8),n!==cs.PCM&&n!==cs.IEEE_FLOAT&&n!==cs.ALAW&&n!==cs.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===cs.PCM&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(n===cs.IEEE_FLOAT&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,i){return Y(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(ct(m)&&(m=yield m),!m)return;const p=Nl(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Nl(m,4),t=xl(m,i),p=Tl(m,t);let k=0;for(let i=0;i0&&(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 Y(this,null,function*(){let i=this.reader.requestSlice(e,t);if(ct(i)&&(i=yield i),!i)return;const r=Xl(i);if(r){const n=t-Hl;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+Hl,r.size);$l(t,r,this.metadataTags)}}})}getCodec(){if(oe(this.audioInfo),this.audioInfo.format===cs.MULAW)return"ulaw";if(this.audioInfo.format===cs.ALAW)return"alaw";if(this.audioInfo.format===cs.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===cs.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}oe(!1)}getMimeType(){return Y(this,null,function*(){return"audio/wav"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const hs=2048;class fs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return Y(this,null,function*(){const e=this.demuxer.getCodec();return e?(oe(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getDisposition(){return H({},Ct)}getPacketAtIndex(e,t){return Y(this,null,function*(){oe(e>=0),oe(this.demuxer.audioInfo);const i=e*hs*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(hs*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(ct(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=br;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);ct(e)&&(e=yield e),oe(e),n=Tl(e,r)}const s=e*hs/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 Tr(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return Y(this,null,function*(){oe(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/hs,(this.demuxer.dataSize-1)/(hs*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;oe(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){oe(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/hs);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ms=e=>{const t=e.filePos,i=Tl(e,9),r=new Bt(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}},ps=1024;class gs extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();oe(this.firstFrameHeader),this.trackBackings=[new ks(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ms(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=Et[t.samplingFrequencyIndex];oe(void 0!==i);const r=ps/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=ps,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return Y(this,null,function*(){return"audio/aac"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(t)&&(t=yield t),!t)break;const i=Xl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ct(r)&&(r=yield r),!r)break;$l(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class ks{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ps}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getCodec(){return"aac"}getInternalCodecId(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){oe(this.demuxer.firstFrameHeader);const e=_t[this.demuxer.firstFrameHeader.channelConfiguration];return oe(void 0!==e),e}getSampleRate(){oe(this.demuxer.firstFrameHeader);const e=Et[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return oe(void 0!==e),e}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.dataSize)}return new Tr(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=_e(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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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+1Y(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=Xl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);ct(r)&&(r=yield r),oe(r),$l(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(255===vl(s)){const t=s.filePos;if(vl(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=Tl(e,4),n=new Bt(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){oe(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){oe(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");oe(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*q(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?q(2,e):null)(n.readBits(4));if(!s)return null;oe(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 o=(e=>{let t=0;const i=new Bt(Tl(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Bt(Tl(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Sl(e)+1:"uncommon-u8"===t?vl(e)+1:"number"===typeof t?t:(Oe(t),void oe(!1)))(e,s),c=((e,t)=>"uncommon-u16"===t?Sl(e):"uncommon-u16-10"===t?10*Sl(e):"uncommon-u8"===t?vl(e):"number"===typeof t?t:null)(e,a);if(null===c)return null;if(c!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,d=vl(e);e.skip(-u),e.skip(-1);const h=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Tl(e,u));return d!==h?null:{num:o,blockSize:l,sampleRate:c}}advanceReader(){return Y(this,null,function*(){yield this.readMetadata(),oe(null!==this.lastLoadedPos),oe(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 bs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return We}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return Y(this,null,function*(){if(oe(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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 Y(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 Y(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.byteSize)}oe(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Tr(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return Y(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Ts=9e4,vs=q(2,33),ws=188,Ss="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.",Ps=new Set([133,134,162]),Is=new Set;class xs extends yr{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=this.reader.requestSlice(0,205);ct(e)&&(e=yield e),oe(e);const t=Tl(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ws;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}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){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 Bt(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=Bs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(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 As(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=$t(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];oe(t);const i=Jt(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[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=ni(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT).nalUnits[0];oe(t);const i=ri(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:tr({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(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=yl.tempFromBytes(r.suppliedPacket.data),i=ms(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=_t[i.channelConfiguration],e.info.sampleRate=Et[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Cl(yl.tempFromBytes(r.suppliedPacket.data)),i=fr(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=kr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Ci(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=xi[t.acmod]+t.lfeon,e.info.sampleRate=Mt[t.fscod]}else if("eac3"===e.info.codec){const t=_i(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Ri(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Fi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=qi(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:rr({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Bt(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),l=e.pos+8*n;let c=!1;for(;e.pos=4){const t=e.readBits(32);c||(c=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=l;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,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let l=null;const u=c&&Ps.has(t)?130:t;switch(u){case 27:case 36:l={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",l={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:a?l={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?l={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(l={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Is.has(t)||(Pt._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Is.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}s=!0}else{const e=new Bt(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)a.initialized&&("video"===a.info.type?this.trackBackingEntries.push(new _s(a)):this.trackBackingEntries.push(new Rs(a)))}))()})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(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 Y(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!==_e(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=Re(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 Y(this,null,function*(){let t=this.reader.requestSlice(e,4);if(ct(t)&&(t=yield t),!t)return null;if(71!==vl(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Sl(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:vl(t)>>4&3}})}readPacket(e){return Y(this,null,function*(){let t=this.reader.requestSlice(e,ws);if(ct(t)&&(t=yield t),!t)return null;const i=Tl(t,ws);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}})}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=vs-t?-vs:vs}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new Bt(t.payload);if(1!==r.readBits(24))return null;const n=r.readBits(8);if(r.skipBits(16),188===n||190===n||191===n||240===n||241===n||255===n||242===n||248===n)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let a=null;if(2===s||3===s)a=0,r.skipBits(4),a+=r.readBits(3)*(1<<30),r.skipBits(1),a+=32768*r.readBits(15),r.skipBits(1),a+=r.readBits(15),a=e.normalizeTimestamp(a);else if(i)throw new Error(Ss);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Bs=(e,t,i)=>{oe(null!==t.endPos);const r=Cs(e,t,i);if(!r)return null;const n=new Bt(t.payload);n.skipBits(32);const s=n.readBits(16);n.skipBits(16);const a=n.readBits(8),o=n.pos+8*a;n.pos=o;const l=o/8;oe(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return V(H({},r),{data:c})};class Es{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++,oe(r instanceof Es),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 We}getDisposition(){return V(H({},Ct),{primary:!1})}getTimeResolution(){return Ts}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Tr(i.metadataOnly?br:e.data,r,e.pts/Ts,Math.max(t/Ts,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return Y(this,null,function*(){const t=this.elementaryStream.firstSection;oe(t);const i=Bs(this.elementaryStream.demuxer,t,!0);oe(i);const r=new As(this.elementaryStream,i),n=new Ms(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 Y(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);oe(s);const a=Bs(n,s,!0);oe(a);const o=new As(this.elementaryStream,a);i=new Ms(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 Y(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 Y(this,null,function*(){var r,n,s,a,o,l;const c=He(e*Ts),u=this.elementaryStream.demuxer,{reader:d,seekChunkSize:h}=u,f=this.elementaryStream.pid,m=(e,t,i)=>Y(this,null,function*(){let r=e;for(;re.pts),T=-1!==b?y[b]:null;if(T&&c-T.pts<45e3)k=T.sectionStartPos;else{let e=0;if(null!==d.fileSize){const t=Math.ceil(d.fileSize/h);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=Ke(t*h,u.packetStride)+g.sectionStartPos,s=n+h,a=yield m(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}k=Ke(e*h,u.packetStride)+g.sectionStartPos}const v=yield m(k,null!=(r=d.fileSize)?r:1/0,!1);let w=null!=(n=null==v?void 0:v.pesPacketHeader)?n:null;w||(w=g);const S=this.getReorderSize(),P=(e,t)=>Y(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);oe(s);const a=Bs(u,s,!0);oe(a);const o=new As(this.elementaryStream,a),l=new Ms(this,o);for(;;){if((null!=(n=null==(r=ce(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=Ne(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();oe(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=w.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;w=e,Fs(this.elementaryStream,w);break}}}e+=u.packetStride}}e:for(let e=0;e=u.packetOffset;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){w=e;break}}}e-=u.packetStride}}return P(w.sectionStartPos,e=>e.pts<=c)}{let e=k,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=g.sectionStartPos;let k,y=null;if(n)k=g,y=p;else{const t=yield m(e,null!=(s=d.fileSize)?s:1/0,i);k=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,y=null!=(o=null==t?void 0:t.section)?o:null}let b=!1,T=0;e:for(;k&&!(null!==t&&k.sectionStartPos>=t);){if(k.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===k.randomAccessIndicator;else{oe(y);const t=Bs(u,y,!0);oe(t);const i=new As(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=k)}if(k.pts>c&&(b=!0),b&&(T++,T>S))break;let e=k.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){k=e,y=t,Fs(this.elementaryStream,k);break}}}e+=u.packetStride}}if(r){let e=r;if(0===T)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===f&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Cs(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield P(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return oe(t),t}if(n)return null;t=e,e=Math.max(Ke(e-g.sectionStartPos-h,u.packetStride)+g.sectionStartPos,g.sectionStartPos)}}})}}class _s extends Es{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 Y(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return Y(this,null,function*(){return!1})}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Rs extends Es{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Fs=(e,t)=>{const i=e.referencePesPackets,r=Re(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=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return oe(e),e}bufferData(e){return Y(this,null,function*(){const t=this.endPos+e;for(;this.endPos=c)break;u=t;const r=o+u;if(u+3>=c){this.seekTo(r);break}const d=l[u+1],h=l[u+2],f=l[u+3];let m=0;if(0===d&&0===h&&1===f?m=4:0===d&&1===h&&(m=3),0===m){u++;continue}const p=r;null!=n||(n=p);const g=u+m,k=g+i,y=6;if(k+("avc"===e?y:1)>c){this.seekTo(r);break}const b=l[g];let T,v,w;if("avc"===e)T=Ht(b),v=T===Nt.NON_IDR_SLICE||T===Nt.SLICE_DPA||T===Nt.IDR,w=T===Nt.SEI||T===Nt.SPS||T===Nt.PPS||T===Nt.AUD;else{T=ii(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=Lt.RASL_R||T>=Lt.BLA_W_LP&&T<=21,w=T>=Lt.VPS_NUT&&T<=37||T===Lt.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let S=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=ue(new Bt(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?S=!0:s=!0)}else w&&s&&(S=!0);if(S){const e=p-n;return this.seekTo(n),this.supplyPacket(e,0)}u+=m}if(rn){const e=this.endPos-n;return this.seekTo(n),this.supplyPacket(e,0)}}else{const n=r.info.codec,s=128;for(;;){let a=this.ensureBuffered(s);ct(a)&&(a=yield a);const o=this.currentPos;for(;this.currentPos-o>6,a=63&i[4];if(3===n||a>37){this.seekTo(e+1);continue}const o=Bi[3*a+n];oe(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),ct(t)&&(t=yield t);const l=Math.round(13824e4/r.info.sampleRate);return this.supplyPacket(t,l)}if("eac3"===n){if(11!==s)continue;this.skip(-1);const e=this.currentPos;let t=this.ensureBuffered(5);if(ct(t)&&(t=yield t),t<5)return;const i=this.readBytes(5);if(11!==i[0]||119!==i[1]){this.seekTo(e+1);continue}const n=2*(((7&i[2])<<8|i[3])+1),a=3===i[4]>>6?3:i[4]>>4&3,o=Ei[a];this.seekTo(e),t=this.ensureBuffered(n),ct(t)&&(t=yield t);const l=256*o,c=Math.round(l*Ts/r.info.sampleRate);return this.supplyPacket(t,c)}if("dts"===n){if(127!==s&&100!==s)continue;this.skip(-1);const n=this.currentPos;let a=this.ensureBuffered(18);if(ct(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=Hi(o);let c=l?null:Vi(o);if(!l&&!c){this.seekTo(n+1);continue}if(c&&!c.asset){this.seekTo(n);const t=Math.min(c.frameSize,4096);let i=this.ensureBuffered(t);ct(i)&&(i=yield i),c=null!=(e=Vi(this.readBytes(i)))?e:c}let u=l?l.frameSize:c.frameSize;if(l){let e=4*Math.ceil(l.frameSize/4);for(;;){this.seekTo(n);const t=e+10;let i=this.ensureBuffered(t);if(ct(i)&&(i=yield i),i=0)}readNext(){return Y(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(oe(-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 Y(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 Y(this,null,function*(){const e=this.decodeOrderPackets[0];for(oe(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;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const Ds="application/vnd.apple.mpegurl",Ns="#EXT-X-STREAM-INF:",Os="#EXT-X-I-FRAME-STREAM-INF:",Ls="#EXT-X-MEDIA:",zs="#EXTINF:",Us="#EXT-X-MAP:",qs="#EXT-X-KEY:",Ws="#EXT-X-MEDIA-SEQUENCE:",Hs="#EXT-X-BYTERANGE:",Vs="#EXT-X-PROGRAM-DATE-TIME:",js="#EXT-X-TARGETDURATION:",Ks="#EXT-X-PLAYLIST-TYPE:",Xs=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class $s{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sY(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,t,i))}else if("audio"===t.type){const i=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(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=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return Y(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 Y(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 Qs{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(this,null,function*(){var e,t;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.");let i=this.segmentedInput.firstSegment,r=null;for(;i;){const e=this.segmentedInput.getInputForSegment(i);if(r=null!=(t=(yield e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number))?t:null,r)break;i=yield this.segmentedInput.getNextSegment(i,{})}if(!r)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=r,this.firstSegment=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 Y(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 Y(this,null,function*(){return yield this.hydrate(),oe(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp})}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return Y(this,null,function*(){oe(e.sequenceNumber>=0),oe(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:je(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 Y(this,null,function*(){var t;yield this.hydrate(),oe(this.firstInputTrack),oe(this.firstSegment);let i=this.firstInputTrack,r=this.firstSegment;for(;;){if(i){const t=yield i._backing.getFirstPacket(e);if(t)return this.createAdjustedPacket(t,r,i)}if(r=yield this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;const n=this.segmentedInput.getInputForSegment(r);i=null!=(t=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number))?t:null}return null})}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}_getNextInternal(e,t,i){return Y(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 Y(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 Ys extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class Js extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}ft();const Zs=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ea extends vt{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}getSizeOrNull(){return Y(this,null,function*(){var e;if(this._disposed)throw new gl;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>Y(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,Zs),e=this._getFileSize(),oe(void 0!==e)),e}))()})}getSize(){return Y(this,null,function*(){if(this._disposed)throw new gl;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 ga(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 ta(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class ta{constructor(e){var t;if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),null==(t=e._refFinalizationRegistry)||t.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){var e;if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const t=this.source;oe(t._refCount>0),t._decrementRefCount(),null==(e=t._refFinalizationRegistry)||e.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class ia extends ea{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 ea||e instanceof ta))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ea?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ct(t)?t.then(i):i(t)}}const ra=(e,t)=>e.path===t.path;class na extends ia{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 ea?e.ref():e;return this._root=t,this._rootRequest=null,t};ct(e)?this._rootRequest=e.then(t):(t(e),oe(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())}}const sa="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class aa extends ea{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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new pa({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*q(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==sa||sa.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ma.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return Y(this,null,function*(){oe(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!it()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==sa||sa.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return Pt._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(q(2,e-2),16)},ca=new Set;class ua extends ia{constructor(e,t={}){var i,r,n,s;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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new ua(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=null!=(i=t.getRetryDelay)?i:la,this._requestInit=H({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=H({},Je(t.requestInit.headers)),i=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==i&&(a=e[i],delete e[i],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){null!=a||(a=t);const i=new Request(e);i.headers.delete("Range"),this._url=i}}if(null!==a){const e=ha(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new pa({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*q(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:ma.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){var e;if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const t=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===t?null!==this._length?this._length:null:qe(t-this._offset,0,null!=(e=this._length)?e:1/0)}_read(e,t,i,r){var n;if(null!==this._length&&t>this._length)return null;const s=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+t):this._orchestrator.read(s+e,s+t,Math.max(s+i,s),s+Math.min(r,null!=(n=this._length)?n:1/0)),o=e=>e?(e.offset-=this._offset,e):null;return ct(a)?a.then(o):o(a)}_runWorker(e){return Y(this,null,function*(){for(var t;;){const r=new AbortController,n=yield Ze(null!=(t=this._options.fetchFn)?t:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(null===this._orchestrator.fileSize&&(206===n.status||"basic"===n.type&&!n.headers.has("Content-Encoding"))){const t=n.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=n.headers.get("Content-Length");if(i){const t=206===n.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==n.status){if(this._sequentialBacking)return void n.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||ca.has(e.origin)||(Pt._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),ca.add(e.origin))}return void this._transitionToSequentialMode(n.body)}const s=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return r.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let t;try{t=yield s.read()}catch(i){if(this._disposed)throw i;const e=this._getRetryDelay(1,i,this._url);if(null!==e){Pt._error("Error while reading response stream. Attempting to resume.",i),yield Tt(1e3*e);break}throw i}if(e.aborted)continue;const{done:n,value:a}=t;if(n){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+a.length),this._orchestrator.supplyWorkerData(e,a)}}})}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const n=new ReadableStream({pull:e=>Y(this,null,function*(){for(var n;;){let a;try{a=yield t.read()}catch(s){if(this._disposed)throw s;const e=this._getRetryDelay(1,s,this._url);if(null===e)throw s;Pt._error("Error while reading response stream. Attempting to resume.",s),yield Tt(1e3*e);const a=yield Ze(null!=(n=this._options.fetchFn)?n:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!a.ok)throw new Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=a.body.getReader(),r=206===a.status?0:i;continue}if(a.done)return void e.close();let o=a.value;if(r>0){const e=Math.min(r,o.length);r-=e,o=o.subarray(e)}if(0!==o.length)return i+=o.length,void e.enqueue(o)}}),cancel:()=>t.cancel()}),s=new fa(n,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const a=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)a.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)a.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of a){const e=s._read(o.start,o.start+o.bytes.length);ct(e)?e.then(e=>{e?(oe(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(oe(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const da=/^bytes=(\d+)-(\d*)$/,ha=e=>{const t=da.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=Re(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=t)break;const r=Math.max(e,i.start);r>n&&this._throwDueToCacheMiss();const a=Math.min(t,i.end);rn&&this._throwDueToCacheMiss();const{promise:a,resolve:o,reject:l}=Ae();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)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),a}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}_pull(){return Y(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._currentIndex0;){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;for(const t of this._pendingSlices)t.reject(new gl);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const ma={fileSystem:(e,t)=>{const i=q(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=q(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*q(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(dt(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=q(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+oa)}}};class pa{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;oe(!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);oe(a<=e&&t<=o);let l=null;const c=Re(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=Re(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=o)break;if(r.end<=a)continue;const n=Math.max(a,r.start),s=Math.min(o,r.end);if(oe(n<=s),m=h.length&&(l={bytes:h,view:me(h),offset:e}),0===p.length)return oe(l),l;const{promise:g,resolve:k,reject:y}=Ae(),b=[];for(const v of p){const i=Math.max(e,v.start),r=Math.min(t,v.end);i===v.start&&r===v.end?b.push(v):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&v.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,v.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:v.start,end:v.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.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?g.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(oe(h),l=g.then(t=>t&&{bytes:t,view:me(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=q(2,17);if(dt(t.start-r,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=s),t.end<=t.start&&(i.holes.splice(e,1),e--)}0===i.holes.length&&(i.resolve(i.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){var t,i;const r=this.workers.indexOf(e);oe(-1!==r),e.running=!1,this.workers.splice(r,1),null==(i=(t=this.options).onIdleWorkerRemoved)||i.call(t,e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=Re(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=me(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=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=me(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;ithis._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return ct(n)?n.then(s):s(n)}_dispose(){var e;null==(e=this._ref)||e.free()}ref(){return null!=this._ref||(this._ref=this._baseSource.ref()),super.ref()}}var ka=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},ya=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 ba=/^0[xX][0-9a-fA-F]+$/,Ta=/^data:.*;base64,/i;class va extends Gs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>Y(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Tt(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 Y(this,null,function*(){var e,t,i,r,n,s,a,o;let l=this.nextLines;if(this.nextLines=null,!l){const e={stack:[],error:void 0,hasError:!1};try{const t=ka(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new kl(t.source),r=yield i.requestEntireFile();oe(r),l=Ol(r,r.length,{ignore:Xs}),t.source instanceof ia&&(this.rootPath=t.source.rootPath)}catch(x){e.error=x,e.hasError=!0}finally{ya(e)}}const c=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let u=!1,d=0,h=null,f=null,m=null,p=0,g=null,k=null,y=null,b=null,T=null,v=null,w=!1,S=null!=(t=ce(this.segments))?t:null;const P=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}},I=e=>{p=e,S&&(oe(null!==S.sequenceNumber),S.sequenceNumber0&&null!==v&&(d=p*v),w=!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(Us)){const t=new $s(e.slice(11)),i=t.get("uri");if(!i)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const r=t.get("byterange");let a=null;if(null!==r&&(a=P(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!S){const e={path:pt(this.rootPath,i),offset:null!=(n=null==a?void 0:a.offset)?n:0,length:null!=(s=null==a?void 0:a.length)?s: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:d,unixEpochTimestamp:h,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:m,initSegment:null,lastProgramDateTimeSeconds:T}}f=null,null===b?y=null:b=null}else if(e.startsWith(qs)){const t=new $s(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(!ba.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Er);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=me(i).getUint32(0);r=vr(i.subarray(8,Math.min(e,i.length)))}}m={method:i,psshBox:r}}}}else if(e.startsWith(Ws)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);I(i)}else if(e.startsWith(Hs)){const t=P(e.slice(17));if(null===t.offset){if(null===y)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=y}b=t,y=t.offset+t.length}else if(e.startsWith(Vs)){if(S)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(T===r)continue;if(null===T&&this.segments.length>0){const e=ce(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,c&&(i.timestamp=i.unixEpochTimestamp)}T=r,h=r,c&&(d=r)}else if("#EXT-X-DISCONTINUITY"===e)g=null;else if(e.startsWith(js)){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,v=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(Ks)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");u=!0}}if(!u)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return Y(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return Y(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=Re(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.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=V(H({},this.input._formatOptions),{isobmff:V(H({},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=>wr(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(V(H({},e),{psshBoxes:t}))})})}),o=new ml({source:new na(r.location.path,e=>Y(this,null,function*(){var t,i;oe(e.isRoot);const n=V(H({},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;oe(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 o=((e,t,i)=>{let r=!1,n=0;const s=q(2,16),a=new Lr;return new ReadableStream({pull:o=>Y(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(ct(c)&&(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=Tl(c,d),f=new Uint8Array(d);for(let e=0;e16)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 kl(t.source),()=>Y(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=ka(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},fl),!1),r=new kl(i.source),n=yield r.requestSlice(0,Er);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Tl(n,Er),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ya(t)}}),()=>{t.free()});s=new fa(o).ref()}else oe(!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 qa)),initInput:null!=s?s:void 0,formatOptions:a});o._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:o,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=kt(this.inputCache,e=>e.age);oe(-1!==e),this.inputCache.splice(e,1)}return o}getLiveRefreshInterval(){return Y(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class wa extends yr{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=(()=>Y(this,null,function*(){oe(this.input._rootSource instanceof ia);const e=yield this.input._reader.requestEntireFile();oe(e);const t=Ol(e,e.length,{ignore:Xs}),{rootPath:i}=this.input._rootSource,r=[],n=[];for(let u=1;u"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((e,t)=>Y(this,null,function*(){var r,o,l,c;const u=[],d=e.attributes.get("codecs");let h;if(d)h=d.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=yield t.getTrackBackings(),r=yield Promise.all(i.map(e=>Y(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));h=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const f=e.attributes.get("video"),m=e.attributes.get("audio"),p=h.some(e=>Ki.includes(or(e))),g=h.some(e=>$i.includes(or(e)));if(null!==f&&!p){if(!s.includes(f))throw new Error(`Invalid M3U8 file; variant stream references video group "${f}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===f&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}if(null!==m&&!g){if(!a.includes(m))throw new Error(`Invalid M3U8 file; variant stream references audio group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}h=[...new Set(h)];let k=null,y=null;const b=e.attributes.getAsNumber("bandwidth");oe(null!==b);const T=e.attributes.getAsNumber("average-bandwidth"),v=e.attributes.get("name");for(const i of h){const d=or(i);if(null!==d)if(Ki.includes(d)){if(null!==k)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");k=i;const a=e.attributes.get("video");if(null===a){const i=e.attributes.get("resolution");let r=null,n=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),n=Number(e[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:We,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:k,pairingMask:BigInt("1")<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 i of n){const n=i.attributes.get("group-id"),s=i.attributes.get("type");if(n!==r||"audio"!==s.toLowerCase())continue;const a=null!=(l=i.attributes.get("channels"))?l:e.attributes.get("channels"),o=null!==a?Number(a.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:xa(i.attributes),autoselect:xa(i.attributes)||Ca(i.attributes),languageCode:Ba(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:y,pairingMask:BigInt("1")<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===We&&(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 Pa(u)):this.trackBackings.push(new Ia(u));this.internalTracks=l}))()}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),oe(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 va(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(this,null,function*(){return Ds})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Sa{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(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 Pa){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{oe(this instanceof Ia);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 V(H({},Ct),{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(){oe(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Pa extends Sa{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Ia extends Sa{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const xa=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}".`)},Ca=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}".`)},Ba=e=>{if(null===e)return We;const t=e.split("-")[0];return t||We};class Ea{constructor(){this._isIsobmff=!1}}class _a extends Ea{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return null;t.skip(4);const i=Nl(t,4);return"ftyp"!==i&&"styp"!==i?null:Nl(t,4)})}_createDemuxer(e){return new zr(e)}}class Ra extends _a{_canReadInput(e){return Y(this,null,function*(){const t=yield this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(ct(t)&&(t=yield t),!t)return!1;let r=Cl(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ct(t)&&(t=yield t),!t)return!1;r=Rl(t),n=16}if(r8)return!1;if(hn(i,r)!==nn.EBML)return!1;const n=mn(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(ct(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=pn(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case nn.EBMLVersion:if(1!==hn(s,r))return!1;break;case nn.EBMLReadVersion:if(1!==hn(s,r))return!1;break;case nn.DocType:if(gn(s,r)!==t)return!1;break;case nn.DocTypeVersion:if(hn(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Vn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ma extends Aa{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Da extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}const i=yield $n(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=hr(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(ct(s)&&(s=yield s),!s)return!1;const a=Cl(s);if(a===ur||a===dr)return!0;t=i.startPos+i.header.totalSize;const o=yield $n(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 Gn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Na extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return!1;const i=Nl(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Nl(t,4)})}_createDemuxer(e){return new ds(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Oa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,4);return ct(t)&&(t=yield t),!!t&&"OggS"===Nl(t,4)})}_createDemuxer(e){return new ss(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class La extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ct(i)&&(i=yield i),!!i&&"fLaC"===Nl(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ys(e)}}class za extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ct(i)&&(i=yield i),!i)return!1;const r=ms(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ct(i)&&(i=yield i),!i)return!1;const n=ms(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new gs(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ua extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,205);if(ct(t)&&(t=yield t),!t)return!1;const i=Tl(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 xs(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class qa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,7);if(ct(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Nl(t,7)))return!1;if(!(e._rootSource instanceof ia))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 wa(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Ds}}const Wa=new Ra,Ha=new Fa,Va=new Aa,ja=new Ma,Ka=new Da,Xa=new Na,$a=new Oa,Ga=new za,Qa=new La,Ya=new Ua,Ja=new qa,Za=[Ja,Wa,Ha,Va,ja,Xa,$a,Qa,Ka,Ga,Ya],eo=[Ja,Wa,Ha,Ka,Ga,Ya];var to=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});ft();let io=-1/0,ro=-1/0,no=null;"undefined"!==typeof FinalizationRegistry&&(no=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-io>=1e3&&(Pt._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."),io=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ro>=1e3&&(Pt._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."),ro=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class so{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const ao=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],oo=new Set(ao);class lo{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(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*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,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F;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||!oo.has(t.format))throw new TypeError("init.format must be one of: "+ao.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&&bt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=null!=(i=t.rotation)?i:0,this.timestamp=t.timestamp,this.duration=null!=(r=t.duration)?r:0;const m=null!=(n=t.layout)?n:bo(t.format,t.codedWidth,t.codedHeight);let p=null!=(s=t.colorSpace)?s:null;null===p&&(p="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:null!=(o=null==(a=t.visibleRect)?void 0:a.left)?o:0,top:null!=(c=null==(l=t.visibleRect)?void 0:l.top)?c:0,width:null!=(d=null==(u=t.visibleRect)?void 0:u.width)?d:t.codedWidth,height:null!=(f=null==(h=t.visibleRect)?void 0:h.height)?f:t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?fe(e):fe(e).slice(),this._layout=m,this.colorSpace=new mo(p)}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)&&bt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:null!=(p=null==(m=e.visibleRect)?void 0:m.x)?p:0,top:null!=(k=null==(g=e.visibleRect)?void 0:g.y)?k:0,width:null!=(b=null==(y=e.visibleRect)?void 0:y.width)?b:e.codedWidth,height:null!=(v=null==(T=e.visibleRect)?void 0:T.height)?v:e.codedHeight},this.rotation=null!=(w=null==t?void 0:t.rotation)?w:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(S=null==t?void 0:t.timestamp)?S:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new mo(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&bt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new lo(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Qe),duration:Math.trunc((null!=(x=t.duration)?x:0)*Qe)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const n=null!=(C=t.visibleRect)?C:{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(n.width,n.height),a=s.getContext("2d",{alpha:nt(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-n.left,-n.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n.width,height:n.height},this.squarePixelWidth=n.width,this.squarePixelHeight=n.height,this.rotation=null!=(B=t.rotation)?B:0,this.timestamp=t.timestamp,this.duration=null!=(E=t.duration)?E:0,this.colorSpace=new mo({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof so))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!ao.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=null!=(_=t.rotation)?_:0,this.timestamp=t.timestamp,this.duration=null!=(R=t.duration)?R:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(F=null==t?void 0:t.encodeOptions)?F:{},this.pixelAspectRatio=yt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==no||no.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return oe(null!==this._data),this._data instanceof so?new lo(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):po(this._data)?new lo(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(oe(this._layout),new lo(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new lo(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof so?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(yo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(t=e.format)?t:this.format))throw new Error("Cannot get allocation size when format is null.");if(po(this._data))return this._data.allocationSize(e);return vo(this,e).allocationSize}copyTo(e){return Y(this,arguments,function*(e,t={}){var i,r;if(!Ie(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(i=t.format)?i:this.format))throw new Error("Cannot copy video sample data when format is null.");if(oe(null!==this._data),po(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof so)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=yield i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const n=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}(i,yield this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},null!=(r=t.colorSpace)?r:"srgb"),!1);if(!(n instanceof lo))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return yield n.copyTo(e,t)}catch(u){i.error=u,i.hasError=!0}finally{to(i)}}}const n=vo(this,t);oe(this.format);const s=fe(e);if(s.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=e}else if(this._data instanceof Uint8Array)oe(this._layout),oe(this._layout.length===a.length),o=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");oe(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:fe(t.data),stride:4*this.codedWidth}]}const l=[],c=a.length;for(let d=0;di.byteLength)throw new Error("Source buffer OOB read.");if(a+c>s.byteLength)throw new Error("Destination buffer OOB write.");const n=i.subarray(r,r+c);s.set(n,a),r+=t,a+=e.destinationStride}l.push(u)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),i=this.format.includes("X")&&t.format.includes("A");if(e||i)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const n=[];for(const s of e)i.set(s.data,r),n.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:n[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return po(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(oe(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,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&&ko(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=t.crop;T&&(T=go(T,m,p));const{sx:v,sy:w,sWidth:S,sHeight:P}=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 I=f%180===0?1:y/b;e.translate(d/2,h/2),e.rotate(f*Math.PI/180),e.scale(1/I,I),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),v,w,S,P,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}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,n=e.height,[s,a]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,l=i.crop?i.crop.height:a;let c=0;2*r0?fo(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=c;p>1;p--){const e=r*q(2,p),t=n*q(2,p);f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*n,0,0,r,n),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(oe(null!==this._data),this._data instanceof so||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return Y(this,null,function*(){var t,i,r,n,s;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&ko(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const a=le(this.rotation+(null!=(t=e.rotate)?t:0)),[o,l]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=e.crop;c&&(c=go(c,o,l));const u=c?c.width:o,d=c?c.height:l,h=u/d;let f,m;void 0!==e.width&&void 0===e.height?(f=e.width,m=f/h):void 0===e.width&&void 0!==e.height?(m=e.height,f=m*h):void 0!==e.width&&void 0!==e.height?(f=e.width,m=e.height):(f=u,m=d),f=Ve(f,null!=(i=e.roundDimensionsTo)?i:1),m=Ve(m,null!=(r=e.roundDimensionsTo)?r:1);const p={width:f,height:m,fit:null!=(n=e.fit)?n:"fill",rotation:a,crop:null!=c?c:{left:0,top:0,width:o,height:l},alpha:null!=(s=e.alpha)?s:"keep"};for(const e of co){let t=e(this,p);if(ct(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=fo(p.width,p.height);return this._drawWithFitAndMipmapping(g,k,{fit:p.fit,rotation:p.rotation,crop:p.crop,targetIsFresh:y,fillBlack:"discard"===p.alpha}),new lo(g,{timestamp:this.timestamp,duration:this.duration,rotation:0})})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const co=[],uo=[];let ho=0;const fo=(e,t)=>{for(const n of uo)if(n.canvas.width===e&&n.canvas.height===t)return n.age=ho++,{canvas:n.canvas,context:n.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return uo.length>=3&&uo.splice(kt(uo,e=>e.age),1),uo.push({canvas:i,context:r,age:ho++}),{canvas:i,context:r,isNew:!0}};class mo{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(ke);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(be);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(ve);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 po=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,go=(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 oe(s>=0),oe(a>=0),{left:r,top:n,width:s,height:a}},ko=(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.")},yo=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.")}},bo=(e,t,i)=>{const r=To(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},To=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:Oe(e),oe(!1)}},vo=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=wo(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let a;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");a=t.format}else a=e.format;return Po(n,a,s)},wo=(e,t,i,r,n)=>{const s=H({},e);if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!So(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},So=(e,t)=>{if(null===e)return!0;const i=To(e);for(let r=0;r{const r=To(t),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const a=[],o=[];for(let l=0;l4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let e=0;e 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/(Bo(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*Bo(this.format);if(i.byteLength=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=Bo(r),o=Eo(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(!Ie(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&&!Io.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:n}=t;let{planeIndex:s}=t,a=this.format;const o=null!=i?i:this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,u=null!=n?n:0;if(u>=l)throw new RangeError("frameOffset out of range");const d=void 0!==r?r:l-u;if(d>l-u)throw new RangeError("frameCount out of range");const h=Bo(o),f=Eo(o);if(f&&s>=c)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?d:d*c)*h;if(e.byteLength2&&o!==a)return void Ao(this._data,p,a,o,c,s,u,d);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:d,format:o})}catch(w){if("f32-planar"===o)throw w;a="f32-planar"}}const k=_o(a),y=Bo(a),b=Eo(a);let T;if(this._data instanceof xo){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*y*(b?1:c);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)T=e(s),s=0;else{T=new Uint8Array(l*y*c);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(n,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Co({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof xo?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fo(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof xo?this._createAudioDataFromData():Fo(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Eo(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const n=Math.min(s,o),l=new Float32Array(i*n);for(let t=0;t0;){const n=Math.min(s,o),c=new Float32Array(i*n);for(let t=0;t{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")}},Eo=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_o=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)}},Ro=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,qe(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,qe(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,qe(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Fo=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Ao=(e,t,i,r,n,s,a,o)=>{const l=_o(i),c=Ro(r),u=Bo(i),d=Bo(r),h=Eo(i);if(Eo(r))if(h){const r=new ArrayBuffer(o*u),n=me(r);e.copyTo(r,{planeIndex:s,frameOffset:a,frameCount:o,format:i});for(let e=0;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.")},Oo=e=>{if(!mt(e))throw new TypeError("timestamp must be a number.")},Lo=(e,t,i)=>i.verifyKeyPackets?t.then(t=>Y(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class zo{constructor(e){if(!(e instanceof el))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return Y(this,arguments,function*(e={}){if(No(e),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return Y(this,arguments,function*(e={}){No(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;oe("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;oe("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 Tr))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 Tr))throw new TypeError("endPacket must be an EncodedPacket.");if(No(i),this._track.input._disposed)throw new gl;const r=[];let{promise:n,resolve:s}=Ae(),{promise:a,resolve:o}=Ae(),l=!1,c=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(()=>Y(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}=Ae()),yield a):(r.push(u),s(),({promise:n,resolve:s}=Ae()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{next(){return Y(this,null,function*(){for(;;){if(m.input._disposed)throw new gl;if(c)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return Y(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Uo{constructor(e,t){this.onSample=e,this.onError=t}}class qo{mediaSamplesInRange(e=-1/0,t=1/0,i){Oo(e),Oo(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=Ae(),{promise:l,resolve:c}=Ae(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g=V(H({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){var i;f=yield this._createDecoder(i=>{c(),i.timestamp>=t&&(d=!0),d?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}=Ae())))},e=>{p||(m=e,p=!0,o())});const k=this._createPacketSink(),y=null!=(i=yield k.getKeyPacket(e,g))?i:yield k.getFirstKeyPacket(g);let b=y;const T=k.packets(null!=y?y:void 0,void 0,g);for(yield T.next();b&&!d&&!this._track.input._disposed;){const e=Wo(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:l,resolve:c}=Ae()),yield l;continue}f.decode(b);const t=yield T.next();if(t.done)break;b=t.value}yield T.return(),h||this._track.input._disposed||(yield f.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{null==f||f.close()});const k=this._track,y=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return Y(this,null,function*(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new gl;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};yield a}})},return(){return Y(this,null,function*(){return h=!0,d=!0,c(),o(),y(),{value:void 0,done:!0}})},throw(e){return Y(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 Z(this,null,function*(){Symbol.iterator in e?yield*ee(e[Symbol.iterator]()):yield*ee(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=Ae(),{promise:o,resolve:l}=Ae(),c=!1,u=!1,d=null,h=null,f=!1;const m=e=>{n.push(e),a(),({promise:s,resolve:a}=Ae())},p=V(H({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){d=yield this._createDecoder(e=>{if(l(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(h=e,f=!0,a())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=()=>Y(this,null,function*(){oe(s),oe(d);let t=s;for(d.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=Ae()),yield o;if(u)break;const r=yield e.getNextPacket(t,p);oe(r),d.decode(r),t=r}g=-1}),y=()=>Y(this,null,function*(){oe(d),yield d.flush();for(let e=0;e{f||(h=e,f=!0,a())}).finally(()=>{null==d||d.close()});const g=this._track,k=()=>{for(const e of n)null==e||e.close()};return{next(){return Y(this,null,function*(){for(;;){if(g.input._disposed)throw u=!0,k(),new gl;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),h;if(n.length>0){const e=n.shift();return oe(void 0!==e),l(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};yield s}})},return(){return Y(this,null,function*(){return u=!0,l(),a(),k(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Wo=e=>0===e?40:8;class Ho extends Uo{constructor(e,t,i,r,n,s){var a,o,l,c,u,d,h,f;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const m=Mo.find(e=>e.supports(i,r));if(m)this.customDecoder=new m,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof lo))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();oe(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(at()){if("avc"===i&&this.decoderConfig.description){const e=Qt(fe(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Jt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=V(H({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=ei(t),this.decoderConfig=V(H({},this.decoderConfig),{description:Gt(e)})))}}Se(this.decoderConfig.colorSpace)||(this.decoderConfig=V(H({},this.decoderConfig),{colorSpace:{primaries:null!=(o=null==(a=this.decoderConfig.colorSpace)?void 0:a.primaries)?o:"bt709",matrix:null!=(c=null==(l=this.decoderConfig.colorSpace)?void 0:l.matrix)?c:"bt709",transfer:null!=(d=null==(u=this.decoderConfig.colorSpace)?void 0:u.transfer)?d:"bt709",fullRange:null!=(f=null==(h=this.decoderConfig.colorSpace)?void 0:h.fullRange)&&f}}))}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:(oe(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)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(oe(this.decoder),it()||Fe(this.inputTimestamps,e.timestamp,e=>e),at()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of Wt(e.data,this.decoderConfig)){const r=Ht(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Nt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&fe(t.description)[4];return Xt(e,i+1)}return Kt(e)})(t,this.decoderConfig);e=new Tr(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=mi(e.data,this.decoderConfig);t&&(e=new Tr(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new jo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();oe(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();oe(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=wi(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 ti(e,this.decoderConfig)){const i=ii(e[t.offset]);if(i===Lt.RASL_N||i===Lt.RASL_R)return!0}return!1}sampleHandler(e){if(it()){if(this.sampleQueue.length>0&&e.timestamp>=ce(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Fe(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();oe(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){return Y(this,null,function*(){const i=Ae();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){oe(this.merger);const i=yield this.merger.merge(e,t);r.sample=new lo(i)}else r.sample=new lo(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){Me(this.finalSamples,r),this.onError(n)}finally{Me(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return Y(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),yield Promise.all(this.mergeAlphaPromises),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),it()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1})}close(){var e;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,null==(e=this.merger)||e.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}let Vo=null;class jo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Vo){const e=new Blob([`(${Ko.toString()})()`],{type:"application/javascript"});Vo=URL.createObjectURL(e)}const e=qe(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=Ae();this.pendingRequests.set(i,r);const n=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,n.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Ko=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>Y(null,null,function*(){try{const e=yield r(n,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{n.close(),s.close()}}))});const r=(e,t)=>Y(null,null,function*(){const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),l=i.includes("P12"),c=r.includes("P10"),u=r.includes("P12");if(c!==o||u!==l)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return yield n(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return yield s(e,t,i);if("NV12"===i)return yield a(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)}),n=(e,t,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=new Uint8Array(4*d);yield e.copyTo(h);const f=yield o(t,c,u,1);for(let e=0,t=3;eY(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=i.includes("P10"),h=i.includes("P12"),f=d||h?2:1;let m,p;i.startsWith("I420")?(m=Math.ceil(c/2),p=Math.ceil(u/2)):i.startsWith("I422")?(m=Math.ceil(c/2),p=u):(m=c,p=u);const g=c*u,k=g*f,y=m*p*f,b=new Uint8Array(k+2*y+g*f);yield e.copyTo(b);const T=yield o(t,c,u,f),v=k+2*y;b.set(T,v);const w={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:c,codedHeight:u,timestamp:e.timestamp,duration:null!=(l=e.duration)?l:void 0,transfer:[b.buffer]};return new VideoFrame(b,w)}),a=(e,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=Math.ceil(c/2)*Math.ceil(u/2),f=e.allocationSize();t&&t.byteLength===f||(t=new Uint8Array(f)),yield e.copyTo(t);const m=new Uint8Array(d+2*h+d);m.set(t.subarray(0,d),0);const p=d,g=d+h,k=d;for(let e=0;eY(null,null,function*(){const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),yield t.copyTo(e);const a=t.format;if("RGBA"===a||"BGRA"===a||"RGBX"===a||"BGRX"===a){const t="RGBA"===a||"RGBX"===a?0:2,n=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class $o extends qo{constructor(e,t={}){if(!(e instanceof rl))throw new TypeError("videoTrack must be an InputVideoTrack.");Xo(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ot("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getRotation();let n=yield this._track.getDecoderConfig();const s=yield this._track.getTimeResolution();return oe(i&&n),n=V(H({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new Ho(e,t,i,n,r,s)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Go{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof rl))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&&ko(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&Xo(t.decoderOptions),this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._options=t,this._fit=null!=(r=t.fit)?r:"fill",this._videoSampleSink=new $o(e,t.decoderOptions),this._canvasPool=Array.from({length:null!=(n=t.poolSize)?n:0},()=>null)}_ensureInit(){var e;return null!=(e=this._initPromise)?e:this._initPromise=(()=>Y(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=go(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||nt()});oe(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&nt()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return Y(this,null,function*(){Oo(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class Qo extends Uo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const n=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(n*s)/s),e(t)},s=Do.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 Co))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{n(new Co(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(oe(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(oe(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return Y(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Yo extends Uo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,oe(Xi.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=ar(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-q(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<(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<e.getUint16(t,s)-q(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):oe(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Le(e,t,s)-q(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Le(e,t,i)<<8>>8)(e,t,s):oe(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-q(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):oe(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):oe(!1);break;default:Oe(n),oe(!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+q(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:Oe(n),oe(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=me(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=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new Co({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return Y(this,null,function*(){})}close(){}}class Jo extends qo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(ot("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getDecoderConfig();return oe(i&&r),Xi.includes(r.codec)?new Yo(e,t,r):new Qo(e,t,i,r)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Zo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Jo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return Y(this,null,function*(){Oo(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return Ue(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Ue(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class el{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof rl}isAudioTrack(){return this instanceof nl}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return Y(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return tl(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return Y(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return tl(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return Y(this,null,function*(){return this._backing.getName()})}get name(){return tl(this._backing.getName(),"name","getName")}getTimeResolution(){return Y(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return tl(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return Y(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return Y(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return Y(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return Y(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return tl(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return Y(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return Y(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return Y(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 Y(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,H({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 je(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return Y(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return Y(this,null,function*(){const i=new zo(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=te(i.packets(void 0,void 0,H({metadataOnly:!0},t)));o=!(l=yield u.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){c=[l]}finally{try{o&&(l=u.return)&&(yield l.call(u))}finally{if(c)throw c[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 Y(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return Y(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof el))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 Y(this,null,function*(){return this.input.getTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return Y(this,null,function*(){return this.input.getVideoTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return Y(this,null,function*(){return this.input.getAudioTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return Y(this,null,function*(){return this.input.getPrimaryVideoTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return Y(this,null,function*(){return this.input.getPrimaryAudioTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return Y(this,null,function*(){e&&(e=il(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=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const tl=(e,t,i)=>{if(ct(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},il=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 ct(r)?r.then(i):i(r)}:void 0};class rl extends el{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:"prores"===(yield this._backing.getCodec())})}getCodedWidth(){return Y(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return tl(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return Y(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return tl(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return Y(this,null,function*(){return this._backing.getRotation()})}get rotation(){return tl(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return Y(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return tl(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return Y(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return tl(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return Y(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=yt({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=yt({num:tl(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:tl(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return Y(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=tl(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return tl(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return Y(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=tl(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return tl(r,"displayHeight","getDisplayHeight")}getColorSpace(){return Y(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return Y(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return Y(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Mo.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))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 oe(i),wi(t,i,e.data)})}computeFrameRateMetrics(){return Y(this,arguments,function*(e={}){var t,i;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!mt(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const r=yield this.getTimeResolution(),n=null!=(t=e.targetPacketCount)?t:256,s=new zo(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=te(s.packets(void 0,void 0,{metadataOnly:!0}));c=!(u=yield h.next()).done;c=!1){const e=u.value;if(a.length>=n&&e.timestamp>=o)break;a.push(e.timestamp),o=Math.max(o,e.timestamp),l++}}catch(u){d=[u]}finally{try{c&&(u=h.return)&&(yield u.call(h))}finally{if(d)throw d[0]}}const f=new Float64Array(a.length);for(let R=0;Re-t),I=S-1>>1,x=S>>1;let C=0,B=0,E=0;for(const R of P)if(E+=b.get(R),0===C&&E>I&&(C=R),E>x){B=R;break}const _=(k/C+k/B)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:hl(_),minFrameRate:k/v,maxFrameRate:k/T,averageFrameRate:k*S/w,medianFrameRate:_,frameRateIsConstant:null!==g&&1===T&&1===v,probedPacketCount:l}})}}class nl extends el{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(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 Y(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return tl(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return Y(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return tl(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Do.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 Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const sl=e=>-(null!=e?e:-1/0),al=e=>-e,ol=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 ct(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return ct(r)?r.then(i):i(r)}:void 0}},ll=(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 ct(s)?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 ct(o)||ct(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),cl=(e,t)=>Y(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=>ct(e))){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=>ct(e))?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;oe.track)}),ul=(e,t)=>{const i=1e6,r=1+1e-9,n=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let v=1;v0))return null;s[v-1]=t}const a=s.slice();a.sort();let o=a[Math.floor(.05*a.length)];for(let v=0;v<6;v++){let e=0,t=0;for(const n of s){const i=Math.max(1,Math.round(n/o));Math.abs(n-i*o)>=r||(e+=n,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let l=0,c=0,u=0;for(const v of s){const e=Math.max(1,Math.round(v/o));Math.abs(v-e*o)>=r||(l++,c+=v,u+=e)}if(l/s.length<.98)return null;o=c/u;const d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const v of n){if(vp)continue;const e=Math.abs(v/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,n=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof Ea)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ea||e.source instanceof ta))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ea&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof ml))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=null!=(t=e.initInput)?t:null,this._formatOptions=null!=(i=e.formatOptions)?i:{},e.source instanceof ea?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return Y(this,null,function*(){oe(this._rootSource instanceof ia);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&&ra(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ra(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>Y(this,null,function*(){const i=yield this._getSourceUncached(e);if(gt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=kt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);oe(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),Me(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);oe(-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=(()=>Y(this,null,function*(){var e;this._reader=new kl(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 pl}))()}get source(){return this._rootSource}getFormat(){return Y(this,null,function*(){return yield this._getDemuxer(),oe(this._format),this._format})}canRead(){return Y(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof pl)return!1;throw e}})}getFirstTimestamp(e){return Y(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._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>{var t;return null!=(t=null==e?void 0:e.timestamp)?t:1/0}));return r===1/0?0:r})}computeDuration(e,t){return Y(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 Y(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 Y(this,null,function*(){e&&(e=ol(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return cl(t,e)})}getVideoTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return cl(t,e)})}getAudioTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return cl(t,e)})}getPrimaryVideoTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=ll(e,{sortBy:e=>Y(null,null,function*(){return[al((yield e.getDisposition()).default),al(yield e.hasPairableAudioTrack()),al(!(yield e.hasOnlyKeyPackets())),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=yield this.getPrimaryVideoTrack(),r=ll(e,{sortBy:e=>Y(this,null,function*(){return[al(!i||e.canBePairedWith(i)),al((yield e.getDisposition()).default),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return Y(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 rl(this,e):new nl(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class pl extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class gl extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class kl{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 gl;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 yl(t,me(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Zs);return ct(r)?r.then(t=>t?new yl(t.bytes,t.view,t.offset,e,i):null):r?new yl(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new gl;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(oe(null!==this.fileSizeNonStrict),this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i)));return ct(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>Y(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(ct(i)&&(i=yield i),!i||0===i.length)break;const r=Tl(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return new yl(i,me(i),0,0,t)}))()}}class yl{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 yl(e,me(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new yl(this.bytes,this.view,this.offset,e,e+t)}}const bl=(e,t)=>{if(e.filePose.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.`)},Tl=(e,t)=>{bl(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},vl=e=>(bl(e,1),e.view.getUint8(e.bufferPos++)),wl=(e,t)=>{bl(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Sl=e=>{bl(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Pl=e=>{bl(e,3);const t=Le(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Il=e=>{bl(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},xl=(e,t)=>{bl(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Cl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Bl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},El=e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},_l=(e,t)=>{let i,r;return t?(i=xl(e,!0),r=xl(e,!0)):(r=xl(e,!1),i=xl(e,!1)),4294967296*r+i},Rl=e=>4294967296*Cl(e)+Cl(e),Fl=e=>4294967296*El(e)+Cl(e),Al=e=>{const t=Bl(e),i=(e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Ml=e=>{bl(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Dl=e=>{bl(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Nl=(e,t)=>{bl(e,t);let i="";for(let r=0;rpe.decode(Tl(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 Ll,zl,Ul,ql;(zl=Ll||(Ll={}))[zl.Unsynchronisation=128]="Unsynchronisation",zl[zl.ExtendedHeader=64]="ExtendedHeader",zl[zl.ExperimentalIndicator=32]="ExperimentalIndicator",zl[zl.Footer=16]="Footer",(ql=Ul||(Ul={}))[ql.ISO_8859_1=0]="ISO_8859_1",ql[ql.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",ql[ql.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",ql[ql.UTF_8=3]="UTF_8";const Wl=128,Hl=10,Vl=["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"],jl=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Tl(e,Wl-3)),e.filePos=r;const n=Kl(e,30);n&&(null!=t.title||(t.title=n));const s=Kl(e,30);s&&(null!=t.artist||(t.artist=s));const a=Kl(e,30);a&&(null!=t.album||(t.album=a));const o=Kl(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Tl(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=Kl(e,28),e.skip(2)}else e.skip(-30),u=Kl(e,30);u&&(null!=t.comment||(t.comment=u));const d=vl(e);d{const i=Tl(e,t),r=ut(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Nl(e,3),r=vl(e),n=vl(e),s=vl(e),a=Cl(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=mr(a);return s&Ll.Footer&&(o+=Hl),{majorVersion:r,revision:n,flags:s,size:o}},$l=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void Pt._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Ll.Footer?t.size-Hl:t.size,u=Tl(e,c),d=new Gl(t,u);if(t.flags&Ll.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Ll.ExtendedHeader){const e=d.readU32();3===t.majorVersion?d.pos+=e:d.pos+=e-4}for(;d.pos<=d.bytes.length-d.frameHeaderSize();){const e=d.readId3V2Frame();if(!e)break;const c=d.pos,u=d.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&Ll.Unsynchronisation)),h)Pt._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)Pt._warn(`Skipping compressed ID3v2 frame ${e.id}`),d.pos=u;else{if(m&&d.ununsynchronizeRegion(d.pos,u),null!=i.raw||(i.raw={}),"TXXX"===e.id){const e=null!=(n=(r=i.raw).TXXX)?n:r.TXXX={},t=d.readId3V2TextEncoding(),s=d.readId3V2Text(t,u),a=d.readId3V2Text(t,u);null!=e[s]||(e[s]=a)}else"T"===e.id[0]?null!=(s=i.raw)[a=e.id]||(s[a]=d.readId3V2EncodingAndText(u)):null!=(o=i.raw)[l=e.id]||(o[l]=d.readBytes(e.size));switch(d.pos=c,e.id){case"TIT2":case"TT2":null!=i.title||(i.title=d.readId3V2EncodingAndText(u));break;case"TIT3":case"TT3":null!=i.description||(i.description=d.readId3V2EncodingAndText(u));break;case"TPE1":case"TP1":null!=i.artist||(i.artist=d.readId3V2EncodingAndText(u));break;case"TALB":case"TAL":null!=i.album||(i.album=d.readId3V2EncodingAndText(u));break;case"TPE2":case"TP2":null!=i.albumArtist||(i.albumArtist=d.readId3V2EncodingAndText(u));break;case"TRCK":case"TRK":{const e=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}null!=i.genre||(i.genre=e)}break;case"TDRC":case"TDAT":{const e=d.readId3V2EncodingAndText(u),t=new Date(e);Number.isNaN(t.getTime())||null!=i.date||(i.date=t)}break;case"TYER":case"TYE":{const e=d.readId3V2EncodingAndText(u),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=i.date||(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.lyrics||(i.lyrics=d.readId3V2Text(e,u))}break;case"COMM":case"COM":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.comment||(i.comment=d.readId3V2Text(e,u))}break;case"APIC":case"PIC":{const e=d.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=d.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=d.readId3V2Text(e,u);const n=d.readU8(),s=d.readId3V2Text(e,u).trimEnd(),a=u-d.pos;if(a>=0){const e=d.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:d.pos+=e.size}d.pos=u}}};class Gl{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{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:mr(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 Ul.ISO_8859_1:{let e="";for(let t=0;t0===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=ut(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=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}case Ul.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=ut(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 Ul.UTF_8:{const e=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ql{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch(n){i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(s){try{null==r||r.disconnect()}catch(a){console.warn("MediaBunny gain setup cleanup:",a)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),s}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{null==t||t.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Yl{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(n){r=!0,i=n}try{e.disconnect()}catch(n){r||(r=!0,i=n)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const n=function(e,t,i,r){const n=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(n+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(n,r),offset:n=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===n.offset?s.start(n.startAt):s.start(n.startAt,n.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,n.endMediaTime)}catch(a){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw a}}}const Jl=Symbol("cancelled");class Zl{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Jl);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function ec(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class tc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}stopIterator(){return Y(this,null,function*(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),yield t})}cancel(){var e;null==(e=this.task)||e.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}run(e){return Y(this,null,function*(){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Zl;this.task=r;let n=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!n||this.host.audioIterator===n);try{for(n=t.buffers(this.host.currentTime),this.host.audioIterator=n;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=yield r.wait(n.next());if(i===Jl||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if((yield r.wait(this.contexts.resume(i)))===Jl||!s())return;ec(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(yield r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(yield r.delay(50))||!s())return}}catch(a){if(s())throw a}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}})}}class ic{constructor(e,d){X(this,u),X(this,t,!1),X(this,i,0),X(this,r),X(this,n),X(this,s),X(this,a,null),X(this,o,null),X(this,l,null),X(this,c),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,$(this,r,new Ql(this)),$(this,n,new Yl(this)),$(this,s,new tc(this,K(this,r),K(this,n))),$(this,c,d)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){K(this,r).ensure(e)}updateGain(){K(this,r).updateGain()}stopQueuedNodes(){K(this,n).stop()}stopIterator(){return Y(this,null,function*(){yield K(this,s).stopIterator()})}handleNoAudioTrack(){K(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){Q(this,i)._++;try{this.pause()}finally{$(this,l,null),this.input=null,this.audioSink=null}}load(e,r){return Y(this,null,function*(){if(K(this,t))return;this.cancelPending();const n=K(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>G(this,u,d).call(this,e,n,r));$(this,l,s);try{yield s}finally{K(this,l)===s&&$(this,l,null)}})}runIterator(e){return Y(this,null,function*(){K(this,t)||(yield K(this,s).run(e))})}play(){return Y(this,null,function*(){if(K(this,t))return;if(K(this,o))return K(this,o);if(!this.paused)return;const e=new Zl;$(this,a,e);const r=K(this,i),n=G(this,u,f).call(this,e,r);$(this,o,n);try{yield n}finally{K(this,a)===e&&($(this,a,null),$(this,o,null))}})}pause(){var e;this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,null==(e=K(this,a))||e.cancel(),$(this,a,null),$(this,o,null),K(this,s).cancel(),this.stopQueuedNodes()}seek(e){return Y(this,null,function*(){var i,r;if(K(this,t))return;const n=!this.paused;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.latestScheduledEndTime=this.playbackTimeAtStart;const a=++this.asyncId;n&&G(this,u,h).call(this,a)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){var i,r;if(K(this,t)||e===this.playbackRate)return;const n=this.currentTime;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=n,this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.playbackRate=e,this.latestScheduledEndTime=n;const a=++this.asyncId;this.paused||G(this,u,h).call(this,a)}destroy(){if(K(this,t))return;$(this,t,!0),Q(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>K(this,r).destroy()])try{t()}catch(n){e.push(n)}if(this.input=null,this.audioSink=null,$(this,l,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakSet,d=function(e,r,n){return Y(this,arguments,function*({input:e,audioTrack:r,duration:n},s,a){const o=()=>!K(this,t)&&K(this,i)===s;if(o()){this.input=e,this.duration=n;try{const e=r&&null!==r.codec&&(yield r.canDecode());if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new Zo(r)}else this.handleNoAudioTrack();o()&&(null==a||a())}catch(l){if(o())throw l}}})},h=function(e){this.runIterator(e).catch(i=>{if(!K(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{K(this,c)?K(this,c).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=function(e,n){return Y(this,null,function*(){const s=()=>!K(this,t)&&!e.cancelled&&K(this,i)===n;try{const t=K(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if((yield e.wait(K(this,r).resume(t)))===Jl||!s())return}if(K(this,l)){if((yield e.wait(K(this,l)))===Jl||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,G(this,u,h).call(this,++this.asyncId)}catch(a){if(s())throw a}})};const rc=new WeakMap;function nc(e,t,i){return Y(this,null,function*(){var r;const{input:n,loadSeq:s}=e;if(!(null==(r=e.media)?void 0:r.isHls)||!n||e.destroyed)return;const a={};rc.set(e,a);const o=()=>!e.destroyed&&e.loadSeq===s&&e.input===n&&rc.get(e)===a;for(;o();){const r=e.media;if(!(null==r?void 0:r.isHls))return;let s;try{s=yield i(n,r,t,o)}catch(l){if(!o())return;if(e.media===r)throw l;continue}if(!o())return;if(e.media===r){if(s)try{yield e.replaceTracks(s)}catch(l){if(o())throw l}return}}})}function sc(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getVideoTracks();if(!r())return null;const a="auto"===i?yield e.getPrimaryVideoTrack():null!=(n=s.find(e=>e.id===i))?n:t.videoTrack;if(!r()||!a)return null;let o=t.audioTrack,l=t.audioMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableAudioTrack(),l="auto"),{videoTrack:a,audioTrack:o,videoMode:"auto"===i?"auto":"manual",audioMode:l}})}function ac(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getAudioTracks();if(!r())return null;const a="auto"===i?t.videoTrack?yield t.videoTrack.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack():null!=(n=s.find(e=>e.id===i))?n:t.audioTrack;if(!r()||!a)return null;let o=t.videoTrack,l=t.videoMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableVideoTrack(),l="auto"),{videoTrack:o,audioTrack:a,videoMode:l,audioMode:"auto"===i?"auto":"manual"}})}function oc(e){return Y(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const lc=/\.m3u8(?:$|[?#])/i;function cc(e){return"string"===typeof e&&lc.test(e)}function uc(e){const t=function(e){return"string"===typeof e?new ua(e):e instanceof Blob?new aa(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new fa(e):null!=e?e:null}(e);return t?new ml({source:t,formats:cc(e)?eo:Za}):null}class dc{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){var e;return null==(e=this.controller)?void 0:e.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}wait(e,t){return Y(this,null,function*(){try{yield Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}})}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,null==e||e.dispose()}cancel(){var e;if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),null==(e=this.controller)||e.abort(),this.disposeInput()}}}function hc(e){return Y(this,arguments,function*({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),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 fc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class mc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return V(H({},fc()),{source:this.host.loadSeq,complete:fc()})}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,null==e||e.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,null==e||e.complete.resolve(),null==e||e.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}runPlay(e){return Y(this,null,function*(){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(yield this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,yield this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),ec(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}})}seek(e,t){return this.position(t=>Y(this,null,function*(){const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();yield Promise.all([i,r])}),["seeked"],!1,t)}replace(e,t){return this.position(i=>Y(this,null,function*(){e.duration=yield hc(e),i()&&(this.host.media=e,yield Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(yield Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))}),["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=null!=r?r:this.seeking?this.wanted:!this.host.paused,this.cancelPlay();const n=this.seeking,s=this.operation();return this.seeking=s,null==n||n.complete.resolve(),null==n||n.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}runPosition(e,t,i,r){return Y(this,null,function*(){const n=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!n())return;if(this.host.ended=!1,this.host.seeking=!0,ec(this.host.events,n,["seeking","waiting"]),!n())return;if(r||this.stop(),!n())return;if(yield t(n),!n())return;if(this.host.seeking=!1,e.complete.resolve(),ec(this.host.events,n,i),!n())return;this.seeking=null,s=this.wanted}catch(a){if(!n())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(a),a}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&(yield this.play())})}}const pc=new WeakMap,gc=new WeakMap;function kc(e){const t=gc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>{var t;return null!=(t=e.value)?t:null});gc.set(e,i);const r=()=>{gc.get(e)===i&&gc.delete(e)};return i.then(r,r),i}function yc(e,t,i,r,n){const s=i?Math.max(.06,r/Math.max(1,n)):0;return i&&e{if(this.image===n&&t()){this.cancel();try{i(n)}catch(e){r(e)}}},n.onerror=()=>{this.image===n&&this.cancel()},n.src=e}}class Tc{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}update(e){return Y(this,null,function*(){var t;const i=this.host.videoIterator;if(!i||!this.ready()||!this.current(e)||this.host.isFetching)return;const r={};this.fetching=r,this.host.isFetching=!0;const n=()=>this.current(e)&&this.host.videoIterator===i;try{for(;n();){const e=yield kc(i);if(!n()||!e)return;const r=null==(t=this.host.audioClock)?void 0:t.currentTime;if(void 0===r)return;const s=yc(e.timestamp,r,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==s){if("draw"!==s)return void(this.host.nextFrame=e);this.draw(e)}}}catch(s){if(n())throw s}finally{this.fetching===r&&(this.fetching=null,this.host.isFetching=!1)}})}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void ec(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(ec(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!K(this,T),e=>G(this,P,E).call(this,e,!0),e=>G(this,P,C).call(this,e)))}preflight(e,t,i){return Y(this,null,function*(){return function(e,t,i,r,n=()=>!0){return Y(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||cc(e))return!0;try{const t=yield fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if((null==r?void 0:r.aborted)||!n())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!((null==r?void 0:r.aborted)||!n())&&(console.warn("Preflight check failed:",s),!0)}})}(e,this.preflightRange,this.events,t,i)})}drawPoster(){if(K(this,b)||!this.poster||this.posterDrawn)return;const e=K(this,m);K(this,v).draw(this.poster,()=>G(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,G(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>G(this,P,C).call(this,e))}stopIterator(){return Y(this,null,function*(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,yield function(e){if(!e)return Promise.resolve();const t=pc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return pc.set(e,i),i}(e)})}clear(){G(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){Q(this,m)._++,Q(this,p)._++,this.stop(),G(this,P,B).call(this),K(this,v).cancel(),$(this,T,!1),$(this,g,null),$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null}load(e,t){return Y(this,null,function*(){if(K(this,b))return;this.cancelPending();const i=K(this,m),r=K(this,p);$(this,T,!0);const n=Promise.resolve().then(()=>G(this,P,_).call(this,e,i,r,t));$(this,g,n);try{yield n}finally{K(this,g)===n&&$(this,g,null)}})}handleNoVideoTrack(){K(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}resetIterator(e){return Y(this,null,function*(){if(K(this,b))return;const t=K(this,m),i=++Q(this,p)._,r=K(this,g);this.stop(),K(this,v).cancel(),$(this,T,!0);try{r&&(yield r),yield G(this,P,R).call(this,e,t,i)}catch(n){if(G(this,P,I).call(this,t)&&K(this,p)===i)throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})}updateNextFrame(e){return Y(this,null,function*(){yield K(this,w).update(e)})}render(){K(this,w).render()}start(e){K(this,w).start(e)}stop(){K(this,w).stop()}seek(e){return Y(this,null,function*(){yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){K(this,b)||($(this,b,!0),Q(this,m)._++,K(this,w).destroy(),K(this,v).cancel(),G(this,P,B).call(this),this.posterDrawn=!1,$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,T=new WeakMap,v=new WeakMap,w=new WeakMap,S=new WeakMap,P=new WeakSet,I=function(e){return!K(this,b)&&K(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){K(this,b)||(G(this,P,B).call(this),K(this,S)?K(this,S).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){K(this,v).cancel(),t&&this.clear(),G(this,P,x).call(this).drawImage(e.canvas,0,0)},_=function(e,t,i,r){return Y(this,null,function*(){if(G(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:n,videoTrack:s,duration:a}=e;if(this.input=n,this.duration=a,!s)return this.handleNoVideoTrack(),void(null==r||r());const o=null!==s.codec&&(yield s.canDecode());if(!G(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void(null==r||r());const l=yield s.canBeTransparent();if(!G(this,P,I).call(this,t))return;$(this,k,()=>new Go(s,{poolSize:2,fit:"contain",alpha:l})),this.videoSink=K(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==r||r(),G(this,P,I).call(this,t)&&(yield G(this,P,R).call(this,0,t,i))}catch(n){if(G(this,P,I).call(this,t))throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})},R=function(e,t,i){return Y(this,null,function*(){if(!G(this,P,I).call(this,t)||K(this,p)!==i)return;G(this,P,B).call(this),K(this,k)&&this.videoSink===K(this,y)&&(this.videoSink=K(this,k).call(this));const r=this.videoSink;if(!r||!G(this,P,I).call(this,t))return;$(this,y,r);const n=r.canvases(e);this.videoIterator=n;const s=()=>G(this,P,I).call(this,t)&&K(this,p)===i&&this.videoIterator===n,a=yield kc(n);if(!s())return;const o=yield kc(n);s()&&(this.nextFrame=o,a?G(this,P,E).call(this,a,!1):this.drawPoster())})};class wc{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l;X(this,F),this.events=i,this.option=r,this.audio=new ic(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new vc({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,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,$(this,F,new mc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,K(this,F).ended(),this.audio.pause())})}load(e){return Y(this,null,function*(){var t,i;if(this.destroyed)return;const r=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),null==(t=this.loadSession)||t.cancel(),r!==this.loadSeq||this.destroyed)return;if(this.pause(),r!==this.loadSeq||this.destroyed)return;this.disposeInput();const n=new dc;this.loadSession=n,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,n.defer(()=>this.events.emit("waiting")),n.defer(()=>this.events.emit("loadstart"));const s=Number.isFinite(this.option.loadTimeout)&&null!=(i=this.option.loadTimeout)?i:0;try{yield n.wait(this.performLoad(e,r,n),s)}catch(a){if(r!==this.loadSeq)return;const e=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),n.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}})}performLoad(e,t){return Y(this,arguments,function*(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(yield this.video.preflight(e,i.signal,r))||!r())return;const n=uc(e);if(!n)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(n);const s=yield function(e,t){return Y(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield hc({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=cc(t);return{input:e,videoTrack:i,audioTrack:r,duration:n,isLive:!Number.isFinite(n)&&Boolean(s&&(yield s.isLive())),isHls:a,videoMode:a?"auto":"manual",audioMode:a?"auto":"manual"}})}(n,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=n,this.media=s;const a=function(e,t){let i=!1,r=!1,n=!1;function s(s){t()&&!n&&("video"===s?i=!0:r=!0,i&&r&&(n=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,ec(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,a.video),t=r()?this.audio.load(s,a.audio):Promise.resolve();if(yield Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,ec(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}})}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){var e;null==(e=this.loadSession)||e.disposeInput(),this.input=null,this.media=null}replaceTracks(e){return Y(this,null,function*(){if(this.media&&!this.destroyed)return K(this,F).replace(H(H({},this.media),e),this.currentTime)})}selectHlsQuality(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,sc)}(this,e)})}selectHlsAudio(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,ac)}(this,e)})}getHlsState(){return Y(this,null,function*(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=yield function(e){return Y(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)=>Y(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield oc(e)}}))),Promise.all(a.map((e,t)=>Y(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 oc(e)}})))]);return{levels:o,audios:l,currentLevel:e.videoTrack&&null!=(t=o.find(t=>{var i;return t.id===(null==(i=e.videoTrack)?void 0:i.id)}))?t:null,currentAudio:e.audioTrack&&null!=(i=l.find(t=>{var i;return t.id===(null==(i=e.audioTrack)?void 0:i.id)}))?i:null,videoMode:null!=(r=e.videoMode)?r:"auto",audioMode:null!=(n=e.audioMode)?n:"auto"}})}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}})}play(){return Y(this,null,function*(){return K(this,F).play()})}pause(){K(this,F).pause()}seek(e){return Y(this,null,function*(){return K(this,F).seek(e)})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,K(this,F).invalidate();const e=[];for(const i of[()=>{var e;return null==(e=this.loadSession)?void 0:e.cancel()},()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){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}}F=new WeakMap;const Sc=new WeakMap;function Pc(e){let t=Sc.get(e);return t||(t={closed:!1,frames:new Set},Sc.set(e,t)),t}class Ic{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new ae,this.engine=new wc({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){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=Pc(e);if(i.closed)return 0;const r=requestAnimationFrame(n=>{i.frames.delete(r),i.closed||t(n,{presentationTime:e.engine.currentTime,expectedDisplayTime:n+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:n,receiveTime:n,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){Pc(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=Pc(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,n=r("canvas"),s=n.getContext("2d"),a=new Ic({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),se({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A=Object.defineProperty,M=Object.defineProperties,D=Object.getOwnPropertyDescriptors,N=Object.getOwnPropertySymbols,O=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable,z=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),U=e=>{throw TypeError(e)},q=Math.pow,W=(e,t,i)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,H=(e,t)=>{for(var i in t||(t={}))O.call(t,i)&&W(e,i,t[i]);if(N)for(var i of N(t))L.call(t,i)&&W(e,i,t[i]);return e},V=(e,t)=>M(e,D(t)),j=(e,t,i)=>t.has(e)||U("Cannot "+i),K=(e,t,i)=>(j(e,t,"read from private field"),i?i.call(e):t.get(e)),X=(e,t,i)=>t.has(e)?U("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),$=(e,t,i,r)=>(j(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),G=(e,t,i)=>(j(e,t,"access private method"),i),Q=(e,t,i,r)=>({set _(r){$(e,t,r,i)},get _(){return K(e,t,r)}}),Y=(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())}),J=function(e,t){this[0]=e,this[1]=t},Z=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof J,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?n("return"===e?e:"next",t[1]?{done:i.done,value:i.value}:i,r,s):r({value:i,done:l})).catch(e=>n("throw",e,r,s))}catch(c){s(c)}},s=(e,t,i,s)=>a[e]=a=>(t=new Promise((t,i,s)=>(s=()=>n(e,a,t,i),r?r.then(s):s())),s=()=>r===i&&(r=0),r=i=t.then(s,s),t),a={};return i=i.apply(e,t),a[z("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},ee=e=>{var t,i=e[z("asyncIterator")],r=!1,n={};return null==i?(i=e[z("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 J(new Promise(r=>{var n=i[e](t);n instanceof Object||U("Object expected"),r(n)}),1)}}),n[z("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},te=(e,t,i)=>(t=e[z("asyncIterator")])?t.call(e):(e=e[z("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 ie(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function re(e,t,i){const r={control:!1,setting:!1};let n=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function a(){n=null,ie([()=>s("control"),()=>s("setting")])}return{update:function(o,l,c,u){if(!o)return void a();n=o;const d=()=>n===o&&c(),h=e=>Y(null,null,function*(){return d()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html});l.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:h})):s("control"),d()&&(l.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:h})):s("setting"))},clear:a}}function ne(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function se({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,n=0,s=0;const a=re(e,"mediabunny-quality",''),o=re(e,"mediabunny-audio",''),l=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;function c(){return Y(this,null,function*(){var e,s;if(r||t.engine.destroyed)return;const c=++n,d=t.engine.loadSeq,h=()=>c===n&&l(d);try{const r=yield t.getM3u8State();if(!h())return;const n=(null==(e=i.m3u8)?void 0:e.quality)||{},c=function(e,t,i){var r;if(!t.control&&!t.setting||!(null==e?void 0:e.levels.length))return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||`${e.height}P`),a=e.currentLevel?s(e.currentLevel):n,o=[];for(const u of e.levels){if(!i())return null;o.push({html:s(u),value:u.id,default:(null==(r=e.currentLevel)?void 0:r.id)===u.id})}const l=new Map(e.levels.map(e=>[e.id,e.height])),c=ne(o).sort((e,t)=>("auto"===t.value?0:l.get(t.value)||0)-("auto"===e.value?0:l.get(e.value)||0));return c.push({html:n,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:a,selector:c}}(r,n,h);if(!h())return;if(a.update(c,n,()=>l(d),(e,t)=>u("quality",e,t)),!h())return;const f=(null==(s=i.m3u8)?void 0:s.audio)||{},m=function(e,t,i){var r;if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||e.lang||e.language),a=e.currentAudio?s(e.currentAudio):n,o=[];for(const c of e.audios){if(!i())return null;o.push({html:s(c),value:c.id,default:(null==(r=e.currentAudio)?void 0:r.id)===c.id})}const l=ne(o);return l.push({html:n,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:a,selector:l}}(r,f,h);h()&&o.update(m,f,()=>l(d),(e,t)=>u("audio",e,t))}catch(f){if(h())throw f}})}function u(i,r,a){return Y(this,null,function*(){const o=++s,u=t.engine.loadSeq;n++;const h=()=>o===s&&l(u);try{"quality"===i?yield t.switchM3u8Quality(r.value):yield t.switchM3u8Audio(r.value),h()&&(yield c(),h()&&(e.notice.show=`${a}: ${r.html}`))}catch(f){if(h()&&(yield d(),h()))throw f}return r.html})}function d(){return c().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function h(){n++,s++;try{ie([a.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}function f(){if(!r){r=!0,h();try{ie([()=>e.off("video:loadedmetadata",d),()=>e.off("restart",d),()=>e.off("video:loadstart",h),()=>e.off("video:error",h),()=>e.off("destroy",f)])}catch(t){console.warn("MediaBunny HLS listener cleanup:",t)}}}try{e.on("video:loadedmetadata",d),e.on("restart",d),e.on("video:loadstart",h),e.on("video:error",h),e.on("destroy",f)}catch(m){throw f(),m}return{update:c,destroy:f}}class ae{constructor(){X(this,e,!1),this.listeners=new Map}addEventListener(t,i){var r;K(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),null==(r=this.listeners.get(t))||r.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){var r;if(K(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{K(this,e)||t(n)})}destroy(){$(this,e,!0),this.listeners.clear()}}function oe(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const le=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},ce=e=>e&&e[e.length-1],ue=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-q(2,r))},he=e=>{const t=ue(e);return 0===(1&t)?-(t>>1):t+1>>1},fe=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),me=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),pe=new TextDecoder,ge=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),ke={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ye=ge(ke),be={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Te=ge(be),ve={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},we=ge(ve),Se=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,Pe={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Ie=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class xe{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return Y(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 Ce=/^[0-9a-fA-F]+$/,Be=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),Ee=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,_e=(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{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},Fe=(e,t,i)=>{const r=Re(e,i(t),i);e.splice(r+1,0,t)},Ae=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},Me=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},De=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},Ne=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Oe=e=>{throw new Error(`Unexpected value: ${e}`)},Le=(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},ze=(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)},Ue=(e,t)=>({next(){return Y(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}}),qe=(e,t,i)=>Math.max(t,Math.min(i,e)),We="und",He=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Ve=(e,t)=>Math.round(e/t)*t,je=(e,t)=>Math.round(e*t)/t,Ke=(e,t)=>Math.floor(e/t)*t,Xe=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},$e=/^[a-z]{3}$/,Ge=e=>$e.test(e),Qe=1e6*(1+Number.EPSILON),Ye=(e,t)=>{const i=H(H({},e),t);if(e.headers||t.headers){const r=e.headers?Je(e.headers):{},n=t.headers?Je(t.headers):{},s=H({},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},Je=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},Ze=(e,t,i,r,n)=>Y(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(Pt._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 Tt(1e3*e)),n())throw a}});class et{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let tt=null;const it=()=>{var e;return null!==tt?tt:tt=!("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 rt=null;const nt=()=>{var e;return null!==rt?rt:rt="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let st=null;const at=()=>{var e;return null!==st?st:st=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},ot=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,lt=Y(null,null,function*(){}).constructor,ct=e=>e instanceof lt||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),ut=(e,t)=>-1!==e?e:t,dt=(e,t,i,r)=>e<=r&&i<=t,ht=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},mt=e=>"number"===typeof e&&!Number.isNaN(e),pt=(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("/")},gt=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{oe(Number.isInteger(e.num)),oe(Number.isInteger(e.den)),oe(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}},bt=(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.`)},Tt=e=>new Promise(t=>setTimeout(t,e));class vt{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)}}}var wt,St;(St=wt||(wt={}))[St.Silent=0]="Silent",St[St.Errors=1]="Errors",St[St.Warnings=2]="Warnings",St[St.Info=3]="Info";class Pt{constructor(){}static get level(){return Pt._level}static set level(e){if(e!==wt.Silent&&e!==wt.Errors&&e!==wt.Warnings&&e!==wt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Pt._level=e}static get _emitter(){var e;return null!=(e=Pt._emitterInstance)?e:Pt._emitterInstance=new vt}static on(e,t,i){return Pt._emitter.on(e,t,i)}static _error(...e){Pt._emitter._emit("error",e),Pt._level>=wt.Errors&&console.error(...e)}static _warn(...e){Pt._emitter._emit("warn",e),Pt._level>=wt.Warnings&&console.warn(...e)}static _info(...e){Pt._emitter._emit("info",e),Pt._level>=wt.Info&&console.info(...e)}}Pt._level=wt.Info,Pt._emitterInstance=null;class It{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 xt{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 Ct={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Bt{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;return this.pos++,n}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}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 Bt(this.bytes);return e.pos=this.pos,e}}const Et=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],_t=[-1,1,2,3,4,5,6,8],Rt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Bt(e),i=Ft(t),{frequencyIndex:r,sampleRate:n}=At(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=_t[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=At(t).sampleRate,o=Ft(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Ft(t)&&t.readBits(1)&&(c=At(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(l=!!t.readBits(1)));break}t.pos=e+1}return null!==a&&a>1&&(l=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:c,outputNumberOfChannels:l&&1===a?2:a}},Ft=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},At=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let n=0;t+3i&&(yield{offset:i,length:t-i}),i=t+n,t=i):t++}-1!==i&&i{if(t.description){const i=3&fe(t.description)[4];return qt(e,i+1)}return Ut(e)},Ht=e=>31&e,Vt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+jt.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(jt,r),r+=jt.byteLength,i.set(n,r),r+=n.byteLength;return i},Xt=(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:ze(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},$t=e=>{try{const t=[],i=[],r=[];for(const o of Ut(e)){const n=e.subarray(o.offset,o.offset+o.length),s=Ht(n[0]);s===Nt.SPS?t.push(n):s===Nt.PPS?i.push(n):s===Nt.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=Jt(n);oe(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 Pt._error("Error building AVC Decoder Configuration Record:",t),null}},Gt=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=me(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{var t;try{const i=Vt(e),r=new Bt(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();ue(r);let o=1,l=0,c=0,u=0;if(100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n){o=ue(r),3===o&&(u=r.readBits(1)),l=ue(r),c=ue(r),r.skipBits(1);if(r.readBits(1))for(let e=0;e<(3!==o?8:12);e++){if(r.readBits(1)){const t=e<6?16:64;let i=8,n=8;for(let e=0;ee.level>=a))?t:ce(Gi),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);P=n,I=n}else P=0,I=0}return oe(null!==I),{emulationUnpreventedBytes:i,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:o,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:k,pixelAspectRatio:S,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:w,numReorderFrames:P,maxDecFrameBuffering:I,vuiParametersFlagBitOffset:B,bitstreamRestrictionFlagBitOffset:x,bitstreamRestrictionFlag:C}}catch(i){return Pt._error("Error parsing AVC SPS:",i),null}},Zt=e=>{const t=ue(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)ue(e),ue(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},ei=e=>{oe(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Bt(e.emulationUnpreventedBytes),r=new Bt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(oe(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),de(r,2),de(r,1),de(r,16),de(r,16),de(r,e.numReorderFrames),de(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return oe(Number.isInteger(n)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,n))},ti=(e,t)=>{if(t.description){const i=3&fe(t.description)[21];return qt(e,i+1)}return Ut(e)},ii=e=>e>>1&63,ri=e=>{try{const t=new Bt(Vt(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}=si(t,i);ue(t);const u=ue(t);let d=0;3===u&&(d=t.readBits(1));const h=ue(t),f=ue(t);let m=h,p=f;if(t.readBits(1)){const e=ue(t),i=ue(t),r=ue(t),n=ue(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=ue(t),k=ue(t);ue(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)ue(t),b=ue(t),ue(t);ue(t),ue(t),ue(t),ue(t),ue(t),ue(t),t.readBits(1)&&t.readBits(1)&&ai(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),ue(t),ue(t),t.skipBits(1));const T=ue(t);if(oi(t,T),t.readBits(1)){const e=ue(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of Ut(e)){const s=e.subarray(l.offset,l.offset+l.length),a=ii(s[0]);a===Lt.VPS_NUT?t.push(s):a===Lt.SPS_NUT?i.push(s):a===Lt.PPS_NUT?r.push(s):a!==Lt.PREFIX_SEI_NUT&&a!==Lt.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=ri(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Bt(Vt(e));t.skipBits(16),ue(t),ue(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),ue(t),ue(t),he(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&ue(t),he(t),he(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:Lt.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Lt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Lt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ii(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 Pt._error("Error building HEVC Decoder Configuration Record:",t),null}},si=(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;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&he(e);for(let t=0;t{const i=[];for(let r=0;r{var n;let s=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){if(t===i){o=t-(ue(e)+1)}else o=t-1;e.readBits(1),ue(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=ue(e),i=ue(e);for(let r=0;r{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=Yt[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)&&(ue(e),ue(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(ue(e),ue(e),ue(e),ue(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&ue(e),e.readBits(1)&&ui(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=ue(e),ue(e),ue(e),ue(e),ue(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},ui=(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?ue(e):i=1===e.readBits(1);let a=1;if(!i){a=ue(e)+1}r&&di(e,a,s),n&&di(e,a,s)}},di=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=hi.audAllowed;for(const s of ti(e,t)){if(r===hi.noMoreDataAllowed){i.add(s.offset);continue}const t=ii(e[s.offset]);if(r===hi.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>hi.audAllowed?n=!0:r=hi.beforeFirstVcl:t<=31?r>hi.afterFirstVcl?n=!0:r=hi.afterFirstVcl:36===t?r!==hi.afterFirstVcl?n=!0:r=hi.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>hi.beforeFirstVcl?n=!0:r=hi.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&fe(t.description)[21];return Xt(e,i+1)}return Kt(e)})(n,t)},pi={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},gi=e=>{var t,i,r;const n=new Bt(e);if(2!==n.readBits(2))return null;const s=n.readBits(1),a=(n.readBits(1)<<1)+s;3===a&&n.skipBits(1);if(1===n.readBits(1))return null;if(0!==n.readBits(1))return null;n.skipBits(2);if(4817730!==n.readBits(24))return null;let o=8;if(a>=2){o=n.readBits(1)?12:10}const l=n.readBits(3);let c=0,u=0;if(7!==l){if(u=n.readBits(1),1===a||3===a){const e=n.readBits(1),t=n.readBits(1);c=e||t?e&&!t?2:1:3,n.skipBits(1)}else c=1}else c=3,u=1;const d=(n.readBits(16)+1)*(n.readBits(16)+1);let h=ce(Qi).level;for(const m of Qi)if(d<=m.maxPictureSize){h=m.level;break}const f=pi[l];return{profile:a,level:h,bitDepth:o,chromaSubsampling:c,videoFullRangeFlag:u,colourPrimaries:null!=(t=null==f?void 0:f.colourPrimaries)?t:2,transferCharacteristics:null!=(i=null==f?void 0:f.transferCharacteristics)?i:2,matrixCoefficients:null!=(r=null==f?void 0:f.matrixCoefficients)?r:2}},ki=function*(e){const t=new Bt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*q(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>q(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);oe(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},yi=e=>{for(const{type:t,data:i}of ki(e)){if(1!==t)continue;const e=new Bt(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{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let n=0;n<=r;n++){e.skipBits(12);const r=e.readBits(5);if(0===n&&(s=r),r>7){const t=e.readBits(1);0===n&&(a=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const 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=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,T=1,v=1,w=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,T=0,v=0):(b=e.readBits(1),0===r?(T=1,v=1):1===r?(T=0,v=0):12===m?(T=e.readBits(1),v=T?e.readBits(1):0):(T=1,v=0),T&&v&&(w=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:w,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},bi=e=>{if(e.length<36)return null;const t=me(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},Ti=[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],vi=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;u97;)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}},wi=(e,t,i)=>{switch(e){case"avc":for(const e of Wt(i,t)){const t=i[e.offset],r=Ht(t);if(r>=Nt.NON_IDR_SLICE&&r<=Nt.SLICE_DPC)return"delta";if(r===Nt.IDR)return"key";if(r===Nt.SEI&&!at()){const t=i.subarray(e.offset,e.offset+e.length),r=Vt(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 Bt(r);e.pos=8*n;const t=ue(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=me(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=pe.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;c0&&(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=ht(c),i=me(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=pe.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})}}}},xi=[2,1,2,3,3,4,4,5],Ci=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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)}},Bi=[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],Ei=[1,2,3,6],_i=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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=Ei[s];let d;d=n<3?Mt[n]/1e3:Dt[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}]}},Ri=e=>{const t=e.substreams[0];return oe(t),t.fscod<3?Mt[t.fscod]:null!==t.fscod2&&t.fscod2<3?Dt[t.fscod2]:null},Fi=e=>{const t=e.substreams[0];oe(t);let i=xi[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},Ai=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Mi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Di=[16,16,20,20,0,24,24,0],Ni=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Oi=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Li=[32e3,44100,48e3,0],zi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ui=[512,1024,2048,4096],qi=e=>{const t=Hi(e),i=me(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Vi(e.subarray(r));if(!t)break;null!=n||(n=t),r+=t.frameSize}if(t)return{frameSize:n?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==n};if(!(null==n?void 0:n.asset))return null;const{asset:s}=n;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Wi=e=>{const t=qi(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},Hi=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new Bt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const n=t.readBits(14)+1;if(n<96)return null;const s=t.readBits(6);if(s>=Ni.length)return null;const a=Ai[t.readBits(4)];if(0===a)return null;const o=Mi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const l=t.readBits(2);if(3===l)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const c=Di[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Ni[s]+(u?1:0),sampleCount:32*r,channelLayout:Oi[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},Vi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new Bt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),n=8+4*r,s=16+4*r;t.skipBits(n);const a=t.readBits(s)+1,o={frameSize:a,asset:null};if(!t.readBits(1))return o;const l=Li[t.readBits(2)],c=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===l||t.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(c*m/l),channelLayout:g,pcmResolution:f}}},ji=e=>Xe(e)+Xe(44646&e),Ki=["avc","hevc","vp9","av1","vp8","prores"],Xi=["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"],$i=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Xi],Gi=[{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}],Qi=[{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}],Yi=".01.01.01.01.00",Ji=".0.110.01.01.01.0",Zi=["ap4x","ap4h","apch","apcn","apcs","apco"],er=["dtsc","dtsh","dtsl","dtse"],tr=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(oe(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${Be(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}.${Be(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=Ee(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=me(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=Ee(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=ce(Qi).level;for(const e of Qi)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(Yi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=ce(Qi).level;for(const e of Qi)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)?ke[r.primaries]:1,u=(null==r?void 0:r.transfer)?be[r.transfer]:1,d=(null==r?void 0:r.matrix)?ve[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(Ji)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&Oe(t),new TypeError(`Unhandled codec '${t}'.`)},ir=e=>{var t,i,r,n,s,a;switch(e.codec){case"avc":{let r=null==(t=e.avcCodecInfo)?void 0:t.sequenceParameterSets[0];if(!r&&e.codecDescription&&(r=null==(i=Qt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=Jt(r);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=me(e);let i=0;const r=t.getUint8(i++),n=t.getUint8(i++),s=n>>6&3,a=n>>5&1,o=31&n,l=t.getUint32(i,!1);i+=4;const c=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,T=k>>2&1,v=3&k,w=t.getUint8(i++),S=[];for(let P=0;P>7&1,s=63&r,a=t.getUint16(i,!1);i+=2;const o=[];for(let l=0;le.nalUnitType===Lt.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=ri(t);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ye[e.vp9CodecInfo.colourPrimaries],transfer:Te[e.vp9CodecInfo.transferCharacteristics],matrix:we[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ye[e.av1CodecInfo.colourPrimaries],transfer:Te[e.av1CodecInfo.transferCharacteristics],matrix:we[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ye[e.proresCodecInfo.colourPrimaries],transfer:Te[e.proresCodecInfo.transferCharacteristics],matrix:we[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},rr=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:n}=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=Rt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return null!=n?n:"dtsc";if(t&&Xi.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},nr=48e3,sr=/^pcm-([usf])(\d+)(be)?$/,ar=e=>{if(oe(Xi.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=sr.exec(e);let i;oe(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?q(2,7):0}},or=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":Zi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":er.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":sr.test(e)?e:"webvtt"===e?"webvtt":null,lr=[44100,48e3,32e3],cr=[-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],ur=1483304551,dr=1231971951,hr=(e,t)=>3===e?3===t?21:36:3===t?13:21,fr=(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=cr[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=lr[u]>>a+o,b=((e,t,i,r,n)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var pr,gr;(gr=pr||(pr={}))[gr.FrameCount=1]="FrameCount",gr[gr.FileSize=2]="FileSize",gr[gr.Toc=4]="Toc";const kr=e=>3===e?1:2;class yr{constructor(e){this.input=e}dispose(){}}const br=new Uint8Array(0);class Tr{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===br&&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===br}get microsecondTimestamp(){return Math.trunc(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){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 Tr(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 Tr(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 vr=e=>{const t=me(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=Be(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=Cl(e);const i=Nl(e,4);let r=8;1===t&&(t=Rl(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Pr=e=>El(e)/65536,Ir=e=>El(e)/1073741824,xr=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=vl(e);if(t|=127&i,0===(128&i))break}return t},Cr=e=>{let t=Sl(e);return e.skip(2),t=Math.min(t,e.remainingLength),pe.decode(Tl(e,t))},Br=e=>{const t=Sr(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Cl(e);e.skip(4);const r=Tl(e,t.contentSize-8);switch(i){case 1:return pe.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new It(r,"image/jpeg");case 14:return new It(r,"image/png");case 27:return new It(r,"image/bmp");default:return r}},Er=16,_r=new Uint32Array(256),Rr=new Uint32Array(256),Fr=new Uint32Array(256),Ar=new Uint32Array(256),Mr=new Uint32Array(256),Dr=new Uint32Array(256),Nr=new Uint32Array(10);let Or=!1;class Lr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Er/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Er),this.out=new Uint8Array(Er),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){oe(16===e.byteLength),oe(16===t.byteLength),Or||(()=>{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);_r[s]=t<<24|t<<16|t<<8|t,Dr[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);Rr[s]=n,Fr[s]=n>>>8|n<<24,Ar[s]=n>>>16|n<<16,Mr[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Nr[s]=n<<24,n=n<<1^(128&n?283:0);Or=!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&_r[e>>>16&255]^16711680&_r[e>>>8&255]^65280&_r[e>>>0&255]^255&_r[e>>>24&255]^Nr[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>>24&255]]^Fr[255&_r[t>>>16&255]]^Ar[255&_r[t>>>8&255]]^Mr[255&_r[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=Rr[e>>>24]^Fr[r>>>16&255]^Ar[i>>>8&255]^Mr[255&t]^this.roundkey[n],c=Rr[t>>>24]^Fr[e>>>16&255]^Ar[r>>>8&255]^Mr[255&i]^this.roundkey[n+1],u=Rr[i>>>24]^Fr[t>>>16&255]^Ar[e>>>8&255]^Mr[255&r]^this.roundkey[n+2],d=Rr[r>>>24]^Fr[i>>>16&255]^Ar[t>>>8&255]^Mr[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Dr[e>>>24&255]^16711680&Dr[r>>>16&255]^65280&Dr[i>>>8&255]^255&Dr[t>>>0&255]^this.roundkey[40],f=4278190080&Dr[t>>>24&255]^16711680&Dr[e>>>16&255]^65280&Dr[r>>>8&255]^255&Dr[i>>>0&255]^this.roundkey[41],m=4278190080&Dr[i>>>24&255]^16711680&Dr[t>>>16&255]^65280&Dr[e>>>8&255]^255&Dr[r>>>0&255]^this.roundkey[42],p=4278190080&Dr[r>>>24&255]^16711680&Dr[i>>>16&255]^65280&Dr[t>>>8&255]^255&Dr[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 zr extends yr{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 Y(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return Y(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 Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(ct(r)&&(r=yield r),!r)break;const n=e,s=Sr(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Nl(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(ct(e)&&(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>n+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');yield this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=n+s.totalSize}if(!i&&this.input._initInput&&(yield this.copyMetadataFromInitInput(this.input._initInput)),t){oe(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ct(e)&&(e=yield e),oe(e);const t=Cl(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(ct(e)&&(e=yield e),e){const t=Sr(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ct(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return Y(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==zr)throw new Error("Init input must match the input's format.");yield t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const e of t.tracks){const t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};if(e.trackBacking)if(oe(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new qr(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new Wr(e),this.tracks.push(t)}}})}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;oe(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&&Xi.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){oe("audio"===(null==(i=e.info)?void 0:i.type));const t=ar(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=Re(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=ce(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;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)Xr(e,r.timestamp);else{const t=Re(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];Xr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=Re(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 Yr(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ge(t.languageCode)||(t.languageCode=We)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Nl(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:H({},Pe),avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=re,this.readContiguousBoxes(e.slice(se,ne.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=vl(e);e.skip(3);const r=Cl(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Cl(e),e.skip(8)):2===a&&(e.skip(4),c=Dl(e),o=Cl(e),e.skip(4),l=Cl(e),u=Cl(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=nr;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(er.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Pt._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":(Pt._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":(Pt._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":(Pt._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":(Pt._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(Pt._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<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==vl(e),t.encryptionInfo.defaultPerSampleIvSize=vl(e),t.encryptionInfo.defaultKid=Be(Tl(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=vl(e),r=new Uint8Array(16);r.set(Tl(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;oe("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=vl(e),n=vl(e),s=vl(e),a=s>>4,o=s>>1&7,l=1&s,c=vl(e),u=vl(e),d=vl(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;oe("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=vl(e),l=o>>5,c=31&o,u=vl(e),d=u>>7,h=u>>6&1,f=u>>4&1,m=u>>3&1,p=u>>2&1,g=3&u,k=2===l&&h?u>>5&1?12:10:h?10:8;e.skip(1);const y=Tl(e,ne.contentSize-4),b=yi(y);t.info.av1CodecInfo={profile:l,level:c,tier:d,bitDepth:k,monochrome:f,chromaSubsamplingX:m,chromaSubsamplingY:p,chromaSamplePosition:g,videoFullRangeFlag:null!=(r=null==b?void 0:b.videoFullRangeFlag)?r:0,colourPrimaries:null!=(n=null==b?void 0:b.colourPrimaries)?n:2,transferCharacteristics:null!=(s=null==b?void 0:b.transferCharacteristics)?s:2,matrixCoefficients:null!=(a=null==b?void 0:b.matrixCoefficients)?a:2}}break;case"colr":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(o=t.info)?void 0:o.type));const i=Nl(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Sl(e),n=Sl(e),s=Sl(e);let a;"nclx"===i&&(a=Boolean(128&vl(e))),t.info.colorSpace={primaries:ye[r],transfer:Te[n],matrix:we[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(l=t.info)?void 0:l.type));const i=Cl(e),r=Cl(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==(null==(c=t.info)?void 0:c.type))break;e.skip(4);oe(3===vl(e)),xr(e),e.skip(2);const i=vl(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=vl(e);e.skip(t)}n&&e.skip(2);oe(4===vl(e));const s=xr(e),a=e.filePos,o=vl(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":Pt._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){oe(5===vl(e));const i=xr(e);if(t.info.codecDescription=Tl(e,i),"aac"===t.info.codec){const e=Rt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&Sl(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=vl(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=vl(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(h=t.info)?void 0:h.type)),e.skip(1);const i=vl(e),r=Sl(e),n=Cl(e),s=Il(e),a=vl(e);let o;o=0!==a?Tl(e,2+i):new Uint8Array(0);const l=new Uint8Array(19+o.byteLength),c=new DataView(l.buffer);c.setUint32(0,1332770163,!1),c.setUint32(4,1214603620,!1),c.setUint8(8,1),c.setUint8(9,i),c.setUint16(10,r,!0),c.setUint32(12,n,!0),c.setInt16(16,s,!0),c.setUint8(18,a),l.set(o,19),t.info.codecDescription=l,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=127,r=128,n=e.filePos;for(;e.filePos>>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=Tl(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;oe("audio"===(null==(m=t.info)?void 0:m.type));const i=Tl(e,3),r=new Bt(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Mt[n]),t.info.numberOfChannels=xi[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(p=t.info)?void 0:p.type));const i=(e=>{if(e.length<2)return null;const t=new Bt(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}})(Tl(e,ne.contentSize));if(!i){Pt._warn("Invalid dec3 box contents, ignoring.");break}const r=Ri(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Fi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(g=t.info)?void 0:g.type));const i=(e=>{if(e.length<20)return null;const t=me(e),i=t.getUint32(0);if(0===i)return null;const r=new Bt(e);r.seekToByte(13);const n=r.readBits(2);r.skipBits(5);const s=r.readBits(1),a=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let l=null;return 0!==o?l=ji(o):ae.id===i);if(!r)break;const n=Cl(e),s=(12&n)>>2,a=3&n,o=[vl,Sl,Pl,Cl],l=o[(48&n)>>4],c=o[s],u=o[a],d=Cl(e);for(let h=0;he.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let n=0;ne.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!=(y=null==d?void 0:d.defaultSampleDescriptionIndex)?y:null,defaultSampleDuration:null!=(b=null==d?void 0:d.defaultSampleDuration)?b:null,defaultSampleSize:null!=(T=null==d?void 0:d.defaultSampleSize)?T:null,defaultSampleFlags:null!=(v=null==d?void 0:d.defaultSampleFlags)?v:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Rl(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Cl(e)),n&&(u.currentFragmentState.defaultSampleDuration=Cl(e)),s&&(u.currentFragmentState.defaultSampleSize=Cl(e)),a&&(u.currentFragmentState.defaultSampleFlags=Cl(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;oe(t.currentFragmentState);const i=vl(e);e.skip(3);const r=0===i?Cl(e):Rl(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;oe(this.currentFragment),oe(t.currentFragmentState);const i=vl(e),r=Pl(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=Cl(e);let d=null;n&&(d=El(e));let h,f=null;s&&(f=Cl(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));for(let m=0;m0&&(n=Tl(e,r));const s=Qr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=vl(e);if(1&Pl(e)){const i=Nl(e,4),r=Cl(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Cl(e);if(0===r)break;r>1&&Pt._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Cl(e):Number(Rl(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);Qr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;oe(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Pl(e),n=Boolean(2&r),s=Cl(e),a=t.encryptionInfo.defaultPerSampleIvSize;oe(null!==a);for(let o=0;o0?r.set(Tl(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Sl(e);s=[];for(let i=0;i0&&(null!=(Y=this.metadataTags).trackNumber||(Y.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(J=this.metadataTags).tracksTotal||(J.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(Z=this.metadataTags).trackNumber||(Z.trackNumber=t)),i>0&&(null!=(ee=this.metadataTags).tracksTotal||(ee.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(te=this.metadataTags).discNumber||(te.discNumber=t)),i>0&&(null!=(ie=this.metadataTags).discsTotal||(ie.discsTotal=i))}}}}}return e.filePos=ae,!0}}class Ur{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;oe(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 Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return Y(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Hr(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return Gr(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=Re(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=Ne(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 oe(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=jr(i,e);if(!r)return null;let n;if(t.metadataOnly)n=br;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ct(t)&&(t=yield t),!t)return null;if(n=Tl(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield Yr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=Re(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(ct(e)&&(e=yield e),!e)break;const i=k,s=Sr(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.moofOffsetY(this,null,function*(){var e,t,i,r,n,s,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=yield this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&bi(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&yi(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&gi(t.data);i&&(this.internalTrack.info.vp9CodecInfo=V(H({},null!=(e=this.internalTrack.info.vp9CodecInfo)?e:i),{videoFullRangeFlag:i.videoFullRangeFlag,colourPrimaries:i.colourPrimaries,transferCharacteristics:i.transferCharacteristics,matrixCoefficients:i.matrixCoefficients}))}else{const e=yield this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&ni(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&$t(e.data)}if(!Se(this.internalTrack.info.colorSpace)){const e=ir(this.internalTrack.info);null!=(t=this.internalTrack.info.colorSpace).primaries||(t.primaries=e.primaries),null!=(i=this.internalTrack.info.colorSpace).transfer||(i.transfer=e.transfer),null!=(r=this.internalTrack.info.colorSpace).matrix||(r.matrix=e.matrix),null!=(n=this.internalTrack.info.colorSpace).fullRange||(n.fullRange=e.fullRange)}const o={codec:tr(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(s=this.internalTrack.info.codecDescription)?s:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Wr extends Ur{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr(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 Hr=(e,t)=>{if(e.presentationTimestamps){const i=Re(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=Re(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)}},Vr=(e,t)=>{var i;if(!e.keySampleIndices)return Hr(e,t);if(e.presentationTimestamps){const i=Re(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!==_e(e.keySampleIndices,i,e=>e))return i}return-1}{const r=Hr(e,t),n=Re(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},jr=(e,t)=>{const i=Re(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=Re(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];oe(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;ge)}},Kr=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=Re(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},Xr=(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},$r=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Gr=e=>0===e.sampleSizes.length,Qr=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}},Yr=(e,t,i)=>Y(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{oe(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Tl(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Sl(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Zr=(e,t,i,r)=>Y(null,null,function*(){var n;oe(e.encryptionInfo);const s=e.encryptionInfo;oe(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=Y(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{oe(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;iY(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=>Y(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);oe(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=rn(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 d=yield a(c),h=new Uint8Array(r);let f=0;for(const e of o)for(const t of e.perSubsample)h.set(d.subarray(f,f+t.length),t.offset),f+=t.length;return h}),tn=(e,t,i,r)=>{const n=new Lr;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(oe(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;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 nn,sn;(sn=nn||(nn={}))[sn.EBML=440786851]="EBML",sn[sn.EBMLVersion=17030]="EBMLVersion",sn[sn.EBMLReadVersion=17143]="EBMLReadVersion",sn[sn.EBMLMaxIDLength=17138]="EBMLMaxIDLength",sn[sn.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",sn[sn.DocType=17026]="DocType",sn[sn.DocTypeVersion=17031]="DocTypeVersion",sn[sn.DocTypeReadVersion=17029]="DocTypeReadVersion",sn[sn.Void=236]="Void",sn[sn.Segment=408125543]="Segment",sn[sn.SeekHead=290298740]="SeekHead",sn[sn.Seek=19899]="Seek",sn[sn.SeekID=21419]="SeekID",sn[sn.SeekPosition=21420]="SeekPosition",sn[sn.Duration=17545]="Duration",sn[sn.Info=357149030]="Info",sn[sn.TimestampScale=2807729]="TimestampScale",sn[sn.MuxingApp=19840]="MuxingApp",sn[sn.WritingApp=22337]="WritingApp",sn[sn.Tracks=374648427]="Tracks",sn[sn.TrackEntry=174]="TrackEntry",sn[sn.TrackNumber=215]="TrackNumber",sn[sn.TrackUID=29637]="TrackUID",sn[sn.TrackType=131]="TrackType",sn[sn.FlagEnabled=185]="FlagEnabled",sn[sn.FlagDefault=136]="FlagDefault",sn[sn.FlagForced=21930]="FlagForced",sn[sn.FlagOriginal=21934]="FlagOriginal",sn[sn.FlagHearingImpaired=21931]="FlagHearingImpaired",sn[sn.FlagVisualImpaired=21932]="FlagVisualImpaired",sn[sn.FlagCommentary=21935]="FlagCommentary",sn[sn.FlagLacing=156]="FlagLacing",sn[sn.Name=21358]="Name",sn[sn.Language=2274716]="Language",sn[sn.LanguageBCP47=2274717]="LanguageBCP47",sn[sn.CodecID=134]="CodecID",sn[sn.CodecPrivate=25506]="CodecPrivate",sn[sn.CodecDelay=22186]="CodecDelay",sn[sn.SeekPreRoll=22203]="SeekPreRoll",sn[sn.DefaultDuration=2352003]="DefaultDuration",sn[sn.Video=224]="Video",sn[sn.PixelWidth=176]="PixelWidth",sn[sn.PixelHeight=186]="PixelHeight",sn[sn.DisplayWidth=21680]="DisplayWidth",sn[sn.DisplayHeight=21690]="DisplayHeight",sn[sn.DisplayUnit=21682]="DisplayUnit",sn[sn.AlphaMode=21440]="AlphaMode",sn[sn.Audio=225]="Audio",sn[sn.SamplingFrequency=181]="SamplingFrequency",sn[sn.Channels=159]="Channels",sn[sn.BitDepth=25188]="BitDepth",sn[sn.SimpleBlock=163]="SimpleBlock",sn[sn.BlockGroup=160]="BlockGroup",sn[sn.Block=161]="Block",sn[sn.BlockAdditions=30113]="BlockAdditions",sn[sn.BlockMore=166]="BlockMore",sn[sn.BlockAdditional=165]="BlockAdditional",sn[sn.BlockAddID=238]="BlockAddID",sn[sn.BlockDuration=155]="BlockDuration",sn[sn.ReferenceBlock=251]="ReferenceBlock",sn[sn.Cluster=524531317]="Cluster",sn[sn.Timestamp=231]="Timestamp",sn[sn.Cues=475249515]="Cues",sn[sn.CuePoint=187]="CuePoint",sn[sn.CueTime=179]="CueTime",sn[sn.CueTrackPositions=183]="CueTrackPositions",sn[sn.CueTrack=247]="CueTrack",sn[sn.CueClusterPosition=241]="CueClusterPosition",sn[sn.Colour=21936]="Colour",sn[sn.MatrixCoefficients=21937]="MatrixCoefficients",sn[sn.TransferCharacteristics=21946]="TransferCharacteristics",sn[sn.Primaries=21947]="Primaries",sn[sn.Range=21945]="Range",sn[sn.Projection=30320]="Projection",sn[sn.ProjectionType=30321]="ProjectionType",sn[sn.ProjectionPoseRoll=30325]="ProjectionPoseRoll",sn[sn.Attachments=423732329]="Attachments",sn[sn.AttachedFile=24999]="AttachedFile",sn[sn.FileDescription=18046]="FileDescription",sn[sn.FileName=18030]="FileName",sn[sn.FileMediaType=18016]="FileMediaType",sn[sn.FileData=18012]="FileData",sn[sn.FileUID=18094]="FileUID",sn[sn.Chapters=272869232]="Chapters",sn[sn.Tags=307544935]="Tags",sn[sn.Tag=29555]="Tag",sn[sn.Targets=25536]="Targets",sn[sn.TargetTypeValue=26826]="TargetTypeValue",sn[sn.TargetType=25546]="TargetType",sn[sn.TagTrackUID=25541]="TagTrackUID",sn[sn.TagEditionUID=25545]="TagEditionUID",sn[sn.TagChapterUID=25540]="TagChapterUID",sn[sn.TagAttachmentUID=25542]="TagAttachmentUID",sn[sn.SimpleTag=26568]="SimpleTag",sn[sn.TagName=17827]="TagName",sn[sn.TagLanguage=17530]="TagLanguage",sn[sn.TagString=17543]="TagString",sn[sn.TagBinary=17541]="TagBinary",sn[sn.ContentEncodings=28032]="ContentEncodings",sn[sn.ContentEncoding=25152]="ContentEncoding",sn[sn.ContentEncodingOrder=20529]="ContentEncodingOrder",sn[sn.ContentEncodingScope=20530]="ContentEncodingScope",sn[sn.ContentCompression=20532]="ContentCompression",sn[sn.ContentCompAlgo=16980]="ContentCompAlgo",sn[sn.ContentCompSettings=16981]="ContentCompSettings",sn[sn.ContentEncryption=20533]="ContentEncryption";const an=[nn.EBML,nn.Segment],on=[nn.SeekHead,nn.Info,nn.Cluster,nn.Tracks,nn.Cues,nn.Attachments,nn.Chapters,nn.Tags],ln=[...an,...on],cn=16,un=e=>{if(e.remainingLength<1)return null;const t=vl(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=vl(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=un(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===vl(e))return;e.skip(-1);const t=dn(e);return null===t?null:72057594037927940!==t?t:void 0},pn=e=>{oe(e.remainingLength>=2);const t=fn(e);if(null===t)return null;const i=mn(e);return null===i?null:{id:t,size:i}},gn=(e,t)=>{const i=Tl(e,t);let r=0;for(;r{const i=Tl(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Ml(e):Dl(e)},bn=(e,t,i,r)=>Y(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Tn=(e,t,i,r)=>Y(null,null,function*(){const n=q(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return Y(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 Y(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=H(H({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,cn);if(ct(t)&&(t=yield t),!t)break;const i=pn(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===nn.EBML){Dn(n);let e=this.reader.requestSlice(s,n);if(ct(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===nn.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===nn.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield bn(this.reader,s,ln,this.reader.fileSize)).pos-s}const e=ce(this.segments);e&&(e.elementEndPos=s+n)}Dn(n),e=s+n}}))()}readSegment(e,t){return Y(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||re.id===s);if(-1!==l){const e=Wn[l].flag;this.currentSegment[e]=!0,Dn(a);let t=this.reader.requestSlice(o,a);ct(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===nn.Tags||s===nn.Attachments){s===nn.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Dn(a);let e=this.reader.requestSlice(o,a);ct(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===nn.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=Wn.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,cn);if(ct(r)&&(r=yield r),!r)continue;const n=pn(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Dn(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);ct(o)&&(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;ta&&(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 Y(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,cn);ct(r)&&(r=yield r),oe(r);const n=e,s=pn(r);oe(s);oe(s.id===nn.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield bn(this.reader,o,ln,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);ct(l)&&(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,ln);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;oe(e.blocks.length>0);let i=!1;for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[ce(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=Re(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=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,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A,M,D,N,O,L,z,U,q,W,j,K,X,$,G,Q,Y,J,Z,ee;const te=pn(e);if(!te)return!1;if(t&&t.includes(te.id))return!1;const{id:ie,size:re}=te,ne=e.filePos;switch(Dn(re),ie){case nn.DocType:this.isWebM="webm"===gn(e,re);break;case nn.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case nn.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=hn(e,re)}break;case nn.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=hn(e,re)}break;case nn.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=hn(e,re),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case nn.Duration:if(!this.currentSegment)break;this.currentSegment.duration=yn(e,re);break;case nn.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:V(H({},Ct),{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(ne,re)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==Ln.Block||e.data.algorithm!==Un.HeaderStripping})&&(Pt._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===vn)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===wn)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Sn)this.currentTrack.info.codec="vp8";else if(t===Pn)this.currentTrack.info.codec="vp9";else if(t===In)this.currentTrack.info.codec="av1";else if(t===xn){const e=this.currentTrack.codecPrivate?pe.decode(this.currentTrack.codecPrivate):"";Zi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Kn(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Cn?(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===Bn?this.currentTrack.info.codec="mp3":t===En?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=nr):t===_n?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Rn?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fn?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===An?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Mn?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Xn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case nn.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=hn(e,re);break;case nn.TrackType:{if(!this.currentTrack)break;const t=hn(e,re);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:H({},Pe),alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case nn.FlagEnabled:if(!this.currentTrack)break;hn(e,re)||(this.currentTrack=null);break;case nn.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!hn(e,re);break;case nn.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!hn(e,re);break;case nn.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!hn(e,re);break;case nn.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!hn(e,re);break;case nn.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!hn(e,re);break;case nn.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!hn(e,re);break;case nn.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=gn(e,re);break;case nn.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Tl(e,re);break;case nn.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=hn(e,re);break;case nn.Name:if(!this.currentTrack)break;this.currentTrack.name=kn(e,re);break;case nn.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=gn(e,re),Ge(this.currentTrack.languageCode)||(this.currentTrack.languageCode=We);break;case nn.LanguageBCP47:{if(!this.currentTrack)break;const t=gn(e,re).split("-")[0];this.currentTrack.languageCode=t||We,this.currentTrack.hasLanguageBcp47=!0}break;case nn.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=hn(e,re);break;case nn.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=hn(e,re);break;case nn.DisplayWidth:if("video"!==(null==(d=null==(u=this.currentTrack)?void 0:u.info)?void 0:d.type))break;this.currentTrack.info.displayWidth=hn(e,re);break;case nn.DisplayHeight:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayHeight=hn(e,re);break;case nn.DisplayUnit:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayUnit=hn(e,re);break;case nn.AlphaMode:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.alphaMode=1===hn(e,re);break;case nn.Colour:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.MatrixCoefficients:{if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;const t=hn(e,re),i=we[t];this.currentTrack.info.colorSpace.matrix=i}break;case nn.Range:{if("video"!==(null==(S=null==(w=this.currentTrack)?void 0:w.info)?void 0:S.type))break;const t=hn(e,re);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case nn.TransferCharacteristics:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=hn(e,re),i=Te[t];this.currentTrack.info.colorSpace.transfer=i}break;case nn.Primaries:{if("video"!==(null==(C=null==(x=this.currentTrack)?void 0:x.info)?void 0:C.type))break;const t=hn(e,re),i=ye[t];this.currentTrack.info.colorSpace.primaries=i}break;case nn.Projection:if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.ProjectionPoseRoll:{if("video"!==(null==(R=null==(_=this.currentTrack)?void 0:_.info)?void 0:R.type))break;const t=-yn(e,re);try{this.currentTrack.info.rotation=le(t)}catch(se){}}break;case nn.Audio:if("audio"!==(null==(A=null==(F=this.currentTrack)?void 0:F.info)?void 0:A.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.SamplingFrequency:if("audio"!==(null==(D=null==(M=this.currentTrack)?void 0:M.info)?void 0:D.type))break;this.currentTrack.info.sampleRate=yn(e,re);break;case nn.Channels:if("audio"!==(null==(O=null==(N=this.currentTrack)?void 0:N.info)?void 0:O.type))break;this.currentTrack.info.numberOfChannels=hn(e,re);break;case nn.BitDepth:if("audio"!==(null==(z=null==(L=this.currentTrack)?void 0:L.info)?void 0:z.type))break;this.currentTrack.info.bitDepth=hn(e,re);break;case nn.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(ne,re)),this.currentCueTime=null;break;case nn.CueTime:this.currentCueTime=hn(e,re);break;case nn.CueTrackPositions:{if(null===this.currentCueTime)break;oe(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case nn.CueTrack:{const t=null==(U=this.currentSegment)?void 0:U.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=hn(e,re)}break;case nn.CueClusterPosition:{const t=null==(q=this.currentSegment)?void 0:q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;oe(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+hn(e,re)}break;case nn.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=hn(e,re);break;case nn.SimpleBlock:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(W=i.track.info)?void 0:W.type)&&i.track.info.codec&&(a=!0);const o=Tl(e,re-(e.filePos-ne)),l=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,postProcessed:!1,mainAdditional:null})}break;case nn.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(ne,re)),this.currentBlock=null;break;case nn.Block:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e)>>1&3,s=Tl(e,re-(e.filePos-ne)),a=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case nn.BlockAdditions:this.readContiguousElements(e.slice(ne,re));break;case nn.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case nn.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Tl(e,re);break;case nn.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=hn(e,re);break;case nn.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=hn(e,re);break;case nn.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case nn.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(ne,re));break;case nn.Targets:this.readContiguousElements(e.slice(ne,re));break;case nn.TargetTypeValue:50!==hn(e,re)&&(this.currentTagTargetIsMovie=!1);break;case nn.TagTrackUID:case nn.TagEditionUID:case nn.TagChapterUID:case nn.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case nn.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(ne,re));break;case nn.TagName:this.currentSimpleTagName=kn(e,re);break;case nn.TagString:{if(!this.currentSimpleTagName)break;const t=kn(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.TagBinary:{if(!this.currentSimpleTagName)break;const t=Tl(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(ne,re));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new xt(this.currentAttachedFile.fileData,null!=(j=this.currentAttachedFile.fileMediaType)?j:void 0,null!=(K=this.currentAttachedFile.fileName)?K:void 0,null!=(X=this.currentAttachedFile.fileDescription)?X:void 0)),(null==($=this.currentAttachedFile.fileMediaType)?void 0:$.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!=(G=this.currentAttachedFile.fileName)?G:void 0,description:null!=(Q=this.currentAttachedFile.fileDescription)?Q:void 0})}this.currentAttachedFile=null}break;case nn.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;rt.order-e.order);break;case nn.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ln.Block,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case nn.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=hn(e,re);break;case nn.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=hn(e,re);break;case nn.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Un.Zlib,settings:null},this.readContiguousElements(e.slice(ne,re));break;case nn.ContentCompAlgo:if("decompress"!==(null==(J=null==(Y=this.currentDecodingInstruction)?void 0:Y.data)?void 0:J.type))break;this.currentDecodingInstruction.data.algorithm=hn(e,re);break;case nn.ContentCompSettings:if("decompress"!==(null==(ee=null==(Z=this.currentDecodingInstruction)?void 0:Z.data)?void 0:ee.type))break;this.currentDecodingInstruction.data.settings=Tl(e,re);break;case nn.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=ne+re,!0}decodeBlockData(e,t){oe(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(oe(r.data),"decompress"===r.data.type)if(r.data.algorithm===Un.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))}}}getDurationFromMetadata(e){return Y(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){oe(r.trackBacking);const e=yield r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(null!=t?t:1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=null!=t?t:0,i})}}class jn{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return Y(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=Re(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=Ne(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 oe(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return Y(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(oe(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if("prores"===(null==(r=this.internalTrack.info)?void 0:r.codec)){if(!(s.data.length>=8&&105===s.data[4]&&99===s.data[5]&&112===s.data[6]&&102===s.data[7])){const e=new Uint8Array(s.data.length+8);me(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(s.data,8),s.data=e}}s.postProcessed=!0}const a=i.metadataOnly?br:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,l=s.duration/this.internalTrack.segment.timestampFactor,c={};s.mainAdditional&&"video"===(null==(n=this.internalTrack.info)?void 0:n.type)&&this.internalTrack.info.alphaMode&&(c.alpha=i.metadataOnly?br:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Tr(a,s.isKeyFrame?"key":"delta",o,l,e.dataStartPos+t,s.data.byteLength,c);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u})}performClusterLookup(e,t,i,r,n){return Y(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=Re(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=Re(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,y=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let b;for(e?null===y||e.elementStartPos>=y?(b=e.elementEndPos,d=e):b=y:b=null!=y?y:u.clusterSeekStartPos;null===u.elementEndPos||b<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(b,2,cn);if(ct(e)&&(e=yield e),!e)break;const i=b,s=pn(e);if(!s||!on.includes(s.id)&&s.id!==nn.Void){const e=yield Tn(c.reader,i,on,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+Hn));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===nn.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){oe(a!==nn.Cluster);l=(yield bn(c.reader,m,ln,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,cn);if(ct(e)&&(e=yield e),!e)break;if(fn(e)===nn.Segment){u.elementEndPos=p;break}}b=p}if(p&&(!h||h.elementStartPosY(this,null,function*(){var e,t,i,r,n;let s=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(s=yield this.getFirstPacket({}));const a={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&&s?$t(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?ni(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?gi(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?yi(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?bi(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!Se(this.internalTrack.info.colorSpace)){const n=ir(a);null!=(e=this.internalTrack.info.colorSpace).primaries||(e.primaries=n.primaries),null!=(t=this.internalTrack.info.colorSpace).transfer||(t.transfer=n.transfer),null!=(i=this.internalTrack.info.colorSpace).matrix||(i.matrix=n.matrix),null!=(r=this.internalTrack.info.colorSpace).fullRange||(r.fullRange=n.fullRange)}const o={codec:tr(a),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(n=this.internalTrack.info.codecDescription)?n:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Xn extends jn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}}))():null})}}const $n=(e,t,i,r=null)=>Y(null,null,function*(){const n=q(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Cl(a),n=null!==e.fileSize?e.fileSize-s:null,o=fr(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&kr(o.header.channel)===kr(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class Gn extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Qn(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield $n(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=hr(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ct(r)&&(r=yield r),r){const n=Cl(r);if(n===ur||n===dr){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ct(t)&&(t=yield t),t){const e=Tl(t,12),i=me(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&pr.FrameCount?i.getUint32(4,!1):null,fileSize:r&pr.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);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 Y(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(ct(n)&&(n=yield n),!n)break;$l(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Wl){let e=this.reader.requestSlice(this.reader.fileSize-Wl,Wl);ct(e)&&(e=yield e),oe(e);"TAG"===Nl(e,3)&&jl(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class Qn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){const e=this.demuxer;if(oe(null!==e.firstFrameHeader),oe(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<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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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>>0&4294967295}const Zn=e=>{const t=me(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n>>24^t])>>>0}return t.setUint32(22,i,!0),r},es=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){oe(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,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:Ti[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},ts=27,is=282,rs=e=>{const t=e.filePos;if(Bl(e)!==Yn)return null;e.skip(1);const i=vl(e),r=Al(e),n=Bl(e),s=Bl(e),a=Bl(e),o=vl(e),l=new Uint8Array(o);for(let d=0;de+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}},ns=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Yn)return!0;e.skip(1)}}return!1};class ss extends yr{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,ts,is);if(ct(t)&&(t=yield t),!t)break;const i=rs(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 as(t,this)))}}))()})}readVorbisMetadata(e,t){return Y(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=me(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:vi(n.data).modeBlockflags},Ii(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return Y(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=me(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=nr,t.codecInfo.opusInfo={preSkip:n.preSkip},Ii(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return Y(this,null,function*(){oe(te+t.length,0);if(0===o)return null;const l=new Uint8Array(o);let c=0;for(let e=0;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 Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class as{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new xe,this.internalSampleRate="opus"===e.codecInfo.codec?nr:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return oe(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return Y(this,null,function*(){var e;return oe(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 We}getDisposition(){return V(H({},Ct),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(oe(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=es(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Tr(i.metadataOnly?br: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 Y(this,null,function*(){oe(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(oe(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 Y(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 Y(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=He(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;oe(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.totalSizen?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,ts,is);ct(t)&&(t=yield t),oe(t);const i=rs(t);oe(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}oe(-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:br,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=ls(d,u,m);oe(e);const t=os(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=ls(d,u,m);if(!e)break;const t=os(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,y=null;for(;null!==u;){oe(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&mn||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 Y(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=He(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=Re(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.timestampe)break;if(n=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);oe(e),this.sequentialScanCache.length>0&&oe(ce(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 os=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}oe(-1===n);if(!(1&r.headerType)){n=0;break}const t=De(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=De(e,e=>e.headerStartPosY(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);ct(i)&&(i=yield i),oe(i);const r=Nl(i,4),n="RIFX"!==r,s="RF64"===r,a=xl(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Nl(i,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=i.filePos;for(;null===o||u=18&&357!==n){const e=wl(r,i),s=t-18;if(Math.min(s,e)>=22&&n===cs.EXTENSIBLE){r.skip(6);const e=Tl(r,16);n=e[0]|e[1]<<8}}if(n!==cs.MULAW&&n!==cs.ALAW||(l=8),n!==cs.PCM&&n!==cs.IEEE_FLOAT&&n!==cs.ALAW&&n!==cs.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===cs.PCM&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(n===cs.IEEE_FLOAT&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,i){return Y(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(ct(m)&&(m=yield m),!m)return;const p=Nl(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Nl(m,4),t=xl(m,i),p=Tl(m,t);let k=0;for(let i=0;i0&&(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 Y(this,null,function*(){let i=this.reader.requestSlice(e,t);if(ct(i)&&(i=yield i),!i)return;const r=Xl(i);if(r){const n=t-Hl;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+Hl,r.size);$l(t,r,this.metadataTags)}}})}getCodec(){if(oe(this.audioInfo),this.audioInfo.format===cs.MULAW)return"ulaw";if(this.audioInfo.format===cs.ALAW)return"alaw";if(this.audioInfo.format===cs.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===cs.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}oe(!1)}getMimeType(){return Y(this,null,function*(){return"audio/wav"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const hs=2048;class fs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return Y(this,null,function*(){const e=this.demuxer.getCodec();return e?(oe(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getDisposition(){return H({},Ct)}getPacketAtIndex(e,t){return Y(this,null,function*(){oe(e>=0),oe(this.demuxer.audioInfo);const i=e*hs*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(hs*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(ct(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=br;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);ct(e)&&(e=yield e),oe(e),n=Tl(e,r)}const s=e*hs/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 Tr(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return Y(this,null,function*(){oe(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/hs,(this.demuxer.dataSize-1)/(hs*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;oe(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){oe(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/hs);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ms=e=>{const t=e.filePos,i=Tl(e,9),r=new Bt(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}},ps=1024;class gs extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();oe(this.firstFrameHeader),this.trackBackings=[new ks(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ms(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=Et[t.samplingFrequencyIndex];oe(void 0!==i);const r=ps/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=ps,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return Y(this,null,function*(){return"audio/aac"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(t)&&(t=yield t),!t)break;const i=Xl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ct(r)&&(r=yield r),!r)break;$l(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class ks{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ps}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getCodec(){return"aac"}getInternalCodecId(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){oe(this.demuxer.firstFrameHeader);const e=_t[this.demuxer.firstFrameHeader.channelConfiguration];return oe(void 0!==e),e}getSampleRate(){oe(this.demuxer.firstFrameHeader);const e=Et[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return oe(void 0!==e),e}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.dataSize)}return new Tr(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=_e(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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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+1Y(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=Xl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);ct(r)&&(r=yield r),oe(r),$l(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(255===vl(s)){const t=s.filePos;if(vl(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=Tl(e,4),n=new Bt(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){oe(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){oe(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");oe(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*q(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?q(2,e):null)(n.readBits(4));if(!s)return null;oe(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 o=(e=>{let t=0;const i=new Bt(Tl(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Bt(Tl(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Sl(e)+1:"uncommon-u8"===t?vl(e)+1:"number"===typeof t?t:(Oe(t),void oe(!1)))(e,s),c=((e,t)=>"uncommon-u16"===t?Sl(e):"uncommon-u16-10"===t?10*Sl(e):"uncommon-u8"===t?vl(e):"number"===typeof t?t:null)(e,a);if(null===c)return null;if(c!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,d=vl(e);e.skip(-u),e.skip(-1);const h=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Tl(e,u));return d!==h?null:{num:o,blockSize:l,sampleRate:c}}advanceReader(){return Y(this,null,function*(){yield this.readMetadata(),oe(null!==this.lastLoadedPos),oe(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 bs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return We}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return Y(this,null,function*(){if(oe(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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 Y(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 Y(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.byteSize)}oe(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Tr(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return Y(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Ts=9e4,vs=q(2,33),ws=188,Ss="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.",Ps=new Set([133,134,162]),Is=new Set;class xs extends yr{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=this.reader.requestSlice(0,205);ct(e)&&(e=yield e),oe(e);const t=Tl(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ws;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}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){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 Bt(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=Bs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(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 As(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=$t(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];oe(t);const i=Jt(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[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=ni(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT).nalUnits[0];oe(t);const i=ri(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:tr({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(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=yl.tempFromBytes(r.suppliedPacket.data),i=ms(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=_t[i.channelConfiguration],e.info.sampleRate=Et[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Cl(yl.tempFromBytes(r.suppliedPacket.data)),i=fr(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=kr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Ci(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=xi[t.acmod]+t.lfeon,e.info.sampleRate=Mt[t.fscod]}else if("eac3"===e.info.codec){const t=_i(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Ri(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Fi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=qi(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:rr({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Bt(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),l=e.pos+8*n;let c=!1;for(;e.pos=4){const t=e.readBits(32);c||(c=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=l;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,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let l=null;const u=c&&Ps.has(t)?130:t;switch(u){case 27:case 36:l={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",l={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:a?l={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?l={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(l={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Is.has(t)||(Pt._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Is.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}s=!0}else{const e=new Bt(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)a.initialized&&("video"===a.info.type?this.trackBackingEntries.push(new _s(a)):this.trackBackingEntries.push(new Rs(a)))}))()})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(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 Y(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!==_e(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=Re(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 Y(this,null,function*(){let t=this.reader.requestSlice(e,4);if(ct(t)&&(t=yield t),!t)return null;if(71!==vl(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Sl(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:vl(t)>>4&3}})}readPacket(e){return Y(this,null,function*(){let t=this.reader.requestSlice(e,ws);if(ct(t)&&(t=yield t),!t)return null;const i=Tl(t,ws);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}})}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=vs-t?-vs:vs}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new Bt(t.payload);if(1!==r.readBits(24))return null;const n=r.readBits(8);if(r.skipBits(16),188===n||190===n||191===n||240===n||241===n||255===n||242===n||248===n)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let a=null;if(2===s||3===s)a=0,r.skipBits(4),a+=r.readBits(3)*(1<<30),r.skipBits(1),a+=32768*r.readBits(15),r.skipBits(1),a+=r.readBits(15),a=e.normalizeTimestamp(a);else if(i)throw new Error(Ss);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Bs=(e,t,i)=>{oe(null!==t.endPos);const r=Cs(e,t,i);if(!r)return null;const n=new Bt(t.payload);n.skipBits(32);const s=n.readBits(16);n.skipBits(16);const a=n.readBits(8),o=n.pos+8*a;n.pos=o;const l=o/8;oe(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return V(H({},r),{data:c})};class Es{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++,oe(r instanceof Es),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 We}getDisposition(){return V(H({},Ct),{primary:!1})}getTimeResolution(){return Ts}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Tr(i.metadataOnly?br:e.data,r,e.pts/Ts,Math.max(t/Ts,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return Y(this,null,function*(){const t=this.elementaryStream.firstSection;oe(t);const i=Bs(this.elementaryStream.demuxer,t,!0);oe(i);const r=new As(this.elementaryStream,i),n=new Ms(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 Y(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);oe(s);const a=Bs(n,s,!0);oe(a);const o=new As(this.elementaryStream,a);i=new Ms(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 Y(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 Y(this,null,function*(){var r,n,s,a,o,l;const c=He(e*Ts),u=this.elementaryStream.demuxer,{reader:d,seekChunkSize:h}=u,f=this.elementaryStream.pid,m=(e,t,i)=>Y(this,null,function*(){let r=e;for(;re.pts),T=-1!==b?y[b]:null;if(T&&c-T.pts<45e3)k=T.sectionStartPos;else{let e=0;if(null!==d.fileSize){const t=Math.ceil(d.fileSize/h);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=Ke(t*h,u.packetStride)+g.sectionStartPos,s=n+h,a=yield m(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}k=Ke(e*h,u.packetStride)+g.sectionStartPos}const v=yield m(k,null!=(r=d.fileSize)?r:1/0,!1);let w=null!=(n=null==v?void 0:v.pesPacketHeader)?n:null;w||(w=g);const S=this.getReorderSize(),P=(e,t)=>Y(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);oe(s);const a=Bs(u,s,!0);oe(a);const o=new As(this.elementaryStream,a),l=new Ms(this,o);for(;;){if((null!=(n=null==(r=ce(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=Ne(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();oe(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=w.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;w=e,Fs(this.elementaryStream,w);break}}}e+=u.packetStride}}e:for(let e=0;e=u.packetOffset;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){w=e;break}}}e-=u.packetStride}}return P(w.sectionStartPos,e=>e.pts<=c)}{let e=k,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=g.sectionStartPos;let k,y=null;if(n)k=g,y=p;else{const t=yield m(e,null!=(s=d.fileSize)?s:1/0,i);k=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,y=null!=(o=null==t?void 0:t.section)?o:null}let b=!1,T=0;e:for(;k&&!(null!==t&&k.sectionStartPos>=t);){if(k.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===k.randomAccessIndicator;else{oe(y);const t=Bs(u,y,!0);oe(t);const i=new As(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=k)}if(k.pts>c&&(b=!0),b&&(T++,T>S))break;let e=k.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){k=e,y=t,Fs(this.elementaryStream,k);break}}}e+=u.packetStride}}if(r){let e=r;if(0===T)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===f&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Cs(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield P(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return oe(t),t}if(n)return null;t=e,e=Math.max(Ke(e-g.sectionStartPos-h,u.packetStride)+g.sectionStartPos,g.sectionStartPos)}}})}}class _s extends Es{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 Y(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return Y(this,null,function*(){return!1})}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Rs extends Es{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Fs=(e,t)=>{const i=e.referencePesPackets,r=Re(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=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return oe(e),e}bufferData(e){return Y(this,null,function*(){const t=this.endPos+e;for(;this.endPos=c)break;u=t;const r=o+u;if(u+3>=c){this.seekTo(r);break}const d=l[u+1],h=l[u+2],f=l[u+3];let m=0;if(0===d&&0===h&&1===f?m=4:0===d&&1===h&&(m=3),0===m){u++;continue}const p=r;null!=n||(n=p);const g=u+m,k=g+i,y=6;if(k+("avc"===e?y:1)>c){this.seekTo(r);break}const b=l[g];let T,v,w;if("avc"===e)T=Ht(b),v=T===Nt.NON_IDR_SLICE||T===Nt.SLICE_DPA||T===Nt.IDR,w=T===Nt.SEI||T===Nt.SPS||T===Nt.PPS||T===Nt.AUD;else{T=ii(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=Lt.RASL_R||T>=Lt.BLA_W_LP&&T<=21,w=T>=Lt.VPS_NUT&&T<=37||T===Lt.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let S=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=ue(new Bt(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?S=!0:s=!0)}else w&&s&&(S=!0);if(S){const e=p-n;return this.seekTo(n),this.supplyPacket(e,0)}u+=m}if(rn){const e=this.endPos-n;return this.seekTo(n),this.supplyPacket(e,0)}}else{const n=r.info.codec,s=128;for(;;){let a=this.ensureBuffered(s);ct(a)&&(a=yield a);const o=this.currentPos;for(;this.currentPos-o>6,a=63&i[4];if(3===n||a>37){this.seekTo(e+1);continue}const o=Bi[3*a+n];oe(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),ct(t)&&(t=yield t);const l=Math.round(13824e4/r.info.sampleRate);return this.supplyPacket(t,l)}if("eac3"===n){if(11!==s)continue;this.skip(-1);const e=this.currentPos;let t=this.ensureBuffered(5);if(ct(t)&&(t=yield t),t<5)return;const i=this.readBytes(5);if(11!==i[0]||119!==i[1]){this.seekTo(e+1);continue}const n=2*(((7&i[2])<<8|i[3])+1),a=3===i[4]>>6?3:i[4]>>4&3,o=Ei[a];this.seekTo(e),t=this.ensureBuffered(n),ct(t)&&(t=yield t);const l=256*o,c=Math.round(l*Ts/r.info.sampleRate);return this.supplyPacket(t,c)}if("dts"===n){if(127!==s&&100!==s)continue;this.skip(-1);const n=this.currentPos;let a=this.ensureBuffered(18);if(ct(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=Hi(o);let c=l?null:Vi(o);if(!l&&!c){this.seekTo(n+1);continue}if(c&&!c.asset){this.seekTo(n);const t=Math.min(c.frameSize,4096);let i=this.ensureBuffered(t);ct(i)&&(i=yield i),c=null!=(e=Vi(this.readBytes(i)))?e:c}let u=l?l.frameSize:c.frameSize;if(l){let e=4*Math.ceil(l.frameSize/4);for(;;){this.seekTo(n);const t=e+10;let i=this.ensureBuffered(t);if(ct(i)&&(i=yield i),i=0)}readNext(){return Y(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(oe(-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 Y(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 Y(this,null,function*(){const e=this.decodeOrderPackets[0];for(oe(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;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const Ds="application/vnd.apple.mpegurl",Ns="#EXT-X-STREAM-INF:",Os="#EXT-X-I-FRAME-STREAM-INF:",Ls="#EXT-X-MEDIA:",zs="#EXTINF:",Us="#EXT-X-MAP:",qs="#EXT-X-KEY:",Ws="#EXT-X-MEDIA-SEQUENCE:",Hs="#EXT-X-BYTERANGE:",Vs="#EXT-X-PROGRAM-DATE-TIME:",js="#EXT-X-TARGETDURATION:",Ks="#EXT-X-PLAYLIST-TYPE:",Xs=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class $s{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sY(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,t,i))}else if("audio"===t.type){const i=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(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=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return Y(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 Y(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 Qs{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(this,null,function*(){var e,t;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.");let i=this.segmentedInput.firstSegment,r=null;for(;i;){const e=this.segmentedInput.getInputForSegment(i);if(r=null!=(t=(yield e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number))?t:null,r)break;i=yield this.segmentedInput.getNextSegment(i,{})}if(!r)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=r,this.firstSegment=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 Y(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 Y(this,null,function*(){return yield this.hydrate(),oe(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp})}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return Y(this,null,function*(){oe(e.sequenceNumber>=0),oe(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:je(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 Y(this,null,function*(){var t;yield this.hydrate(),oe(this.firstInputTrack),oe(this.firstSegment);let i=this.firstInputTrack,r=this.firstSegment;for(;;){if(i){const t=yield i._backing.getFirstPacket(e);if(t)return this.createAdjustedPacket(t,r,i)}if(r=yield this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;const n=this.segmentedInput.getInputForSegment(r);i=null!=(t=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number))?t:null}return null})}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}_getNextInternal(e,t,i){return Y(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 Y(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 Ys extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class Js extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}ft();const Zs=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ea extends vt{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}getSizeOrNull(){return Y(this,null,function*(){var e;if(this._disposed)throw new gl;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>Y(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,Zs),e=this._getFileSize(),oe(void 0!==e)),e}))()})}getSize(){return Y(this,null,function*(){if(this._disposed)throw new gl;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 ga(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 ta(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class ta{constructor(e){var t;if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),null==(t=e._refFinalizationRegistry)||t.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){var e;if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const t=this.source;oe(t._refCount>0),t._decrementRefCount(),null==(e=t._refFinalizationRegistry)||e.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class ia extends ea{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 ea||e instanceof ta))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ea?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ct(t)?t.then(i):i(t)}}const ra=(e,t)=>e.path===t.path;class na extends ia{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 ea?e.ref():e;return this._root=t,this._rootRequest=null,t};ct(e)?this._rootRequest=e.then(t):(t(e),oe(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())}}const sa="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class aa extends ea{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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new pa({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*q(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==sa||sa.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ma.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return Y(this,null,function*(){oe(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!it()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==sa||sa.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return Pt._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(q(2,e-2),16)},ca=new Set;class ua extends ia{constructor(e,t={}){var i,r,n,s;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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new ua(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=null!=(i=t.getRetryDelay)?i:la,this._requestInit=H({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=H({},Je(t.requestInit.headers)),i=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==i&&(a=e[i],delete e[i],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){null!=a||(a=t);const i=new Request(e);i.headers.delete("Range"),this._url=i}}if(null!==a){const e=ha(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new pa({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*q(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:ma.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){var e;if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const t=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===t?null!==this._length?this._length:null:qe(t-this._offset,0,null!=(e=this._length)?e:1/0)}_read(e,t,i,r){var n;if(null!==this._length&&t>this._length)return null;const s=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+t):this._orchestrator.read(s+e,s+t,Math.max(s+i,s),s+Math.min(r,null!=(n=this._length)?n:1/0)),o=e=>e?(e.offset-=this._offset,e):null;return ct(a)?a.then(o):o(a)}_runWorker(e){return Y(this,null,function*(){for(var t;;){const r=new AbortController,n=yield Ze(null!=(t=this._options.fetchFn)?t:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(null===this._orchestrator.fileSize&&(206===n.status||"basic"===n.type&&!n.headers.has("Content-Encoding"))){const t=n.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=n.headers.get("Content-Length");if(i){const t=206===n.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==n.status){if(this._sequentialBacking)return void n.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||ca.has(e.origin)||(Pt._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),ca.add(e.origin))}return void this._transitionToSequentialMode(n.body)}const s=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return r.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let t;try{t=yield s.read()}catch(i){if(this._disposed)throw i;const e=this._getRetryDelay(1,i,this._url);if(null!==e){Pt._error("Error while reading response stream. Attempting to resume.",i),yield Tt(1e3*e);break}throw i}if(e.aborted)continue;const{done:n,value:a}=t;if(n){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+a.length),this._orchestrator.supplyWorkerData(e,a)}}})}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const n=new ReadableStream({pull:e=>Y(this,null,function*(){for(var n;;){let a;try{a=yield t.read()}catch(s){if(this._disposed)throw s;const e=this._getRetryDelay(1,s,this._url);if(null===e)throw s;Pt._error("Error while reading response stream. Attempting to resume.",s),yield Tt(1e3*e);const a=yield Ze(null!=(n=this._options.fetchFn)?n:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!a.ok)throw new Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=a.body.getReader(),r=206===a.status?0:i;continue}if(a.done)return void e.close();let o=a.value;if(r>0){const e=Math.min(r,o.length);r-=e,o=o.subarray(e)}if(0!==o.length)return i+=o.length,void e.enqueue(o)}}),cancel:()=>t.cancel()}),s=new fa(n,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const a=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)a.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)a.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of a){const e=s._read(o.start,o.start+o.bytes.length);ct(e)?e.then(e=>{e?(oe(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(oe(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const da=/^bytes=(\d+)-(\d*)$/,ha=e=>{const t=da.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=Re(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=t)break;const r=Math.max(e,i.start);r>n&&this._throwDueToCacheMiss();const a=Math.min(t,i.end);rn&&this._throwDueToCacheMiss();const{promise:a,resolve:o,reject:l}=Ae();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)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),a}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}_pull(){return Y(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._currentIndex0;){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;for(const t of this._pendingSlices)t.reject(new gl);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const ma={fileSystem:(e,t)=>{const i=q(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=q(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*q(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(dt(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=q(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+oa)}}};class pa{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;oe(!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);oe(a<=e&&t<=o);let l=null;const c=Re(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=Re(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=o)break;if(r.end<=a)continue;const n=Math.max(a,r.start),s=Math.min(o,r.end);if(oe(n<=s),m=h.length&&(l={bytes:h,view:me(h),offset:e}),0===p.length)return oe(l),l;const{promise:g,resolve:k,reject:y}=Ae(),b=[];for(const v of p){const i=Math.max(e,v.start),r=Math.min(t,v.end);i===v.start&&r===v.end?b.push(v):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&v.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,v.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:v.start,end:v.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.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?g.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(oe(h),l=g.then(t=>t&&{bytes:t,view:me(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=q(2,17);if(dt(t.start-r,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=s),t.end<=t.start&&(i.holes.splice(e,1),e--)}0===i.holes.length&&(i.resolve(i.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){var t,i;const r=this.workers.indexOf(e);oe(-1!==r),e.running=!1,this.workers.splice(r,1),null==(i=(t=this.options).onIdleWorkerRemoved)||i.call(t,e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=Re(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=me(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=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=me(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;ithis._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return ct(n)?n.then(s):s(n)}_dispose(){var e;null==(e=this._ref)||e.free()}ref(){return null!=this._ref||(this._ref=this._baseSource.ref()),super.ref()}}var ka=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},ya=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 ba=/^0[xX][0-9a-fA-F]+$/,Ta=/^data:.*;base64,/i;class va extends Gs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>Y(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Tt(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 Y(this,null,function*(){var e,t,i,r,n,s,a,o;let l=this.nextLines;if(this.nextLines=null,!l){const e={stack:[],error:void 0,hasError:!1};try{const t=ka(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new kl(t.source),r=yield i.requestEntireFile();oe(r),l=Ol(r,r.length,{ignore:Xs}),t.source instanceof ia&&(this.rootPath=t.source.rootPath)}catch(x){e.error=x,e.hasError=!0}finally{ya(e)}}const c=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let u=!1,d=0,h=null,f=null,m=null,p=0,g=null,k=null,y=null,b=null,T=null,v=null,w=!1,S=null!=(t=ce(this.segments))?t:null;const P=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}},I=e=>{p=e,S&&(oe(null!==S.sequenceNumber),S.sequenceNumber0&&null!==v&&(d=p*v),w=!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(Us)){const t=new $s(e.slice(11)),i=t.get("uri");if(!i)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const r=t.get("byterange");let a=null;if(null!==r&&(a=P(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!S){const e={path:pt(this.rootPath,i),offset:null!=(n=null==a?void 0:a.offset)?n:0,length:null!=(s=null==a?void 0:a.length)?s: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:d,unixEpochTimestamp:h,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:m,initSegment:null,lastProgramDateTimeSeconds:T}}f=null,null===b?y=null:b=null}else if(e.startsWith(qs)){const t=new $s(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(!ba.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Er);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=me(i).getUint32(0);r=vr(i.subarray(8,Math.min(e,i.length)))}}m={method:i,psshBox:r}}}}else if(e.startsWith(Ws)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);I(i)}else if(e.startsWith(Hs)){const t=P(e.slice(17));if(null===t.offset){if(null===y)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=y}b=t,y=t.offset+t.length}else if(e.startsWith(Vs)){if(S)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(T===r)continue;if(null===T&&this.segments.length>0){const e=ce(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,c&&(i.timestamp=i.unixEpochTimestamp)}T=r,h=r,c&&(d=r)}else if("#EXT-X-DISCONTINUITY"===e)g=null;else if(e.startsWith(js)){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,v=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(Ks)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");u=!0}}if(!u)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return Y(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return Y(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=Re(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.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=V(H({},this.input._formatOptions),{isobmff:V(H({},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=>wr(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(V(H({},e),{psshBoxes:t}))})})}),o=new ml({source:new na(r.location.path,e=>Y(this,null,function*(){var t,i;oe(e.isRoot);const n=V(H({},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;oe(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 o=((e,t,i)=>{let r=!1,n=0;const s=q(2,16),a=new Lr;return new ReadableStream({pull:o=>Y(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(ct(c)&&(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=Tl(c,d),f=new Uint8Array(d);for(let e=0;e16)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 kl(t.source),()=>Y(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=ka(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},fl),!1),r=new kl(i.source),n=yield r.requestSlice(0,Er);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Tl(n,Er),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ya(t)}}),()=>{t.free()});s=new fa(o).ref()}else oe(!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 qa)),initInput:null!=s?s:void 0,formatOptions:a});o._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:o,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=kt(this.inputCache,e=>e.age);oe(-1!==e),this.inputCache.splice(e,1)}return o}getLiveRefreshInterval(){return Y(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class wa extends yr{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=(()=>Y(this,null,function*(){oe(this.input._rootSource instanceof ia);const e=yield this.input._reader.requestEntireFile();oe(e);const t=Ol(e,e.length,{ignore:Xs}),{rootPath:i}=this.input._rootSource,r=[],n=[];for(let u=1;u"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((e,t)=>Y(this,null,function*(){var r,o,l,c;const u=[],d=e.attributes.get("codecs");let h;if(d)h=d.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=yield t.getTrackBackings(),r=yield Promise.all(i.map(e=>Y(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));h=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const f=e.attributes.get("video"),m=e.attributes.get("audio"),p=h.some(e=>Ki.includes(or(e))),g=h.some(e=>$i.includes(or(e)));if(null!==f&&!p){if(!s.includes(f))throw new Error(`Invalid M3U8 file; variant stream references video group "${f}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===f&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}if(null!==m&&!g){if(!a.includes(m))throw new Error(`Invalid M3U8 file; variant stream references audio group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}h=[...new Set(h)];let k=null,y=null;const b=e.attributes.getAsNumber("bandwidth");oe(null!==b);const T=e.attributes.getAsNumber("average-bandwidth"),v=e.attributes.get("name");for(const i of h){const d=or(i);if(null!==d)if(Ki.includes(d)){if(null!==k)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");k=i;const a=e.attributes.get("video");if(null===a){const i=e.attributes.get("resolution");let r=null,n=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),n=Number(e[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:We,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:k,pairingMask:BigInt("1")<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 i of n){const n=i.attributes.get("group-id"),s=i.attributes.get("type");if(n!==r||"audio"!==s.toLowerCase())continue;const a=null!=(l=i.attributes.get("channels"))?l:e.attributes.get("channels"),o=null!==a?Number(a.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:xa(i.attributes),autoselect:xa(i.attributes)||Ca(i.attributes),languageCode:Ba(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:y,pairingMask:BigInt("1")<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===We&&(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 Pa(u)):this.trackBackings.push(new Ia(u));this.internalTracks=l}))()}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),oe(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 va(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(this,null,function*(){return Ds})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Sa{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(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 Pa){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{oe(this instanceof Ia);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 V(H({},Ct),{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(){oe(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Pa extends Sa{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Ia extends Sa{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const xa=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}".`)},Ca=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}".`)},Ba=e=>{if(null===e)return We;const t=e.split("-")[0];return t||We};class Ea{constructor(){this._isIsobmff=!1}}class _a extends Ea{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return null;t.skip(4);const i=Nl(t,4);return"ftyp"!==i&&"styp"!==i?null:Nl(t,4)})}_createDemuxer(e){return new zr(e)}}class Ra extends _a{_canReadInput(e){return Y(this,null,function*(){const t=yield this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(ct(t)&&(t=yield t),!t)return!1;let r=Cl(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ct(t)&&(t=yield t),!t)return!1;r=Rl(t),n=16}if(r8)return!1;if(hn(i,r)!==nn.EBML)return!1;const n=mn(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(ct(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=pn(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case nn.EBMLVersion:if(1!==hn(s,r))return!1;break;case nn.EBMLReadVersion:if(1!==hn(s,r))return!1;break;case nn.DocType:if(gn(s,r)!==t)return!1;break;case nn.DocTypeVersion:if(hn(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Vn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ma extends Aa{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Da extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}const i=yield $n(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=hr(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(ct(s)&&(s=yield s),!s)return!1;const a=Cl(s);if(a===ur||a===dr)return!0;t=i.startPos+i.header.totalSize;const o=yield $n(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 Gn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Na extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return!1;const i=Nl(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Nl(t,4)})}_createDemuxer(e){return new ds(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Oa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,4);return ct(t)&&(t=yield t),!!t&&"OggS"===Nl(t,4)})}_createDemuxer(e){return new ss(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class La extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ct(i)&&(i=yield i),!!i&&"fLaC"===Nl(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ys(e)}}class za extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ct(i)&&(i=yield i),!i)return!1;const r=ms(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ct(i)&&(i=yield i),!i)return!1;const n=ms(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new gs(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ua extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,205);if(ct(t)&&(t=yield t),!t)return!1;const i=Tl(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 xs(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class qa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,7);if(ct(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Nl(t,7)))return!1;if(!(e._rootSource instanceof ia))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 wa(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Ds}}const Wa=new Ra,Ha=new Fa,Va=new Aa,ja=new Ma,Ka=new Da,Xa=new Na,$a=new Oa,Ga=new za,Qa=new La,Ya=new Ua,Ja=new qa,Za=[Ja,Wa,Ha,Va,ja,Xa,$a,Qa,Ka,Ga,Ya],eo=[Ja,Wa,Ha,Ka,Ga,Ya];var to=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});ft();let io=-1/0,ro=-1/0,no=null;"undefined"!==typeof FinalizationRegistry&&(no=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-io>=1e3&&(Pt._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."),io=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ro>=1e3&&(Pt._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."),ro=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class so{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const ao=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],oo=new Set(ao);class lo{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(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*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,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F;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||!oo.has(t.format))throw new TypeError("init.format must be one of: "+ao.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&&bt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=null!=(i=t.rotation)?i:0,this.timestamp=t.timestamp,this.duration=null!=(r=t.duration)?r:0;const m=null!=(n=t.layout)?n:bo(t.format,t.codedWidth,t.codedHeight);let p=null!=(s=t.colorSpace)?s:null;null===p&&(p="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:null!=(o=null==(a=t.visibleRect)?void 0:a.left)?o:0,top:null!=(c=null==(l=t.visibleRect)?void 0:l.top)?c:0,width:null!=(d=null==(u=t.visibleRect)?void 0:u.width)?d:t.codedWidth,height:null!=(f=null==(h=t.visibleRect)?void 0:h.height)?f:t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?fe(e):fe(e).slice(),this._layout=m,this.colorSpace=new mo(p)}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)&&bt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:null!=(p=null==(m=e.visibleRect)?void 0:m.x)?p:0,top:null!=(k=null==(g=e.visibleRect)?void 0:g.y)?k:0,width:null!=(b=null==(y=e.visibleRect)?void 0:y.width)?b:e.codedWidth,height:null!=(v=null==(T=e.visibleRect)?void 0:T.height)?v:e.codedHeight},this.rotation=null!=(w=null==t?void 0:t.rotation)?w:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(S=null==t?void 0:t.timestamp)?S:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new mo(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&bt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new lo(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Qe),duration:Math.trunc((null!=(x=t.duration)?x:0)*Qe)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const n=null!=(C=t.visibleRect)?C:{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(n.width,n.height),a=s.getContext("2d",{alpha:nt(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-n.left,-n.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n.width,height:n.height},this.squarePixelWidth=n.width,this.squarePixelHeight=n.height,this.rotation=null!=(B=t.rotation)?B:0,this.timestamp=t.timestamp,this.duration=null!=(E=t.duration)?E:0,this.colorSpace=new mo({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof so))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!ao.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=null!=(_=t.rotation)?_:0,this.timestamp=t.timestamp,this.duration=null!=(R=t.duration)?R:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(F=null==t?void 0:t.encodeOptions)?F:{},this.pixelAspectRatio=yt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==no||no.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return oe(null!==this._data),this._data instanceof so?new lo(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):po(this._data)?new lo(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(oe(this._layout),new lo(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new lo(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof so?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(yo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(t=e.format)?t:this.format))throw new Error("Cannot get allocation size when format is null.");if(po(this._data))return this._data.allocationSize(e);return vo(this,e).allocationSize}copyTo(e){return Y(this,arguments,function*(e,t={}){var i,r;if(!Ie(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(i=t.format)?i:this.format))throw new Error("Cannot copy video sample data when format is null.");if(oe(null!==this._data),po(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof so)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=yield i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const n=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}(i,yield this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},null!=(r=t.colorSpace)?r:"srgb"),!1);if(!(n instanceof lo))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return yield n.copyTo(e,t)}catch(u){i.error=u,i.hasError=!0}finally{to(i)}}}const n=vo(this,t);oe(this.format);const s=fe(e);if(s.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=e}else if(this._data instanceof Uint8Array)oe(this._layout),oe(this._layout.length===a.length),o=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");oe(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:fe(t.data),stride:4*this.codedWidth}]}const l=[],c=a.length;for(let d=0;di.byteLength)throw new Error("Source buffer OOB read.");if(a+c>s.byteLength)throw new Error("Destination buffer OOB write.");const n=i.subarray(r,r+c);s.set(n,a),r+=t,a+=e.destinationStride}l.push(u)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),i=this.format.includes("X")&&t.format.includes("A");if(e||i)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const n=[];for(const s of e)i.set(s.data,r),n.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:n[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return po(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(oe(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,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&&ko(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=t.crop;T&&(T=go(T,m,p));const{sx:v,sy:w,sWidth:S,sHeight:P}=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 I=f%180===0?1:y/b;e.translate(d/2,h/2),e.rotate(f*Math.PI/180),e.scale(1/I,I),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),v,w,S,P,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}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,n=e.height,[s,a]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,l=i.crop?i.crop.height:a;let c=0;2*r0?fo(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=c;p>1;p--){const e=r*q(2,p),t=n*q(2,p);f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*n,0,0,r,n),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(oe(null!==this._data),this._data instanceof so||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return Y(this,null,function*(){var t,i,r,n,s;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&ko(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const a=le(this.rotation+(null!=(t=e.rotate)?t:0)),[o,l]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=e.crop;c&&(c=go(c,o,l));const u=c?c.width:o,d=c?c.height:l,h=u/d;let f,m;void 0!==e.width&&void 0===e.height?(f=e.width,m=f/h):void 0===e.width&&void 0!==e.height?(m=e.height,f=m*h):void 0!==e.width&&void 0!==e.height?(f=e.width,m=e.height):(f=u,m=d),f=Ve(f,null!=(i=e.roundDimensionsTo)?i:1),m=Ve(m,null!=(r=e.roundDimensionsTo)?r:1);const p={width:f,height:m,fit:null!=(n=e.fit)?n:"fill",rotation:a,crop:null!=c?c:{left:0,top:0,width:o,height:l},alpha:null!=(s=e.alpha)?s:"keep"};for(const e of co){let t=e(this,p);if(ct(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=fo(p.width,p.height);return this._drawWithFitAndMipmapping(g,k,{fit:p.fit,rotation:p.rotation,crop:p.crop,targetIsFresh:y,fillBlack:"discard"===p.alpha}),new lo(g,{timestamp:this.timestamp,duration:this.duration,rotation:0})})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const co=[],uo=[];let ho=0;const fo=(e,t)=>{for(const n of uo)if(n.canvas.width===e&&n.canvas.height===t)return n.age=ho++,{canvas:n.canvas,context:n.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return uo.length>=3&&uo.splice(kt(uo,e=>e.age),1),uo.push({canvas:i,context:r,age:ho++}),{canvas:i,context:r,isNew:!0}};class mo{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(ke);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(be);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(ve);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 po=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,go=(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 oe(s>=0),oe(a>=0),{left:r,top:n,width:s,height:a}},ko=(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.")},yo=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.")}},bo=(e,t,i)=>{const r=To(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},To=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:Oe(e),oe(!1)}},vo=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=wo(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let a;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");a=t.format}else a=e.format;return Po(n,a,s)},wo=(e,t,i,r,n)=>{const s=H({},e);if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!So(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},So=(e,t)=>{if(null===e)return!0;const i=To(e);for(let r=0;r{const r=To(t),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const a=[],o=[];for(let l=0;l4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let e=0;e 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/(Bo(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*Bo(this.format);if(i.byteLength=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=Bo(r),o=Eo(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(!Ie(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&&!Io.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:n}=t;let{planeIndex:s}=t,a=this.format;const o=null!=i?i:this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,u=null!=n?n:0;if(u>=l)throw new RangeError("frameOffset out of range");const d=void 0!==r?r:l-u;if(d>l-u)throw new RangeError("frameCount out of range");const h=Bo(o),f=Eo(o);if(f&&s>=c)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?d:d*c)*h;if(e.byteLength2&&o!==a)return void Ao(this._data,p,a,o,c,s,u,d);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:d,format:o})}catch(w){if("f32-planar"===o)throw w;a="f32-planar"}}const k=_o(a),y=Bo(a),b=Eo(a);let T;if(this._data instanceof xo){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*y*(b?1:c);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)T=e(s),s=0;else{T=new Uint8Array(l*y*c);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(n,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Co({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof xo?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fo(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof xo?this._createAudioDataFromData():Fo(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Eo(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const n=Math.min(s,o),l=new Float32Array(i*n);for(let t=0;t0;){const n=Math.min(s,o),c=new Float32Array(i*n);for(let t=0;t{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")}},Eo=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_o=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)}},Ro=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,qe(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,qe(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,qe(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Fo=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Ao=(e,t,i,r,n,s,a,o)=>{const l=_o(i),c=Ro(r),u=Bo(i),d=Bo(r),h=Eo(i);if(Eo(r))if(h){const r=new ArrayBuffer(o*u),n=me(r);e.copyTo(r,{planeIndex:s,frameOffset:a,frameCount:o,format:i});for(let e=0;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.")},Oo=e=>{if(!mt(e))throw new TypeError("timestamp must be a number.")},Lo=(e,t,i)=>i.verifyKeyPackets?t.then(t=>Y(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class zo{constructor(e){if(!(e instanceof el))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return Y(this,arguments,function*(e={}){if(No(e),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return Y(this,arguments,function*(e={}){No(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;oe("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;oe("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 Tr))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 Tr))throw new TypeError("endPacket must be an EncodedPacket.");if(No(i),this._track.input._disposed)throw new gl;const r=[];let{promise:n,resolve:s}=Ae(),{promise:a,resolve:o}=Ae(),l=!1,c=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(()=>Y(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}=Ae()),yield a):(r.push(u),s(),({promise:n,resolve:s}=Ae()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{next(){return Y(this,null,function*(){for(;;){if(m.input._disposed)throw new gl;if(c)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return Y(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Uo{constructor(e,t){this.onSample=e,this.onError=t}}class qo{mediaSamplesInRange(e=-1/0,t=1/0,i){Oo(e),Oo(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=Ae(),{promise:l,resolve:c}=Ae(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g=V(H({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){var i;f=yield this._createDecoder(i=>{c(),i.timestamp>=t&&(d=!0),d?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}=Ae())))},e=>{p||(m=e,p=!0,o())});const k=this._createPacketSink(),y=null!=(i=yield k.getKeyPacket(e,g))?i:yield k.getFirstKeyPacket(g);let b=y;const T=k.packets(null!=y?y:void 0,void 0,g);for(yield T.next();b&&!d&&!this._track.input._disposed;){const e=Wo(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:l,resolve:c}=Ae()),yield l;continue}f.decode(b);const t=yield T.next();if(t.done)break;b=t.value}yield T.return(),h||this._track.input._disposed||(yield f.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{null==f||f.close()});const k=this._track,y=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return Y(this,null,function*(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new gl;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};yield a}})},return(){return Y(this,null,function*(){return h=!0,d=!0,c(),o(),y(),{value:void 0,done:!0}})},throw(e){return Y(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 Z(this,null,function*(){Symbol.iterator in e?yield*ee(e[Symbol.iterator]()):yield*ee(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=Ae(),{promise:o,resolve:l}=Ae(),c=!1,u=!1,d=null,h=null,f=!1;const m=e=>{n.push(e),a(),({promise:s,resolve:a}=Ae())},p=V(H({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){d=yield this._createDecoder(e=>{if(l(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(h=e,f=!0,a())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=()=>Y(this,null,function*(){oe(s),oe(d);let t=s;for(d.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=Ae()),yield o;if(u)break;const r=yield e.getNextPacket(t,p);oe(r),d.decode(r),t=r}g=-1}),y=()=>Y(this,null,function*(){oe(d),yield d.flush();for(let e=0;e{f||(h=e,f=!0,a())}).finally(()=>{null==d||d.close()});const g=this._track,k=()=>{for(const e of n)null==e||e.close()};return{next(){return Y(this,null,function*(){for(;;){if(g.input._disposed)throw u=!0,k(),new gl;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),h;if(n.length>0){const e=n.shift();return oe(void 0!==e),l(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};yield s}})},return(){return Y(this,null,function*(){return u=!0,l(),a(),k(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Wo=e=>0===e?40:8;class Ho extends Uo{constructor(e,t,i,r,n,s){var a,o,l,c,u,d,h,f;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const m=Mo.find(e=>e.supports(i,r));if(m)this.customDecoder=new m,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof lo))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();oe(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(at()){if("avc"===i&&this.decoderConfig.description){const e=Qt(fe(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Jt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=V(H({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=ei(t),this.decoderConfig=V(H({},this.decoderConfig),{description:Gt(e)})))}}Se(this.decoderConfig.colorSpace)||(this.decoderConfig=V(H({},this.decoderConfig),{colorSpace:{primaries:null!=(o=null==(a=this.decoderConfig.colorSpace)?void 0:a.primaries)?o:"bt709",matrix:null!=(c=null==(l=this.decoderConfig.colorSpace)?void 0:l.matrix)?c:"bt709",transfer:null!=(d=null==(u=this.decoderConfig.colorSpace)?void 0:u.transfer)?d:"bt709",fullRange:null!=(f=null==(h=this.decoderConfig.colorSpace)?void 0:h.fullRange)&&f}}))}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:(oe(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)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(oe(this.decoder),it()||Fe(this.inputTimestamps,e.timestamp,e=>e),at()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of Wt(e.data,this.decoderConfig)){const r=Ht(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Nt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&fe(t.description)[4];return Xt(e,i+1)}return Kt(e)})(t,this.decoderConfig);e=new Tr(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=mi(e.data,this.decoderConfig);t&&(e=new Tr(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new jo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();oe(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();oe(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=wi(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 ti(e,this.decoderConfig)){const i=ii(e[t.offset]);if(i===Lt.RASL_N||i===Lt.RASL_R)return!0}return!1}sampleHandler(e){if(it()){if(this.sampleQueue.length>0&&e.timestamp>=ce(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Fe(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();oe(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){return Y(this,null,function*(){const i=Ae();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){oe(this.merger);const i=yield this.merger.merge(e,t);r.sample=new lo(i)}else r.sample=new lo(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){Me(this.finalSamples,r),this.onError(n)}finally{Me(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return Y(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),yield Promise.all(this.mergeAlphaPromises),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),it()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1})}close(){var e;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,null==(e=this.merger)||e.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}let Vo=null;class jo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Vo){const e=new Blob([`(${Ko.toString()})()`],{type:"application/javascript"});Vo=URL.createObjectURL(e)}const e=qe(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=Ae();this.pendingRequests.set(i,r);const n=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,n.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Ko=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>Y(null,null,function*(){try{const e=yield r(n,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{n.close(),s.close()}}))});const r=(e,t)=>Y(null,null,function*(){const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),l=i.includes("P12"),c=r.includes("P10"),u=r.includes("P12");if(c!==o||u!==l)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return yield n(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return yield s(e,t,i);if("NV12"===i)return yield a(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)}),n=(e,t,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=new Uint8Array(4*d);yield e.copyTo(h);const f=yield o(t,c,u,1);for(let e=0,t=3;eY(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=i.includes("P10"),h=i.includes("P12"),f=d||h?2:1;let m,p;i.startsWith("I420")?(m=Math.ceil(c/2),p=Math.ceil(u/2)):i.startsWith("I422")?(m=Math.ceil(c/2),p=u):(m=c,p=u);const g=c*u,k=g*f,y=m*p*f,b=new Uint8Array(k+2*y+g*f);yield e.copyTo(b);const T=yield o(t,c,u,f),v=k+2*y;b.set(T,v);const w={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:c,codedHeight:u,timestamp:e.timestamp,duration:null!=(l=e.duration)?l:void 0,transfer:[b.buffer]};return new VideoFrame(b,w)}),a=(e,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=Math.ceil(c/2)*Math.ceil(u/2),f=e.allocationSize();t&&t.byteLength===f||(t=new Uint8Array(f)),yield e.copyTo(t);const m=new Uint8Array(d+2*h+d);m.set(t.subarray(0,d),0);const p=d,g=d+h,k=d;for(let e=0;eY(null,null,function*(){const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),yield t.copyTo(e);const a=t.format;if("RGBA"===a||"BGRA"===a||"RGBX"===a||"BGRX"===a){const t="RGBA"===a||"RGBX"===a?0:2,n=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class $o extends qo{constructor(e,t={}){if(!(e instanceof rl))throw new TypeError("videoTrack must be an InputVideoTrack.");Xo(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ot("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getRotation();let n=yield this._track.getDecoderConfig();const s=yield this._track.getTimeResolution();return oe(i&&n),n=V(H({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new Ho(e,t,i,n,r,s)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Go{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof rl))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&&ko(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&Xo(t.decoderOptions),this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._options=t,this._fit=null!=(r=t.fit)?r:"fill",this._videoSampleSink=new $o(e,t.decoderOptions),this._canvasPool=Array.from({length:null!=(n=t.poolSize)?n:0},()=>null)}_ensureInit(){var e;return null!=(e=this._initPromise)?e:this._initPromise=(()=>Y(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=go(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||nt()});oe(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&nt()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return Y(this,null,function*(){Oo(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class Qo extends Uo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const n=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(n*s)/s),e(t)},s=Do.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 Co))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{n(new Co(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(oe(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(oe(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return Y(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Yo extends Uo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,oe(Xi.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=ar(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-q(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<(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<e.getUint16(t,s)-q(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):oe(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Le(e,t,s)-q(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Le(e,t,i)<<8>>8)(e,t,s):oe(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-q(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):oe(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):oe(!1);break;default:Oe(n),oe(!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+q(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:Oe(n),oe(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=me(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=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new Co({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return Y(this,null,function*(){})}close(){}}class Jo extends qo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(ot("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getDecoderConfig();return oe(i&&r),Xi.includes(r.codec)?new Yo(e,t,r):new Qo(e,t,i,r)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Zo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Jo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return Y(this,null,function*(){Oo(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return Ue(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Ue(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class el{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof rl}isAudioTrack(){return this instanceof nl}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return Y(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return tl(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return Y(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return tl(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return Y(this,null,function*(){return this._backing.getName()})}get name(){return tl(this._backing.getName(),"name","getName")}getTimeResolution(){return Y(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return tl(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return Y(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return Y(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return Y(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return Y(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return tl(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return Y(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return Y(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return Y(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 Y(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,H({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 je(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return Y(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return Y(this,null,function*(){const i=new zo(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=te(i.packets(void 0,void 0,H({metadataOnly:!0},t)));o=!(l=yield u.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){c=[l]}finally{try{o&&(l=u.return)&&(yield l.call(u))}finally{if(c)throw c[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 Y(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return Y(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof el))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 Y(this,null,function*(){return this.input.getTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return Y(this,null,function*(){return this.input.getVideoTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return Y(this,null,function*(){return this.input.getAudioTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return Y(this,null,function*(){return this.input.getPrimaryVideoTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return Y(this,null,function*(){return this.input.getPrimaryAudioTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return Y(this,null,function*(){e&&(e=il(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=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const tl=(e,t,i)=>{if(ct(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},il=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 ct(r)?r.then(i):i(r)}:void 0};class rl extends el{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:"prores"===(yield this._backing.getCodec())})}getCodedWidth(){return Y(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return tl(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return Y(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return tl(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return Y(this,null,function*(){return this._backing.getRotation()})}get rotation(){return tl(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return Y(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return tl(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return Y(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return tl(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return Y(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=yt({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=yt({num:tl(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:tl(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return Y(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=tl(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return tl(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return Y(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=tl(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return tl(r,"displayHeight","getDisplayHeight")}getColorSpace(){return Y(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return Y(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return Y(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Mo.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))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 oe(i),wi(t,i,e.data)})}computeFrameRateMetrics(){return Y(this,arguments,function*(e={}){var t,i;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!mt(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const r=yield this.getTimeResolution(),n=null!=(t=e.targetPacketCount)?t:256,s=new zo(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=te(s.packets(void 0,void 0,{metadataOnly:!0}));c=!(u=yield h.next()).done;c=!1){const e=u.value;if(a.length>=n&&e.timestamp>=o)break;a.push(e.timestamp),o=Math.max(o,e.timestamp),l++}}catch(u){d=[u]}finally{try{c&&(u=h.return)&&(yield u.call(h))}finally{if(d)throw d[0]}}const f=new Float64Array(a.length);for(let R=0;Re-t),I=S-1>>1,x=S>>1;let C=0,B=0,E=0;for(const R of P)if(E+=b.get(R),0===C&&E>I&&(C=R),E>x){B=R;break}const _=(k/C+k/B)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:hl(_),minFrameRate:k/v,maxFrameRate:k/T,averageFrameRate:k*S/w,medianFrameRate:_,frameRateIsConstant:null!==g&&1===T&&1===v,probedPacketCount:l}})}}class nl extends el{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(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 Y(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return tl(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return Y(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return tl(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Do.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 Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const sl=e=>-(null!=e?e:-1/0),al=e=>-e,ol=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 ct(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return ct(r)?r.then(i):i(r)}:void 0}},ll=(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 ct(s)?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 ct(o)||ct(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),cl=(e,t)=>Y(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=>ct(e))){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=>ct(e))?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;oe.track)}),ul=(e,t)=>{const i=1e6,r=1+1e-9,n=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let v=1;v0))return null;s[v-1]=t}const a=s.slice();a.sort();let o=a[Math.floor(.05*a.length)];for(let v=0;v<6;v++){let e=0,t=0;for(const n of s){const i=Math.max(1,Math.round(n/o));Math.abs(n-i*o)>=r||(e+=n,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let l=0,c=0,u=0;for(const v of s){const e=Math.max(1,Math.round(v/o));Math.abs(v-e*o)>=r||(l++,c+=v,u+=e)}if(l/s.length<.98)return null;o=c/u;const d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const v of n){if(vp)continue;const e=Math.abs(v/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,n=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof Ea)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ea||e.source instanceof ta))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ea&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof ml))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=null!=(t=e.initInput)?t:null,this._formatOptions=null!=(i=e.formatOptions)?i:{},e.source instanceof ea?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return Y(this,null,function*(){oe(this._rootSource instanceof ia);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&&ra(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ra(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>Y(this,null,function*(){const i=yield this._getSourceUncached(e);if(gt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=kt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);oe(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),Me(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);oe(-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=(()=>Y(this,null,function*(){var e;this._reader=new kl(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 pl}))()}get source(){return this._rootSource}getFormat(){return Y(this,null,function*(){return yield this._getDemuxer(),oe(this._format),this._format})}canRead(){return Y(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof pl)return!1;throw e}})}getFirstTimestamp(e){return Y(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._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>{var t;return null!=(t=null==e?void 0:e.timestamp)?t:1/0}));return r===1/0?0:r})}computeDuration(e,t){return Y(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 Y(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 Y(this,null,function*(){e&&(e=ol(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return cl(t,e)})}getVideoTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return cl(t,e)})}getAudioTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return cl(t,e)})}getPrimaryVideoTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=ll(e,{sortBy:e=>Y(null,null,function*(){return[al((yield e.getDisposition()).default),al(yield e.hasPairableAudioTrack()),al(!(yield e.hasOnlyKeyPackets())),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=yield this.getPrimaryVideoTrack(),r=ll(e,{sortBy:e=>Y(this,null,function*(){return[al(!i||e.canBePairedWith(i)),al((yield e.getDisposition()).default),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return Y(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 rl(this,e):new nl(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class pl extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class gl extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class kl{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 gl;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 yl(t,me(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Zs);return ct(r)?r.then(t=>t?new yl(t.bytes,t.view,t.offset,e,i):null):r?new yl(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new gl;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(oe(null!==this.fileSizeNonStrict),this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i)));return ct(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>Y(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(ct(i)&&(i=yield i),!i||0===i.length)break;const r=Tl(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return new yl(i,me(i),0,0,t)}))()}}class yl{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 yl(e,me(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new yl(this.bytes,this.view,this.offset,e,e+t)}}const bl=(e,t)=>{if(e.filePose.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.`)},Tl=(e,t)=>{bl(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},vl=e=>(bl(e,1),e.view.getUint8(e.bufferPos++)),wl=(e,t)=>{bl(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Sl=e=>{bl(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Pl=e=>{bl(e,3);const t=Le(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Il=e=>{bl(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},xl=(e,t)=>{bl(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Cl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Bl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},El=e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},_l=(e,t)=>{let i,r;return t?(i=xl(e,!0),r=xl(e,!0)):(r=xl(e,!1),i=xl(e,!1)),4294967296*r+i},Rl=e=>4294967296*Cl(e)+Cl(e),Fl=e=>4294967296*El(e)+Cl(e),Al=e=>{const t=Bl(e),i=(e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Ml=e=>{bl(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Dl=e=>{bl(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Nl=(e,t)=>{bl(e,t);let i="";for(let r=0;rpe.decode(Tl(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 Ll,zl,Ul,ql;(zl=Ll||(Ll={}))[zl.Unsynchronisation=128]="Unsynchronisation",zl[zl.ExtendedHeader=64]="ExtendedHeader",zl[zl.ExperimentalIndicator=32]="ExperimentalIndicator",zl[zl.Footer=16]="Footer",(ql=Ul||(Ul={}))[ql.ISO_8859_1=0]="ISO_8859_1",ql[ql.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",ql[ql.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",ql[ql.UTF_8=3]="UTF_8";const Wl=128,Hl=10,Vl=["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"],jl=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Tl(e,Wl-3)),e.filePos=r;const n=Kl(e,30);n&&(null!=t.title||(t.title=n));const s=Kl(e,30);s&&(null!=t.artist||(t.artist=s));const a=Kl(e,30);a&&(null!=t.album||(t.album=a));const o=Kl(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Tl(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=Kl(e,28),e.skip(2)}else e.skip(-30),u=Kl(e,30);u&&(null!=t.comment||(t.comment=u));const d=vl(e);d{const i=Tl(e,t),r=ut(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Nl(e,3),r=vl(e),n=vl(e),s=vl(e),a=Cl(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=mr(a);return s&Ll.Footer&&(o+=Hl),{majorVersion:r,revision:n,flags:s,size:o}},$l=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void Pt._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Ll.Footer?t.size-Hl:t.size,u=Tl(e,c),d=new Gl(t,u);if(t.flags&Ll.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Ll.ExtendedHeader){const e=d.readU32();3===t.majorVersion?d.pos+=e:d.pos+=e-4}for(;d.pos<=d.bytes.length-d.frameHeaderSize();){const e=d.readId3V2Frame();if(!e)break;const c=d.pos,u=d.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&Ll.Unsynchronisation)),h)Pt._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)Pt._warn(`Skipping compressed ID3v2 frame ${e.id}`),d.pos=u;else{if(m&&d.ununsynchronizeRegion(d.pos,u),null!=i.raw||(i.raw={}),"TXXX"===e.id){const e=null!=(n=(r=i.raw).TXXX)?n:r.TXXX={},t=d.readId3V2TextEncoding(),s=d.readId3V2Text(t,u),a=d.readId3V2Text(t,u);null!=e[s]||(e[s]=a)}else"T"===e.id[0]?null!=(s=i.raw)[a=e.id]||(s[a]=d.readId3V2EncodingAndText(u)):null!=(o=i.raw)[l=e.id]||(o[l]=d.readBytes(e.size));switch(d.pos=c,e.id){case"TIT2":case"TT2":null!=i.title||(i.title=d.readId3V2EncodingAndText(u));break;case"TIT3":case"TT3":null!=i.description||(i.description=d.readId3V2EncodingAndText(u));break;case"TPE1":case"TP1":null!=i.artist||(i.artist=d.readId3V2EncodingAndText(u));break;case"TALB":case"TAL":null!=i.album||(i.album=d.readId3V2EncodingAndText(u));break;case"TPE2":case"TP2":null!=i.albumArtist||(i.albumArtist=d.readId3V2EncodingAndText(u));break;case"TRCK":case"TRK":{const e=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}null!=i.genre||(i.genre=e)}break;case"TDRC":case"TDAT":{const e=d.readId3V2EncodingAndText(u),t=new Date(e);Number.isNaN(t.getTime())||null!=i.date||(i.date=t)}break;case"TYER":case"TYE":{const e=d.readId3V2EncodingAndText(u),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=i.date||(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.lyrics||(i.lyrics=d.readId3V2Text(e,u))}break;case"COMM":case"COM":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.comment||(i.comment=d.readId3V2Text(e,u))}break;case"APIC":case"PIC":{const e=d.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=d.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=d.readId3V2Text(e,u);const n=d.readU8(),s=d.readId3V2Text(e,u).trimEnd(),a=u-d.pos;if(a>=0){const e=d.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:d.pos+=e.size}d.pos=u}}};class Gl{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{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:mr(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 Ul.ISO_8859_1:{let e="";for(let t=0;t0===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=ut(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=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}case Ul.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=ut(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 Ul.UTF_8:{const e=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ql{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch(n){i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(s){try{null==r||r.disconnect()}catch(a){console.warn("MediaBunny gain setup cleanup:",a)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),s}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{null==t||t.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Yl{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(n){r=!0,i=n}try{e.disconnect()}catch(n){r||(r=!0,i=n)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const n=function(e,t,i,r){const n=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(n+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(n,r),offset:n=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===n.offset?s.start(n.startAt):s.start(n.startAt,n.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,n.endMediaTime)}catch(a){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw a}}}const Jl=Symbol("cancelled");class Zl{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Jl);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function ec(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class tc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}stopIterator(){return Y(this,null,function*(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),yield t})}cancel(){var e;null==(e=this.task)||e.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}run(e){return Y(this,null,function*(){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Zl;this.task=r;let n=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!n||this.host.audioIterator===n);try{for(n=t.buffers(this.host.currentTime),this.host.audioIterator=n;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=yield r.wait(n.next());if(i===Jl||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if((yield r.wait(this.contexts.resume(i)))===Jl||!s())return;ec(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(yield r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(yield r.delay(50))||!s())return}}catch(a){if(s())throw a}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}})}}class ic{constructor(e,d){X(this,u),X(this,t,!1),X(this,i,0),X(this,r),X(this,n),X(this,s),X(this,a,null),X(this,o,null),X(this,l,null),X(this,c),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,$(this,r,new Ql(this)),$(this,n,new Yl(this)),$(this,s,new tc(this,K(this,r),K(this,n))),$(this,c,d)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){K(this,r).ensure(e)}updateGain(){K(this,r).updateGain()}stopQueuedNodes(){K(this,n).stop()}stopIterator(){return Y(this,null,function*(){yield K(this,s).stopIterator()})}handleNoAudioTrack(){K(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){Q(this,i)._++;try{this.pause()}finally{$(this,l,null),this.input=null,this.audioSink=null}}load(e,r){return Y(this,null,function*(){if(K(this,t))return;this.cancelPending();const n=K(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>G(this,u,d).call(this,e,n,r));$(this,l,s);try{yield s}finally{K(this,l)===s&&$(this,l,null)}})}runIterator(e){return Y(this,null,function*(){K(this,t)||(yield K(this,s).run(e))})}play(){return Y(this,null,function*(){if(K(this,t))return;if(K(this,o))return K(this,o);if(!this.paused)return;const e=new Zl;$(this,a,e);const r=K(this,i),n=G(this,u,f).call(this,e,r);$(this,o,n);try{yield n}finally{K(this,a)===e&&($(this,a,null),$(this,o,null))}})}pause(){var e;this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,null==(e=K(this,a))||e.cancel(),$(this,a,null),$(this,o,null),K(this,s).cancel(),this.stopQueuedNodes()}seek(e){return Y(this,null,function*(){var i,r;if(K(this,t))return;const n=!this.paused;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.latestScheduledEndTime=this.playbackTimeAtStart;const a=++this.asyncId;n&&G(this,u,h).call(this,a)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){var i,r;if(K(this,t)||e===this.playbackRate)return;const n=this.currentTime;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=n,this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.playbackRate=e,this.latestScheduledEndTime=n;const a=++this.asyncId;this.paused||G(this,u,h).call(this,a)}destroy(){if(K(this,t))return;$(this,t,!0),Q(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>K(this,r).destroy()])try{t()}catch(n){e.push(n)}if(this.input=null,this.audioSink=null,$(this,l,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakSet,d=function(e,r,n){return Y(this,arguments,function*({input:e,audioTrack:r,duration:n},s,a){const o=()=>!K(this,t)&&K(this,i)===s;if(o()){this.input=e,this.duration=n;try{const e=r&&null!==r.codec&&(yield r.canDecode());if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new Zo(r)}else this.handleNoAudioTrack();o()&&(null==a||a())}catch(l){if(o())throw l}}})},h=function(e){this.runIterator(e).catch(i=>{if(!K(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{K(this,c)?K(this,c).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=function(e,n){return Y(this,null,function*(){const s=()=>!K(this,t)&&!e.cancelled&&K(this,i)===n;try{const t=K(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if((yield e.wait(K(this,r).resume(t)))===Jl||!s())return}if(K(this,l)){if((yield e.wait(K(this,l)))===Jl||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,G(this,u,h).call(this,++this.asyncId)}catch(a){if(s())throw a}})};const rc=new WeakMap;function nc(e,t,i){return Y(this,null,function*(){var r;const{input:n,loadSeq:s}=e;if(!(null==(r=e.media)?void 0:r.isHls)||!n||e.destroyed)return;const a={};rc.set(e,a);const o=()=>!e.destroyed&&e.loadSeq===s&&e.input===n&&rc.get(e)===a;for(;o();){const r=e.media;if(!(null==r?void 0:r.isHls))return;let s;try{s=yield i(n,r,t,o)}catch(l){if(!o())return;if(e.media===r)throw l;continue}if(!o())return;if(e.media===r){if(s)try{yield e.replaceTracks(s)}catch(l){if(o())throw l}return}}})}function sc(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getVideoTracks();if(!r())return null;const a="auto"===i?yield e.getPrimaryVideoTrack():null!=(n=s.find(e=>e.id===i))?n:t.videoTrack;if(!r()||!a)return null;let o=t.audioTrack,l=t.audioMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableAudioTrack(),l="auto"),{videoTrack:a,audioTrack:o,videoMode:"auto"===i?"auto":"manual",audioMode:l}})}function ac(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getAudioTracks();if(!r())return null;const a="auto"===i?t.videoTrack?yield t.videoTrack.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack():null!=(n=s.find(e=>e.id===i))?n:t.audioTrack;if(!r()||!a)return null;let o=t.videoTrack,l=t.videoMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableVideoTrack(),l="auto"),{videoTrack:o,audioTrack:a,videoMode:l,audioMode:"auto"===i?"auto":"manual"}})}function oc(e){return Y(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const lc=/\.m3u8(?:$|[?#])/i;function cc(e){return"string"===typeof e&&lc.test(e)}function uc(e){const t=function(e){return"string"===typeof e?new ua(e):e instanceof Blob?new aa(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new fa(e):null!=e?e:null}(e);return t?new ml({source:t,formats:cc(e)?eo:Za}):null}class dc{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){var e;return null==(e=this.controller)?void 0:e.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}wait(e,t){return Y(this,null,function*(){try{yield Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}})}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,null==e||e.dispose()}cancel(){var e;if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),null==(e=this.controller)||e.abort(),this.disposeInput()}}}function hc(e){return Y(this,arguments,function*({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),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 fc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class mc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return V(H({},fc()),{source:this.host.loadSeq,complete:fc()})}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,null==e||e.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,null==e||e.complete.resolve(),null==e||e.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}runPlay(e){return Y(this,null,function*(){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(yield this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,yield this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),ec(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}})}seek(e,t){return this.position(t=>Y(this,null,function*(){const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();yield Promise.all([i,r])}),["seeked"],!1,t)}replace(e,t){return this.position(i=>Y(this,null,function*(){e.duration=yield hc(e),i()&&(this.host.media=e,yield Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(yield Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))}),["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=null!=r?r:this.seeking?this.wanted:!this.host.paused,this.cancelPlay();const n=this.seeking,s=this.operation();return this.seeking=s,null==n||n.complete.resolve(),null==n||n.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}runPosition(e,t,i,r){return Y(this,null,function*(){const n=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!n())return;if(this.host.ended=!1,this.host.seeking=!0,ec(this.host.events,n,["seeking","waiting"]),!n())return;if(r||this.stop(),!n())return;if(yield t(n),!n())return;if(this.host.seeking=!1,e.complete.resolve(),ec(this.host.events,n,i),!n())return;this.seeking=null,s=this.wanted}catch(a){if(!n())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(a),a}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&(yield this.play())})}}const pc=new WeakMap,gc=new WeakMap;function kc(e){const t=gc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>{var t;return null!=(t=e.value)?t:null});gc.set(e,i);const r=()=>{gc.get(e)===i&&gc.delete(e)};return i.then(r,r),i}function yc(e,t,i,r,n){const s=i?Math.max(.06,r/Math.max(1,n)):0;return i&&e{if(this.image===n&&t()){this.cancel();try{i(n)}catch(e){r(e)}}},n.onerror=()=>{this.image===n&&this.cancel()},n.src=e}}class Tc{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}update(e){return Y(this,null,function*(){var t;const i=this.host.videoIterator;if(!i||!this.ready()||!this.current(e)||this.host.isFetching)return;const r={};this.fetching=r,this.host.isFetching=!0;const n=()=>this.current(e)&&this.host.videoIterator===i;try{for(;n();){const e=yield kc(i);if(!n()||!e)return;const r=null==(t=this.host.audioClock)?void 0:t.currentTime;if(void 0===r)return;const s=yc(e.timestamp,r,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==s){if("draw"!==s)return void(this.host.nextFrame=e);this.draw(e)}}}catch(s){if(n())throw s}finally{this.fetching===r&&(this.fetching=null,this.host.isFetching=!1)}})}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void ec(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(ec(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!K(this,T),e=>G(this,P,E).call(this,e,!0),e=>G(this,P,C).call(this,e)))}preflight(e,t,i){return Y(this,null,function*(){return function(e,t,i,r,n=()=>!0){return Y(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||cc(e))return!0;try{const t=yield fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if((null==r?void 0:r.aborted)||!n())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!((null==r?void 0:r.aborted)||!n())&&(console.warn("Preflight check failed:",s),!0)}})}(e,this.preflightRange,this.events,t,i)})}drawPoster(){if(K(this,b)||!this.poster||this.posterDrawn)return;const e=K(this,m);K(this,v).draw(this.poster,()=>G(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,G(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>G(this,P,C).call(this,e))}stopIterator(){return Y(this,null,function*(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,yield function(e){if(!e)return Promise.resolve();const t=pc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return pc.set(e,i),i}(e)})}clear(){G(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){Q(this,m)._++,Q(this,p)._++,this.stop(),G(this,P,B).call(this),K(this,v).cancel(),$(this,T,!1),$(this,g,null),$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null}load(e,t){return Y(this,null,function*(){if(K(this,b))return;this.cancelPending();const i=K(this,m),r=K(this,p);$(this,T,!0);const n=Promise.resolve().then(()=>G(this,P,_).call(this,e,i,r,t));$(this,g,n);try{yield n}finally{K(this,g)===n&&$(this,g,null)}})}handleNoVideoTrack(){K(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}resetIterator(e){return Y(this,null,function*(){if(K(this,b))return;const t=K(this,m),i=++Q(this,p)._,r=K(this,g);this.stop(),K(this,v).cancel(),$(this,T,!0);try{r&&(yield r),yield G(this,P,R).call(this,e,t,i)}catch(n){if(G(this,P,I).call(this,t)&&K(this,p)===i)throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})}updateNextFrame(e){return Y(this,null,function*(){yield K(this,w).update(e)})}render(){K(this,w).render()}start(e){K(this,w).start(e)}stop(){K(this,w).stop()}seek(e){return Y(this,null,function*(){yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){K(this,b)||($(this,b,!0),Q(this,m)._++,K(this,w).destroy(),K(this,v).cancel(),G(this,P,B).call(this),this.posterDrawn=!1,$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,T=new WeakMap,v=new WeakMap,w=new WeakMap,S=new WeakMap,P=new WeakSet,I=function(e){return!K(this,b)&&K(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){K(this,b)||(G(this,P,B).call(this),K(this,S)?K(this,S).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){K(this,v).cancel(),t&&this.clear(),G(this,P,x).call(this).drawImage(e.canvas,0,0)},_=function(e,t,i,r){return Y(this,null,function*(){if(G(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:n,videoTrack:s,duration:a}=e;if(this.input=n,this.duration=a,!s)return this.handleNoVideoTrack(),void(null==r||r());const o=null!==s.codec&&(yield s.canDecode());if(!G(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void(null==r||r());const l=yield s.canBeTransparent();if(!G(this,P,I).call(this,t))return;$(this,k,()=>new Go(s,{poolSize:2,fit:"contain",alpha:l})),this.videoSink=K(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==r||r(),G(this,P,I).call(this,t)&&(yield G(this,P,R).call(this,0,t,i))}catch(n){if(G(this,P,I).call(this,t))throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})},R=function(e,t,i){return Y(this,null,function*(){if(!G(this,P,I).call(this,t)||K(this,p)!==i)return;G(this,P,B).call(this),K(this,k)&&this.videoSink===K(this,y)&&(this.videoSink=K(this,k).call(this));const r=this.videoSink;if(!r||!G(this,P,I).call(this,t))return;$(this,y,r);const n=r.canvases(e);this.videoIterator=n;const s=()=>G(this,P,I).call(this,t)&&K(this,p)===i&&this.videoIterator===n,a=yield kc(n);if(!s())return;const o=yield kc(n);s()&&(this.nextFrame=o,a?G(this,P,E).call(this,a,!1):this.drawPoster())})};class wc{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l;X(this,F),this.events=i,this.option=r,this.audio=new ic(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new vc({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,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,$(this,F,new mc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,K(this,F).ended(),this.audio.pause())})}load(e){return Y(this,null,function*(){var t,i;if(this.destroyed)return;const r=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),null==(t=this.loadSession)||t.cancel(),r!==this.loadSeq||this.destroyed)return;if(this.pause(),r!==this.loadSeq||this.destroyed)return;this.disposeInput();const n=new dc;this.loadSession=n,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,n.defer(()=>this.events.emit("waiting")),n.defer(()=>this.events.emit("loadstart"));const s=Number.isFinite(this.option.loadTimeout)&&null!=(i=this.option.loadTimeout)?i:0;try{yield n.wait(this.performLoad(e,r,n),s)}catch(a){if(r!==this.loadSeq)return;const e=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),n.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}})}performLoad(e,t){return Y(this,arguments,function*(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(yield this.video.preflight(e,i.signal,r))||!r())return;const n=uc(e);if(!n)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(n);const s=yield function(e,t){return Y(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield hc({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=cc(t);return{input:e,videoTrack:i,audioTrack:r,duration:n,isLive:!Number.isFinite(n)&&Boolean(s&&(yield s.isLive())),isHls:a,videoMode:a?"auto":"manual",audioMode:a?"auto":"manual"}})}(n,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=n,this.media=s;const a=function(e,t){let i=!1,r=!1,n=!1;function s(s){t()&&!n&&("video"===s?i=!0:r=!0,i&&r&&(n=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,ec(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,a.video),t=r()?this.audio.load(s,a.audio):Promise.resolve();if(yield Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,ec(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}})}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){var e;null==(e=this.loadSession)||e.disposeInput(),this.input=null,this.media=null}replaceTracks(e){return Y(this,null,function*(){if(this.media&&!this.destroyed)return K(this,F).replace(H(H({},this.media),e),this.currentTime)})}selectHlsQuality(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,sc)}(this,e)})}selectHlsAudio(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,ac)}(this,e)})}getHlsState(){return Y(this,null,function*(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=yield function(e){return Y(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)=>Y(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield oc(e)}}))),Promise.all(a.map((e,t)=>Y(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 oc(e)}})))]);return{levels:o,audios:l,currentLevel:e.videoTrack&&null!=(t=o.find(t=>{var i;return t.id===(null==(i=e.videoTrack)?void 0:i.id)}))?t:null,currentAudio:e.audioTrack&&null!=(i=l.find(t=>{var i;return t.id===(null==(i=e.audioTrack)?void 0:i.id)}))?i:null,videoMode:null!=(r=e.videoMode)?r:"auto",audioMode:null!=(n=e.audioMode)?n:"auto"}})}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}})}play(){return Y(this,null,function*(){return K(this,F).play()})}pause(){K(this,F).pause()}seek(e){return Y(this,null,function*(){return K(this,F).seek(e)})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,K(this,F).invalidate();const e=[];for(const i of[()=>{var e;return null==(e=this.loadSession)?void 0:e.cancel()},()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){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}}F=new WeakMap;const Sc=new WeakMap;function Pc(e){let t=Sc.get(e);return t||(t={closed:!1,frames:new Set},Sc.set(e,t)),t}class Ic{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new ae,this.engine=new wc({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){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=Pc(e);if(i.closed)return 0;const r=requestAnimationFrame(n=>{i.frames.delete(r),i.closed||t(n,{presentationTime:e.engine.currentTime,expectedDisplayTime:n+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:n,receiveTime:n,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){Pc(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=Pc(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}function xc(e={}){return t=>{const i=t,{createElement:r}=i.constructor.utils,n=r("canvas"),s=new Ic({art:i,canvas:n,ctx:n.getContext("2d"),option:e}),a=function(e,t,i,r){let n,s=!1;function a(){var i;s||!(null==(i=e.template)?void 0:i.$player)||e.option.autoSize||Object.assign(t.style,{width:"100%",height:"100%",objectFit:"contain"})}function o(){s||(s=!0,ie([()=>null==n?void 0:n.destroy(),()=>{e.mediabunny===i&&delete e.mediabunny},()=>i.destroy(),()=>{var t;return null==(t=e.off)?void 0:t.call(e,"resize",a)},()=>{var t;return null==(t=e.off)?void 0:t.call(e,"video:loadedmetadata",a)},()=>{var t;return null==(t=e.off)?void 0:t.call(e,"destroy",o)}]))}return{install:function(){e.on("resize",a),e.on("video:loadedmetadata",a),n=se({art:e,shim:i,option:r}),e.on("destroy",o)},destroy:o}}(i,n,s,e);try{i.mediabunny=s,function(e,t){const i=new Map,r=e,n=t;for(const a in e)if("function"===typeof r[a]){const t=r[a];i.set(a,t.bind(e))}const s=new Set([...Object.getOwnPropertyNames(t),...Object.getOwnPropertyNames(Object.getPrototypeOf(t))]);for(const a of s)"constructor"===a||a in e||Object.defineProperty(e,a,{get(){const e=n[a];return"function"===typeof e?e.bind(t):e},set(e){n[a]=e},configurable:!0,enumerable:!0});for(const[a,o]of i)r[a]=(...e)=>o(...e)}(n,s),a.install()}catch(o){try{a.destroy()}catch(l){console.warn("MediaBunny entry setup cleanup:",l)}throw o}return n}}return Object.defineProperty(xc,"default",{value:xc,writable:!0,configurable:!0}),xc}); diff --git a/docs/compiled/artplayer-proxy-mediabunny.mjs b/docs/compiled/artplayer-proxy-mediabunny.mjs index f6e84117c..0d30a4e5f 100644 --- a/docs/compiled/artplayer-proxy-mediabunny.mjs +++ b/docs/compiled/artplayer-proxy-mediabunny.mjs @@ -21,8 +21,38 @@ var __privateWrapper = (obj, member, setter, getter) => ({ } }); var _closed, _closed2, _generation, _contexts, _nodes, _pump, _playTask, _playing, _loading, _onError, _AudioEngine_instances, load_fn, startPump_fn, play_fn, _generation2, _iteration, _loading2, _createSink, _usedSink, _destroyed, _preparing, _poster, _renderer, _onError2, _VideoEngine_instances, current_fn, context_fn, report_fn, release_fn, draw_fn, load_fn2, reset_fn, _playback; -const $audio = ''; -const $quality = ''; +function bridgeCanvas(canvas, shim) { + const methods = /* @__PURE__ */ new Map(); + const native = canvas; + const members = shim; + for (const name in canvas) { + if (typeof native[name] === "function") { + const method = native[name]; + methods.set(name, method.bind(canvas)); + } + } + const names = /* @__PURE__ */ new Set([ + ...Object.getOwnPropertyNames(shim), + ...Object.getOwnPropertyNames(Object.getPrototypeOf(shim)) + ]); + for (const name of names) { + if (name === "constructor" || name in canvas) + continue; + Object.defineProperty(canvas, name, { + get() { + const value = members[name]; + return typeof value === "function" ? value.bind(shim) : value; + }, + set(value) { + members[name] = value; + }, + configurable: true, + enumerable: true + }); + } + for (const [name, method] of methods) + native[name] = (...args) => method(...args); +} function releaseAll(actions) { const failures = []; for (const action of actions) { @@ -35,6 +65,8 @@ function releaseAll(actions) { if (failures.length) throw failures[0]; } +const $audio = ''; +const $quality = ''; function createMenu(art, name, icon) { const owned = { control: false, setting: false }; let model = null; @@ -218,12 +250,49 @@ function setupM3u8Controls({ art, shim, option }) { console.warn("MediaBunny HLS listener cleanup:", error); } } - art.on("video:loadedmetadata", refresh); - art.on("restart", refresh); - art.on("video:loadstart", invalidate); - art.on("video:error", invalidate); - art.on("destroy", destroy); - return { update }; + try { + art.on("video:loadedmetadata", refresh); + art.on("restart", refresh); + art.on("video:loadstart", invalidate); + art.on("video:error", invalidate); + art.on("destroy", destroy); + } catch (error) { + destroy(); + throw error; + } + return { update, destroy }; +} +function entryLifecycle(art, canvas, shim, option) { + let closed = false; + let controls; + function resize() { + if (closed || !art.template?.$player || art.option.autoSize) + return; + Object.assign(canvas.style, { width: "100%", height: "100%", objectFit: "contain" }); + } + function destroy() { + if (closed) + return; + closed = true; + releaseAll([ + () => controls?.destroy(), + () => { + if (art.mediabunny === shim) + delete art.mediabunny; + }, + () => shim.destroy(), + () => art.off?.("resize", resize), + () => art.off?.("video:loadedmetadata", resize), + () => art.off?.("destroy", destroy) + ]); + } + function install() { + art.on("resize", resize); + art.on("video:loadedmetadata", resize); + controls = setupM3u8Controls({ art, shim, option }); + art.on("destroy", destroy); + } + return { install, destroy }; } class EventTarget { constructor() { @@ -26143,68 +26212,28 @@ class VideoShim { } } function artplayerProxyMediabunny(option = {}) { - return (art) => { - const { constructor } = art; - const { createElement } = constructor.utils; + return (player) => { + const art = player; + const { createElement } = art.constructor.utils; const canvas = createElement("canvas"); - const ctx = canvas.getContext("2d"); - const shim = new VideoShim({ - art, - canvas, - ctx, - option - }); - art.mediabunny = shim; - const originalCanvasMethods = {}; - for (const prop in canvas) { - if (typeof canvas[prop] === "function") { - originalCanvasMethods[prop] = canvas[prop].bind(canvas); + const shim = new VideoShim({ art, canvas, ctx: canvas.getContext("2d"), option }); + const lifecycle = entryLifecycle(art, canvas, shim, option); + try { + art.mediabunny = shim; + bridgeCanvas(canvas, shim); + lifecycle.install(); + } catch (error) { + try { + lifecycle.destroy(); + } catch (failure) { + console.warn("MediaBunny entry setup cleanup:", failure); } + throw error; } - const propertyNames = /* @__PURE__ */ new Set([ - ...Object.getOwnPropertyNames(shim), - ...Object.getOwnPropertyNames(Object.getPrototypeOf(shim)) - ]); - for (const prop of propertyNames) { - if (prop === "constructor") - continue; - if (!(prop in canvas)) { - Object.defineProperty(canvas, prop, { - get() { - const value = shim[prop]; - return typeof value === "function" ? value.bind(shim) : value; - }, - set(v) { - shim[prop] = v; - }, - configurable: true, - enumerable: true - }); - } - } - for (const prop in originalCanvasMethods) { - canvas[prop] = (...args) => originalCanvasMethods[prop](...args); - } - function resize() { - const player = art.template?.$player; - if (!player || art.option.autoSize) - return; - Object.assign(canvas.style, { - width: "100%", - height: "100%", - objectFit: "contain" - }); - } - art.on("resize", resize); - art.on("video:loadedmetadata", resize); - setupM3u8Controls({ art, shim, option }); - art.on("destroy", () => { - delete art.mediabunny; - shim.destroy(); - }); return canvas; }; } +Object.defineProperty(artplayerProxyMediabunny, "default", { value: artplayerProxyMediabunny, writable: true, configurable: true }); export { artplayerProxyMediabunny as default }; diff --git a/package.json b/package.json index 0a729be63..a0e55f431 100644 --- a/package.json +++ b/package.json @@ -51,7 +51,7 @@ "ci:build": "yarn build:types && yarn build all && yarn build:i18n && yarn build:ts && yarn build:docs && yarn test:imports", "test:imports": "node --test test/esm.test.js test/i18n.test.js test/ssr.test.js", "typecheck": "node scripts/typecheck.mjs", - "test:unit": "node --test test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js test/dpip.test.js test/dpip-lifecycle.test.js test/canvas.test.js test/canvas-lifecycle.test.js test/ambilight.test.js test/ambilight-lifecycle.test.js test/ambilight-proxy.test.js test/vast.test.js test/vast-lifecycle.test.js test/ads.test.js test/ads-lifecycle.test.js test/playback.test.js test/dash-control.test.js test/dash-contract.test.js test/dash-lifecycle.test.js test/dash-events.test.js test/hls-control.test.js test/audio-track.test.js test/public-behavior.test.js test/helpers.test.js test/chapter.test.js test/utils.test.js test/resource-scope.test.js test/instance-lifecycle.test.js test/options.test.js test/media-hosts.test.js test/plugins.test.js test/source.test.js test/playback-properties.test.js test/media-events.test.js test/template-resources.test.js test/core-vendor.test.js test/component-resources.test.js test/setting-model.test.js test/setting-layout.test.js test/setting-resources.test.js test/subtitle.test.js test/display-native.test.js test/display-video-fullscreen.test.js test/display-pip.test.js test/display-mini.test.js test/display-sizing.test.js test/display-orientation.test.js test/hotkey.test.js test/listener-registry.test.js test/global-events.test.js test/pointer-events.test.js test/gesture.test.js test/event-scheduling.test.js test/notice.test.js test/fast-forward.test.js test/auto-playback.test.js test/builtin-layers.test.js test/prompt-components.test.js test/screenshot.test.js test/thumbnails.test.js test/progress.test.js test/environment.test.js test/storage.test.js test/facade-properties.test.js test/dom-boundaries.test.js test/initialization.test.js test/entry.test.js test/accessibility-button.test.js test/accessibility-focus.test.js test/accessibility-slider.test.js", + "test:unit": "node --test test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-entry.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js test/dpip.test.js test/dpip-lifecycle.test.js test/canvas.test.js test/canvas-lifecycle.test.js test/ambilight.test.js test/ambilight-lifecycle.test.js test/ambilight-proxy.test.js test/vast.test.js test/vast-lifecycle.test.js test/ads.test.js test/ads-lifecycle.test.js test/playback.test.js test/dash-control.test.js test/dash-contract.test.js test/dash-lifecycle.test.js test/dash-events.test.js test/hls-control.test.js test/audio-track.test.js test/public-behavior.test.js test/helpers.test.js test/chapter.test.js test/utils.test.js test/resource-scope.test.js test/instance-lifecycle.test.js test/options.test.js test/media-hosts.test.js test/plugins.test.js test/source.test.js test/playback-properties.test.js test/media-events.test.js test/template-resources.test.js test/core-vendor.test.js test/component-resources.test.js test/setting-model.test.js test/setting-layout.test.js test/setting-resources.test.js test/subtitle.test.js test/display-native.test.js test/display-video-fullscreen.test.js test/display-pip.test.js test/display-mini.test.js test/display-sizing.test.js test/display-orientation.test.js test/hotkey.test.js test/listener-registry.test.js test/global-events.test.js test/pointer-events.test.js test/gesture.test.js test/event-scheduling.test.js test/notice.test.js test/fast-forward.test.js test/auto-playback.test.js test/builtin-layers.test.js test/prompt-components.test.js test/screenshot.test.js test/thumbnails.test.js test/progress.test.js test/environment.test.js test/storage.test.js test/facade-properties.test.js test/dom-boundaries.test.js test/initialization.test.js test/entry.test.js test/accessibility-button.test.js test/accessibility-focus.test.js test/accessibility-slider.test.js", "test:coverage": "node --test test/coverage.test.js && node scripts/coverage.mjs", "test": "yarn test:node && yarn test:baseline", "test:browser": "playwright test", @@ -76,7 +76,8 @@ "test:canvas-types-package": "node refactor/scripts/canvas-package-types.mjs", "test:dpip": "node --test test/dpip.test.js test/dpip-lifecycle.test.js", "test:dpip-types-package": "node refactor/scripts/dpip-package-types.mjs", - "test:mediabunny": "node --test test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js" + "test:mediabunny": "node --test test/mediabunny.test.js test/mediabunny-shim.test.js test/mediabunny-coordination.test.js test/mediabunny-video.test.js test/mediabunny-audio.test.js test/mediabunny-hls.test.js test/mediabunny-entry.test.js test/mediabunny-load.test.js test/mediabunny-input.test.js", + "test:mediabunny-types-package": "node refactor/scripts/mb-package-types.mjs" }, "browserslist": "last 1 Chrome version", "devDependencies": { diff --git a/packages/artplayer-proxy-mediabunny/.npmignore b/packages/artplayer-proxy-mediabunny/.npmignore index 4439c6874..2b272d565 100644 --- a/packages/artplayer-proxy-mediabunny/.npmignore +++ b/packages/artplayer-proxy-mediabunny/.npmignore @@ -2,4 +2,5 @@ node_modules .DS_Store yarn.lock package-lock.json -src \ No newline at end of file +src +tsconfig.json diff --git a/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md b/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md index ca911b119..5449e081b 100644 --- a/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md +++ b/packages/artplayer-proxy-mediabunny/ARCHITECTURE.md @@ -1,14 +1,19 @@ # MediaBunny proxy maintenance -The public entry is `src/index.js`: an optional-options factory returns the existing +The public entry is `src/index.ts`: an optional-options factory returns the existing ArtPlayer proxy callback and an HTMLCanvasElement. Public declarations remain in -`types/artplayer-proxy-mediabunny.d.ts`. The input migration does not change those -declarations, the factory signature, canvas forwarding, or package entrypoints. +`types/artplayer-proxy-mediabunny.d.ts`, with a separate ESM declaration entry. +The exact optional factory and HTMLCanvasElement result remain unchanged. The media +view in `types/media.d.ts` is opt-in and checked against the real VideoShim class. ## Current module map | Module | Responsibility | | --- | --- | +| `index.ts` | Optional factory, Canvas construction, alias installation and setup rollback | +| `canvas-bridge.ts` | Historical own/direct-prototype forwarding and native Canvas receiver binding | +| `entry-lifecycle.ts` | Entry resize/metadata/destroy subscriptions, alias ownership and shim cleanup | +| `cleanup.ts` | Attempt every release and preserve the first failure | | `input.ts` | String/Blob/ReadableStream normalization, SDK Source/SourceRef pass-through, HLS detection and Input construction | | `media.ts` | Internal SDK-backed media and track-mode types; not public consumer types | | `tracks.ts` | Primary video and pairable audio selection, metadata/computed/live duration | @@ -38,11 +43,20 @@ declarations, the factory signature, canvas forwarding, or package entrypoints. | `m3u8-menu.ts` | Owned control/setting surfaces and stale callback guards | | `m3u8-types.ts` | Narrow internal UI/shim contracts without changing public factory declarations | -The thirty production TypeScript modules use strict checking with `skipLibCheck: false` +The thirty-four production TypeScript modules use strict checking with `skipLibCheck: false` and no ambient Node types. The coordinator and both decoder engines are checked implementations; there are no remaining adjacent JavaScript declaration bridges. -Only the public factory remains JavaScript, scheduled in PKG-MB-08. -Do not describe the whole package as migrated yet. +All owned production JavaScript has been migrated. This source milestone does not complete +PKG-MB-08: unsupported decoder fallback/readiness still needs its remaining review. + +The entry preserves native Canvas method priority, detached createElement invocation, +two reads of enumerable native method accessors, direct-prototype forwarding, bound shim +methods and strict assignment errors for getter-only properties. Avoid replacing these +with generic Reflect forwarding or a broad HTMLVideoElement cast. Entry bookkeeping stays +off the canvas surface. Destroy unregisters its callbacks and only removes art.mediabunny +when the alias still belongs to that entry. A custom historical host without off keeps inert +callbacks; a real Artplayer host removes them. Partial setup attempts all cleanup while +preserving the original setup error. HLS cleanup cannot strand the remaining entry resources. The shim keeps its existing own-property order and direct prototype surface because the entry copies those descriptors onto the canvas. Resource bookkeeping lives in a @@ -228,13 +242,39 @@ resolution selects `@types/dom-webcodecs@0.1.19` for both dependency paths; the itself is unchanged. This is a build-time declaration correction, not a browser polyfill. The package typecheck adds ESNext.Disposable for SDK declarations while keeping the ES2020 target; production source does not use `using` or require Symbol.dispose. -Public consumer declarations do not import these SDK types; preserve that boundary -until the separate consumer-compatibility task verifies any proposed change. +Public declarations do not import SDK types or modern DOM VideoFrame callback names. +The optional media view names the synthetic frame metadata directly; SDK track objects +are unknown until consumers narrow them using their own SDK version. `VideoShim implements +MediaBunnyShim` checks that this view matches implementation rather than masking JS with +an adjacent declaration. Explicit getter return types retain coercive unknown setters +internally while giving consumers numeric/boolean reads. + +Default Result remains exactly HTMLCanvasElement, allowing callers to substitute a plain +canvas initializer or an entire historical factory. MediaBunnyCanvas combines the opt-in +media view with native Canvas methods winning collisions. MediaBunnyPlayer has an optional +mediabunny alias because it is absent before initialization and after destruction; there +is no global augmentation of Artplayer. Named exports are types only. + +The .d.mts wrapper fixes NodeNext ESM default resolution. CommonJS keeps the historical +default declaration facade, and typesVersions resolves /legacy in TS 4.3/classic Node +resolution. Runtime remains directly callable and adds a nonenumerable, writable default +self alias for the 1.0.0 CommonJS usage. That property is deliberately not mandatory on +the default factory type. Whole-factory assignments are tested bidirectionally against +both frozen published declarations, in an actual isolated install as well as workspace +consumers. Do not switch to export= or a required default member without those checks. + +`canPlayType()` still always returns maybe; buffered/played/seekable and RAF metadata remain +synthetic. None is proof that a codec or browser can play the input. Missing Web Audio or +WebCodecs in Windows WebKit remains an unsupported-capability control. Existing but +undecodable tracks can still take historical clock-only fallback; remaining MB-08 work +must distinguish valid audio-only/video-only playback from false readiness with no usable +decoder, including selection replacement. Native/long-play/device acceptance remains MB-09. ## Validation and remaining work ```sh yarn test:mediabunny +yarn test:mediabunny-types-package node node_modules/typescript/bin/tsc -p packages/artplayer-proxy-mediabunny/tsconfig.json yarn build artplayer-proxy-mediabunny yarn test:browser test/browser/mediabunny-inputs.spec.js test/browser/mediabunny.spec.js test/browser/mediabunny-load.spec.js @@ -242,6 +282,7 @@ yarn test:browser test/browser/mediabunny-shim.spec.js yarn test:browser test/browser/mediabunny-video.spec.js yarn test:browser test/browser/mediabunny-audio.spec.js yarn test:browser test/browser/mediabunny-hls.spec.js +yarn test:browser test/browser/mediabunny-entry.spec.js ``` Node tests use actual SDK parsing and controlled lifecycle interleavings. Browser tests diff --git a/packages/artplayer-proxy-mediabunny/README.md b/packages/artplayer-proxy-mediabunny/README.md index 82fafd7f0..ca2ab9f5c 100644 --- a/packages/artplayer-proxy-mediabunny/README.md +++ b/packages/artplayer-proxy-mediabunny/README.md @@ -10,6 +10,46 @@ mediabunny proxy for ArtPlayer, including `m3u8` playback through Mediabunny's H MIT © Harvey Zhao +## TypeScript + +The default factory still accepts optional options and returns an initializer whose +result is exactly `HTMLCanvasElement`. Existing factory replacements remain assignable. +Use the optional media view when accessing the proxy's media methods: + +```ts +import type { MediaBunnyPlayer } from 'artplayer-proxy-mediabunny' +import Artplayer from 'artplayer' +import mediabunny from 'artplayer-proxy-mediabunny' + +const art: MediaBunnyPlayer = new Artplayer({ + container: '#player', + url: 'movie.mp4', + proxy: mediabunny({ volume: 0.7 }), +}) + +art.on('ready', async () => { + const shim = art.mediabunny + if (!shim) + return + const state = await shim.getM3u8State() + console.log(state?.currentLevel?.height) +}) +``` + +`MediaBunnyShim`, `MediaBunnyCanvas`, HLS track/state and synthetic frame callback types +are also available as type-only exports. The player alias is optional and removed on +destruction. Native Canvas event/attribute methods take precedence over shim methods. +SDK track objects need explicit narrowing with your application's SDK types. + +The `canPlayType()` response remains `maybe` for compatibility; it does not test codec +support. TimeRanges and frame callback metadata are synthetic. Actual playback requires +supported codecs and browser media APIs; a `legacy` bundle does not polyfill those APIs. +Decoder fallback and broader browser/device validation remain in progress. + +ESM default imports and `/legacy` type resolution now support the tested TS 5.9 and +TS 4.3 modes. CommonJS supports both direct calls and the old `require(...).default` +runtime path. The default factory type keeps its historical callable signature. + ## Maintenance See [ARCHITECTURE.md](ARCHITECTURE.md) for current modules, resource ownership, compatibility boundaries and validation commands. diff --git a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js index dceb215e3..099dbcd87 100644 --- a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js +++ b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js @@ -4,4 +4,4 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,a,s,n,o,c,l,u,h,d,f,m,p,g,k,y,b,w,T,S,v,P,I,x,C,B,E,_,R,F,A=e=>{throw TypeError(e)},M=(e,t,i)=>t.has(e)||A("Cannot "+i),D=(e,t,i)=>(M(e,t,"read from private field"),i?i.call(e):t.get(e)),N=(e,t,i)=>t.has(e)?A("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),O=(e,t,i,r)=>(M(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),L=(e,t,i)=>(M(e,t,"access private method"),i),z=(e,t,i,r)=>({set _(r){O(e,t,r,i)},get _(){return D(e,t,r)}});function U(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function q(e,t,i){const r={control:!1,setting:!1};let a=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function n(){a=null,U([()=>s("control"),()=>s("setting")])}return{update:function(o,c,l,u){if(!o)return void n();a=o;const h=()=>a===o&&l(),d=async e=>h()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html;c.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:d})):s("control"),h()&&(c.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:d})):s("setting"))},clear:n}}function W(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function H({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,a=0,s=0;const n=q(e,"mediabunny-quality",''),o=q(e,"mediabunny-audio",''),c=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;async function l(){if(r||t.engine.destroyed)return;const e=++a,s=t.engine.loadSeq,l=()=>e===a&&c(s);try{const e=await t.getM3u8State();if(!l())return;const r=i.m3u8?.quality||{},a=function(e,t,i){if(!t.control&&!t.setting||!e?.levels.length)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||`${e.height}P`),s=e.currentLevel?a(e.currentLevel):r,n=[];for(const l of e.levels){if(!i())return null;n.push({html:a(l),value:l.id,default:e.currentLevel?.id===l.id})}const o=new Map(e.levels.map(e=>[e.id,e.height])),c=W(n).sort((e,t)=>("auto"===t.value?0:o.get(t.value)||0)-("auto"===e.value?0:o.get(e.value)||0));return c.push({html:r,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:s,selector:c}}(e,r,l);if(!l())return;if(n.update(a,r,()=>c(s),(e,t)=>u("quality",e,t)),!l())return;const h=i.m3u8?.audio||{},d=function(e,t,i){if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||e.lang||e.language),s=e.currentAudio?a(e.currentAudio):r,n=[];for(const c of e.audios){if(!i())return null;n.push({html:a(c),value:c.id,default:e.currentAudio?.id===c.id})}const o=W(n);return o.push({html:r,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:s,selector:o}}(e,h,l);l()&&o.update(d,h,()=>c(s),(e,t)=>u("audio",e,t))}catch(h){if(l())throw h}}async function u(i,r,n){const o=++s,u=t.engine.loadSeq;a++;const d=()=>o===s&&c(u);try{"quality"===i?await t.switchM3u8Quality(r.value):await t.switchM3u8Audio(r.value),d()&&(await l(),d()&&(e.notice.show=`${n}: ${r.html}`))}catch(f){if(d()&&(await h(),d()))throw f}return r.html}function h(){return l().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function d(){a++,s++;try{U([n.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}return e.on("video:loadedmetadata",h),e.on("restart",h),e.on("video:loadstart",d),e.on("video:error",d),e.on("destroy",function t(){if(!r){r=!0,d();try{U([()=>e.off("video:loadedmetadata",h),()=>e.off("restart",h),()=>e.off("video:loadstart",d),()=>e.off("video:error",d),()=>e.off("destroy",t)])}catch(i){console.warn("MediaBunny HLS listener cleanup:",i)}}}),{update:l}}class V{constructor(){N(this,e,!1),this.listeners=new Map}addEventListener(t,i){D(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t)?.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){if(D(this,e))return;const r=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{D(this,e)||t(r)})}destroy(){O(this,e,!0),this.listeners.clear()}}function j(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const K=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},X=e=>e&&e[e.length-1],$=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-2**r)},Q=e=>{const t=$(e);return 0===(1&t)?-(t>>1):t+1>>1},Y=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),J=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Z=new TextDecoder,ee=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),te={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ie=ee(te),re={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ae=ee(re),se={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ne=ee(se),oe=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,ce={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},le=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class ue{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const he=/^[0-9a-fA-F]+$/,de=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),fe=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,me=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},ge=(e,t,i)=>{const r=pe(e,i(t),i);e.splice(r+1,0,t)},ke=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},ye=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},be=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},we=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Te=e=>{throw new Error(`Unexpected value: ${e}`)},Se=(e,t,i)=>{const r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},ve=(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)},Pe=(e,t)=>({async next(){const i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),Ie=(e,t,i)=>Math.max(t,Math.min(i,e)),xe="und",Ce=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Be=(e,t)=>Math.round(e/t)*t,Ee=(e,t)=>Math.round(e*t)/t,_e=(e,t)=>Math.floor(e/t)*t,Re=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},Fe=/^[a-z]{3}$/,Ae=e=>Fe.test(e),Me=1e6*(1+Number.EPSILON),De=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?Ne(e.headers):{},a=t.headers?Ne(t.headers):{},s={...r};Object.entries(a).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},Ne=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},Oe=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(n){if(a())throw n;s++;const e=r(s,n,t);if(null===e)throw n;if(ct._error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await at(1e3*e),a())throw n}};class Le{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ze=null;const Ue=()=>null!==ze?ze:ze=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let qe=null;const We=()=>null!==qe?qe:qe="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let He=null;const Ve=()=>null!==He?He:He=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),je=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,Ke=(async()=>{})().constructor,Xe=e=>e instanceof Ke||e instanceof Promise||"function"===typeof e?.then,$e=(e,t)=>-1!==e?e:t,Ge=(e,t,i,r)=>e<=r&&i<=t,Qe=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Je=e=>"number"===typeof e&&!Number.isNaN(e),Ze=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const a=e.indexOf("/",r+3);i=-1===a?e+t:e.slice(0,a)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const a=i.indexOf("://");if(-1!==a){const e=i.indexOf("/",a+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),n=[];for(const o of s)".."===o?n.pop():"."!==o&&n.push(o);return r+n.join("/")},et=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{j(Number.isInteger(e.num)),j(Number.isInteger(e.den)),j(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}},rt=(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.`)},at=e=>new Promise(t=>setTimeout(t,e));class st{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const r={fn:t,once:i?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(a){console.error(a)}s.once&&r.delete(s)}}}var nt,ot;(ot=nt||(nt={}))[ot.Silent=0]="Silent",ot[ot.Errors=1]="Errors",ot[ot.Warnings=2]="Warnings",ot[ot.Info=3]="Info";class ct{constructor(){}static get level(){return ct._level}static set level(e){if(e!==nt.Silent&&e!==nt.Errors&&e!==nt.Warnings&&e!==nt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ct._level=e}static get _emitter(){return ct._emitterInstance??(ct._emitterInstance=new st)}static on(e,t,i){return ct._emitter.on(e,t,i)}static _error(...e){ct._emitter._emit("error",e),ct._level>=nt.Errors&&console.error(...e)}static _warn(...e){ct._emitter._emit("warn",e),ct._level>=nt.Warnings&&console.warn(...e)}static _info(...e){ct._emitter._emit("info",e),ct._level>=nt.Info&&console.info(...e)}}ct._level=nt.Info,ct._emitterInstance=null;class lt{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 ut{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 ht={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class dt{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(7&this.pos),r=(t&1<>i;return this.pos++,r}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new dt(this.bytes);return e.pos=this.pos,e}}const ft=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],mt=[-1,1,2,3,4,5,6,8],pt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new dt(e),i=gt(t),{frequencyIndex:r,sampleRate:a}=kt(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=mt[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=kt(t).sampleRate,o=gt(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===gt(t)&&t.readBits(1)&&(l=kt(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(c=!!t.readBits(1)));break}t.pos=e+1}return null!==n&&n>1&&(c=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:c&&1===n?2:n}},gt=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},kt=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let a=0;t+3i&&(yield{offset:i,length:t-i}),i=t+a,t=i):t++}-1!==i&&i{if(t.description){const i=3&Y(t.description)[4];return It(e,i+1)}return Pt(e)},Ct=e=>31&e,Bt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Et.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Et,r),r+=Et.byteLength,i.set(a,r),r+=a.byteLength;return i},Rt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let a=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(a,s.byteLength);break;case 2:e.setUint16(a,s.byteLength,!1);break;case 3:ve(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Ft=e=>{try{const t=[],i=[],r=[];for(const o of Pt(e)){const a=e.subarray(o.offset,o.offset+o.length),s=Ct(a[0]);s===wt.SPS?t.push(a):s===wt.PPS?i.push(a):s===wt.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=Nt(a);j(null!==s);const n=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:n?s.chromaFormatIdc:null,bitDepthLumaMinus8:n?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:n?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:n?r:null}}catch(t){return ct._error("Error building AVC Decoder Configuration Record:",t),null}},At=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint8(i++),n=t.getUint8(i++),o=3&t.getUint8(i++),c=31&t.getUint8(i++),l=[];for(let f=0;f{try{const t=Bt(e),i=new dt(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();$(i);let n=1,o=0,c=0,l=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=$(i),3===n&&(l=i.readBits(1)),o=$(i),c=$(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==n?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,a=8;for(let e=0;ee.level>=s)??X(Ai),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);v=r,P=r}else v=0,P=0}return j(null!==P),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:S,colourPrimaries:y,matrixCoefficients:w,transferCharacteristics:b,fullRangeFlag:T,numReorderFrames:v,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:C,bitstreamRestrictionFlagBitOffset:I,bitstreamRestrictionFlag:x}}catch(t){return ct._error("Error parsing AVC SPS:",t),null}},Ot=e=>{const t=$(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)$(e),$(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Lt=e=>{j(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new dt(e.emulationUnpreventedBytes),r=new dt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(j(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),G(r,2),G(r,1),G(r,16),G(r,16),G(r,e.numReorderFrames),G(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return j(Number.isInteger(a)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,a))},zt=(e,t)=>{if(t.description){const i=3&Y(t.description)[21];return It(e,i+1)}return Pt(e)},Ut=e=>e>>1&63,qt=e=>{try{const t=new dt(Bt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Ht(t,i);$(t);const u=$(t);let h=0;3===u&&(h=t.readBits(1));const d=$(t),f=$(t);let m=d,p=f;if(t.readBits(1)){const e=$(t),i=$(t),r=$(t),a=$(t);let s=1,n=1;const o=0===h?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),m-=(e+i)*s,p-=(r+a)*n}const g=$(t),k=$(t);$(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)$(t),b=$(t),$(t);$(t),$(t),$(t),$(t),$(t),$(t),t.readBits(1)&&t.readBits(1)&&Vt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),$(t),$(t),t.skipBits(1));const w=$(t);if(jt(t,w),t.readBits(1)){const e=$(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of Pt(e)){const s=e.subarray(c.offset,c.offset+c.length),n=Ut(s[0]);n===St.VPS_NUT?t.push(s):n===St.SPS_NUT?i.push(s):n===St.PPS_NUT?r.push(s):n!==St.PREFIX_SEI_NUT&&n!==St.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=qt(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new dt(Bt(e));t.skipBits(16),$(t),$(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),$(t),$(t),Q(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&$(t),Q(t),Q(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType: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}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ut(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:n,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return ct._error("Error building HEVC Decoder Configuration Record:",t),null}},Ht=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let u=0;u<6;u++)n[u]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let u=0;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&Q(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){if(t===i){n=t-($(e)+1)}else n=t-1;e.readBits(1),$(e);const s=r[n]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=r[n]}else{const t=$(e),i=$(e);for(let r=0;r{let i=2,r=2,a=2,s=0,n=0,o={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{const e=Dt[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&($(e),$(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&($(e),$(e),$(e),$(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&$(e),e.readBits(1)&&$t(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=$(e),$(e),$(e),$(e),$(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},$t=(e,t,i)=>{let r=!1,a=!1,s=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?$(e):i=1===e.readBits(1);let n=1;if(!i){n=$(e)+1}r&&Gt(e,n,s),a&&Gt(e,n,s)}},Gt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=Qt.audAllowed;for(const s of zt(e,t)){if(r===Qt.noMoreDataAllowed){i.add(s.offset);continue}const t=Ut(e[s.offset]);if(r===Qt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>Qt.audAllowed?a=!0:r=Qt.beforeFirstVcl:t<=31?r>Qt.afterFirstVcl?a=!0:r=Qt.afterFirstVcl:36===t?r!==Qt.afterFirstVcl?a=!0:r=Qt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>Qt.beforeFirstVcl?a=!0:r=Qt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&Y(t.description)[21];return Rt(e,i+1)}return _t(e)})(a,t)},Zt={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},ei=e=>{const t=new dt(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(r>=2){a=t.readBits(1)?12:10}const s=t.readBits(3);let n=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);n=e||i?e&&!i?2:1:3,t.skipBits(1)}else n=1}else n=3,o=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let l=X(Mi).level;for(const h of Mi)if(c<=h.maxPictureSize){l=h.level;break}const u=Zt[s];return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:u?.colourPrimaries??2,transferCharacteristics:u?.transferCharacteristics??2,matrixCoefficients:u?.matrixCoefficients??2}},ti=function*(e){const t=new dt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*2**(7*i),!(128&r))break;if(7===i&&128&r)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),a=t.readBits(1),s=t.readBits(1);let n;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;n=e}else n=Math.floor(t.getBitsLeft()/8);j(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},ii=e=>{for(const{type:t,data:i}of ti(e)){if(1!==t)continue;const e=new dt(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const h=l+1;e.skipBits(h);let d=0;if(d=a?0:e.readBits(1),d&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},ri=e=>{if(e.length<36)return null;const t=J(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},ai=[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],si=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;u97;)if(1===r.readBits(1)){a=r.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;r.getBitsLeft()>=97;){const e=r.pos,t=r.readBits(8),i=r.readBits(16),a=r.readBits(16);if(t>63||0!==i||0!==a){r.pos=e;break}if(r.skipBits(1),s++,s>64)break;r.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;r.pos=0,r.skipBits(a);const l=Array(c).fill(0);for(let u=c-1;u>=0;u--)r.skipBits(40),l[u]=r.readBits(1);return{modeBlockflags:l}},ni=(e,t,i)=>{switch(e){case"avc":for(const e of xt(i,t)){const t=i[e.offset],r=Ct(t);if(r>=wt.NON_IDR_SLICE&&r<=wt.SLICE_DPC)return"delta";if(r===wt.IDR)return"key";if(r===wt.SEI&&!Ve()){const t=i.subarray(e.offset,e.offset+e.length),r=Bt(t);let a=1;do{let e=0;for(;;){const t=r[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new dt(r);e.pos=8*a;const t=$(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=J(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=Z.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(i=t.raw).vendor??(i.vendor=o));const c=a.getUint32(s,!0);s+=4;for(let l=0;l0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=l.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.discNumber??(t.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??(t.discsTotal=r))}break;case"DISCTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(l);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=l);break;case"METADATA_BLOCK_PICTURE":{const e=Qe(l),i=J(e),r=i.getUint32(0,!1),a=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=i.getUint32(8+a,!1),o=Z.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),u=e.subarray(a+n+32,a+n+32+c);t.images??(t.images=[]),t.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},ui=[2,1,2,3,3,4,4,5],hi=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),a=t.readBits(5);if(a>8)return null;const s=t.readBits(3),n=t.readBits(3);0!==(1&n)&&1!==n&&t.skipBits(2),0!==(4&n)&&t.skipBits(2),2===n&&t.skipBits(2);return{fscod:i,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},di=[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],fi=[1,2,3,6],mi=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),a=t.readBits(2);let s,n=0;3===a?(n=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;const u=fi[s];let h;h=a<3?yt[a]/1e3:bt[n]/1e3;return{dataRate:Math.round((r+1)*h/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},pi=e=>{const t=e.substreams[0];return j(t),t.fscod<3?yt[t.fscod]:null!==t.fscod2&&t.fscod2<3?bt[t.fscod2]:null},gi=e=>{const t=e.substreams[0];j(t);let i=ui[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},ki=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],yi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],bi=[16,16,20,20,0,24,24,0],wi=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ti=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Si=[32e3,44100,48e3,0],vi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Pi=[512,1024,2048,4096],Ii=e=>{const t=Ci(e),i=J(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Bi(e.subarray(r));if(!t)break;a??(a=t),r+=t.frameSize}if(t)return{frameSize:a?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==a};if(!a?.asset)return null;const{asset:s}=a;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},xi=e=>{const t=Ii(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Ci=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new dt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const a=t.readBits(14)+1;if(a<96)return null;const s=t.readBits(6);if(s>=wi.length)return null;const n=ki[t.readBits(4)];if(0===n)return null;const o=yi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const c=t.readBits(2);if(3===c)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const l=bi[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:wi[s]+(u?1:0),sampleCount:32*r,channelLayout:Ti[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Bi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new dt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),a=8+4*r,s=16+4*r;t.skipBits(a);const n=t.readBits(s)+1,o={frameSize:n,asset:null};if(!t.readBits(1))return o;const c=Si[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,h=t.readBits(3)+1,d=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===c||t.getBitsLeft()<0?o:{frameSize:n,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:f}}},Ei=e=>Re(e)+Re(44646&e),_i=["avc","hevc","vp9","av1","vp8","prores"],Ri=["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"],Fi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Ri],Ai=[{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}],Mi=[{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}],Di=".01.01.01.01.00",Ni=".0.110.01.01.01.0",Oi=["ap4x","ap4h","apch","apcn","apcs","apco"],Li=["dtsc","dtsh","dtsl","dtse"],zi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o,proresFormat:c}=e;if("avc"===t){if(j(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${de(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}.${de(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=fe(s.generalProfileCompatibilityFlags),a=s.generalTierFlag,n=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=J(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=fe(s.getUint32(2)),a=c>>5&1,n=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=r.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=n;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!n){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${n.profile.toString().padStart(2,"0")}.${n.level.toString().padStart(2,"0")}.${n.bitDepth.toString().padStart(2,"0")}.${n.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${n.colourPrimaries.toString().padStart(2,"0")}.${n.transferCharacteristics.toString().padStart(2,"0")}.${n.matrixCoefficients.toString().padStart(2,"0")}.${n.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Di)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),a=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),n=o.monochrome?"1":"0",c=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),l=r?.primaries?te[r.primaries]:1,u=r?.transfer?re[r.transfer]:1,h=r?.matrix?se[r.matrix]:1,d=r?.fullRange?1:0;let f=`av01.${t}.${i}${a}.${s}`;return f+=`.${n}.${c.toString().padStart(3,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${d}`,f.endsWith(Ni)&&(f=f.slice(0,-17)),f}if("prores"===t)return c??"apch";throw null!==t&&Te(t),new TypeError(`Unhandled codec '${t}'.`)},Ui=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Mt(e.codecDescription)?.sequenceParameterSets[0]),t){const e=Nt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===St.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),h=(15&t.getUint8(i++))<<8|t.getUint8(i++),d=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,w=k>>2&1,T=3&k,S=t.getUint8(i++),v=[];for(let P=0;P>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===St.SPS_NUT)?.nalUnits[0]),t){const e=qt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ie[e.vp9CodecInfo.colourPrimaries],transfer:ae[e.vp9CodecInfo.transferCharacteristics],matrix:ne[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ie[e.av1CodecInfo.colourPrimaries],transfer:ae[e.av1CodecInfo.transferCharacteristics],matrix:ne[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ie[e.proresCodecInfo.colourPrimaries],transfer:ae[e.proresCodecInfo.transferCharacteristics],matrix:ne[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},qi=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=pt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return a??"dtsc";if(t&&Ri.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Wi=48e3,Hi=/^pcm-([usf])(\d+)(be)?$/,Vi=e=>{if(j(Ri.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=Hi.exec(e);let i;j(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},ji=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":Oi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":Li.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Hi.test(e)?e:"webvtt"===e?"webvtt":null,Ki=[44100,48e3,32e3],Xi=[-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],$i=1483304551,Gi=1231971951,Qi=(e,t)=>3===e?3===t?21:36:3===t?13:21,Yi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,h=s>>6&3,d=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Xi[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=Ki[u]>>n+o,b=((e,t,i,r,a)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Zi,er;(er=Zi||(Zi={}))[er.FrameCount=1]="FrameCount",er[er.FileSize=2]="FileSize",er[er.Toc=4]="Toc";const tr=e=>3===e?1:2;class ir{constructor(e){this.input=e}dispose(){}}const rr=new Uint8Array(0);class ar{constructor(e,t,i,r,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=a,e===rr&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!==typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===rr}get microsecondTimestamp(){return Math.trunc(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new ar(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new ar(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const sr=e=>{const t=J(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=de(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=uc(e);const i=bc(e,4);let r=8;1===t&&(t=mc(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},cr=e=>dc(e)/65536,lr=e=>dc(e)/1073741824,ur=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=ac(e);if(t|=127&i,0===(128&i))break}return t},hr=e=>{let t=nc(e);return e.skip(2),t=Math.min(t,e.remainingLength),Z.decode(rc(e,t))},dr=e=>{const t=or(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=uc(e);e.skip(4);const r=rc(e,t.contentSize-8);switch(i){case 1:return Z.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new lt(r,"image/jpeg");case 14:return new lt(r,"image/png");case 27:return new lt(r,"image/bmp");default:return r}},fr=16,mr=new Uint32Array(256),pr=new Uint32Array(256),gr=new Uint32Array(256),kr=new Uint32Array(256),yr=new Uint32Array(256),br=new Uint32Array(256),wr=new Uint32Array(10);let Tr=!1;class Sr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(fr/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(fr),this.out=new Uint8Array(fr),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){j(16===e.byteLength),j(16===t.byteLength),Tr||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,n=1;s<256;s++)i[s]=n,t[n]=s,n=n^n<<1^(128&n?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let a=r^r<<1^r<<2^r<<3^r<<4;a=a>>>8^255&a^99,e[s]=a}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);mr[s]=t<<24|t<<16|t<<8|t,br[s]=i<<24|i<<16|i<<8|i;const a=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);pr[s]=a,gr[s]=a>>>8|a<<24,kr[s]=a>>>16|a<<16,yr[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)wr[s]=a<<24,a=a<<1^(128&a?283:0);Tr=!0})();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let a=4;a<44;a+=4){const e=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^4278190080&mr[e>>>16&255]^16711680&mr[e>>>8&255]^65280&mr[e>>>0&255]^255&mr[e>>>24&255]^wr[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a>>24&255]]^gr[255&mr[t>>>16&255]]^kr[255&mr[t>>>8&255]]^yr[255&mr[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,h;for(let g=1;g<10;g++){const a=4*g;c=pr[e>>>24]^gr[r>>>16&255]^kr[i>>>8&255]^yr[255&t]^this.roundkey[a],l=pr[t>>>24]^gr[e>>>16&255]^kr[r>>>8&255]^yr[255&i]^this.roundkey[a+1],u=pr[i>>>24]^gr[t>>>16&255]^kr[e>>>8&255]^yr[255&r]^this.roundkey[a+2],h=pr[r>>>24]^gr[i>>>16&255]^kr[t>>>8&255]^yr[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=h}const d=4278190080&br[e>>>24&255]^16711680&br[r>>>16&255]^65280&br[i>>>8&255]^255&br[t>>>0&255]^this.roundkey[40],f=4278190080&br[t>>>24&255]^16711680&br[e>>>16&255]^65280&br[r>>>8&255]^255&br[i>>>0&255]^this.roundkey[41],m=4278190080&br[i>>>24&255]^16711680&br[t>>>16&255]^65280&br[e>>>8&255]^255&br[r>>>0&255]^this.roundkey[42],p=4278190080&br[r>>>24&255]^16711680&br[i>>>16&255]^65280&br[t>>>8&255]^255&br[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,d^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class vr extends ir{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Xe(r)&&(r=await r),!r)break;const a=e,s=or(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=bc(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Xe(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>a+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=a+s.totalSize}if(!i&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){j(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Xe(e)&&(e=await e),j(e);const t=uc(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Xe(e)&&(e=await e),e){const t=or(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Xe(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==vr)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const i of t.tracks){const e={id:i.id,demuxer:this,trackBacking:null,disposition:i.disposition,timescale:i.timescale,durationInMediaTimescale:i.durationInMediaTimescale,durationInMovieTimescale:i.durationInMovieTimescale,rotation:i.rotation,internalCodecId:i.internalCodecId,name:i.name,languageCode:i.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:i.editListPreviousSegmentDurations,editListOffset:i.editListOffset,encryptionInfo:i.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:i.info};if(i.trackBacking)if(j(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ir(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new xr(t),this.tracks.push(e)}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,null===e.sampleTableByteOffset)return t;j(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(i),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Ri.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){j("audio"===e.info?.type);const i=Vi(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),u=t.sampleTimingEntries[l],h=pe(t.sampleTimingEntries,c,e=>e.startIndex),d=t.sampleTimingEntries[h],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta-f,p=X(r);p&&p.delta===m?p.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:f,count:1,delta:m});const g=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(g)}n.startSampleIndex=n.startChunkIndex,n.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let i=0;ie.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===a.moofOffset);if(i)Rr(s,i.timestamp);else{const e=pe(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Rr(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=pe(t,s.startTimestamp,e=>e.startTimestamp);if(-1!==i&&t[i].moofOffset===a.moofOffset||t.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:s.startTimestamp,endTimestamp:s.endTimestamp}),s.encryptionAuxInfo&&e.encryptionInfo){const t=await Dr(this.reader,e.encryptionInfo,s.encryptionAuxInfo);for(let e=0;e0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ae(t.languageCode)||(t.languageCode=xe)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=bc(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...ce},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=M,this.readContiguousBoxes(e.slice(N,D.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=ac(e);e.skip(3);const r=uc(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*uc(e),e.skip(8)):2===n&&(e.skip(4),l=yc(e),o=uc(e),e.skip(4),c=uc(e),u=uc(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const h="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===h);else if("opus"===h)t.info.codec="opus",t.info.sampleRate=Wi;else if("flac"===h)t.info.codec="flac";else if("ulaw"===h)t.info.codec="ulaw";else if("alaw"===h)t.info.codec="alaw";else if("ac-3"===h)t.info.codec="ac3";else if("ec-3"===h)t.info.codec="eac3";else if(Li.includes(h))t.info.codec="dts",t.info.dtsFormat=h;else if("twos"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ct._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(ct._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===h)t.info.codec="pcm-u8";else if("in24"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===h){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":(ct._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":(ct._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===h){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===h&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==ac(e),t.encryptionInfo.defaultPerSampleIvSize=ac(e),t.encryptionInfo.defaultKid=de(rc(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=ac(e),r=new Uint8Array(16);r.set(rc(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(4);const i=ac(e),r=ac(e),a=ac(e),s=a>>4,n=a>>1&7,o=1&a,c=ac(e),l=ac(e),u=ac(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case"av1C":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(1);const i=ac(e),r=i>>5,a=31&i,s=ac(e),n=s>>7,o=s>>6&1,c=s>>4&1,l=s>>3&1,u=s>>2&1,h=3&s,d=2===r&&o?s>>5&1?12:10:o?10:8;e.skip(1);const f=rc(e,D.contentSize-4),m=ii(f);t.info.av1CodecInfo={profile:r,level:a,tier:n,bitDepth:d,monochrome:c,chromaSubsamplingX:l,chromaSubsamplingY:u,chromaSamplePosition:h,videoFullRangeFlag:m?.videoFullRangeFlag??0,colourPrimaries:m?.colourPrimaries??2,transferCharacteristics:m?.transferCharacteristics??2,matrixCoefficients:m?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=bc(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=nc(e),a=nc(e),s=nc(e);let n;"nclx"===i&&(n=Boolean(128&ac(e))),t.info.colorSpace={primaries:ie[r],transfer:ae[a],matrix:ne[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=uc(e),r=uc(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==t.info?.type)break;e.skip(4);j(3===ac(e)),ur(e),e.skip(2);const i=ac(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=ac(e);e.skip(t)}a&&e.skip(2);j(4===ac(e));const s=ur(e),n=e.filePos,o=ac(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":ct._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-n){j(5===ac(e));const i=ur(e);if(t.info.codecDescription=rc(e,i),"aac"===t.info.codec){const e=pt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&nc(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=ac(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=ac(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(1);const i=ac(e),r=nc(e),a=uc(e),s=cc(e),n=ac(e);let o;o=0!==n?rc(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,i),l.setUint16(10,r,!0),l.setUint32(12,a,!0),l.setInt16(16,s,!0),l.setUint8(18,n),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=127,r=128,a=e.filePos;for(;e.filePos>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(a&r)break}const s=e.filePos;e.filePos=a;const n=rc(e,s-a),o=new Uint8Array(4+n.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(n,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=rc(e,3),r=new dt(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=yt[a]),t.info.numberOfChannels=ui[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new dt(e),i=t.readBits(13),r=t.readBits(3),a=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),n=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let c=0;o>0?c=t.readBits(9):t.skipBits(1),a.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:n,numDepSub:o,chanLoc:c})}return 0===a.length?null:{dataRate:i,substreams:a}})(rc(e,D.contentSize));if(!i){ct._warn("Invalid dec3 box contents, ignoring.");break}const r=pi(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=gi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=J(e),i=t.getUint32(0);if(0===i)return null;const r=new dt(e);r.seekToByte(13);const a=r.readBits(2);r.skipBits(5);const s=r.readBits(1),n=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return 0!==o?c=Ei(o):ne.id===i);if(!r)break;const a=uc(e),s=(12&a)>>2,n=3&a,o=[ac,nc,oc,uc],c=o[(48&a)>>4],l=o[s],u=o[n],h=uc(e);for(let d=0;de.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let a=0;ae.id===l);if(!u)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=mc(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=uc(e)),a&&(u.currentFragmentState.defaultSampleDuration=uc(e)),s&&(u.currentFragmentState.defaultSampleSize=uc(e)),n&&(u.currentFragmentState.defaultSampleFlags=uc(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;j(t.currentFragmentState);const i=ac(e);e.skip(3);const r=0===i?uc(e):mc(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;j(this.currentFragment),j(t.currentFragmentState);const i=ac(e),r=oc(e),a=Boolean(1&r),s=Boolean(4&r),n=Boolean(256&r),o=Boolean(512&r),c=Boolean(1024&r),l=Boolean(2048&r),u=uc(e);let h=null;a&&(h=dc(e));let d,f=null;s&&(f=uc(e)),this.currentFragment.trackData.has(t.id)?(d=this.currentFragment.trackData.get(t.id),null!==h&&(d.currentOffset=t.currentFragmentState.baseDataOffset+h)):(d={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(h??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,d));for(let m=0;m0&&(a=rc(e,r));const s=Mr(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=ac(e);if(1&oc(e)){const i=bc(e,4),r=uc(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=uc(e);if(0===r)break;r>1&&ct._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?uc(e):Number(mc(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Mr(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;j(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=oc(e),a=Boolean(2&r),s=uc(e),n=t.encryptionInfo.defaultPerSampleIvSize;j(null!==n);for(let o=0;o0?r.set(rc(e,n),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=nc(e);s=[];for(let i=0;i0&&((B=this.metadataTags).trackNumber??(B.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((E=this.metadataTags).tracksTotal??(E.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((_=this.metadataTags).trackNumber??(_.trackNumber=t)),i>0&&((R=this.metadataTags).tracksTotal??(R.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((F=this.metadataTags).discNumber??(F.discNumber=t)),i>0&&((A=this.metadataTags).discsTotal??(A.discsTotal=i))}}}}}return e.filePos=O,!0}}class Pr{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;j(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return(t?.timestamp??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ce(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Cr(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Ar(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=pe(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=we(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 j(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Er(i,e);if(!r)return null;let a;if(t.metadataOnly)a=rr;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Xe(t)&&(t=await t),!t)return null;if(a=rc(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Dr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),u=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,h=pe(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),d=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(u?.moofOffset??0,d?.moofOffset??0)||null;let m;for(e?null===f||e.moofOffset>=f?(m=e.moofOffset+e.moofSize,n=e):m=f:m=f??0;;){if(n){const e=n.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(m,8,16);if(Xe(e)&&(e=await e),!e)break;const i=m,l=or(e);if(!l)break;if("moof"===l.name){n=await s.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(n);if(r)return this.fetchPacketInFragment(n,e,a);-1!==e&&(o=n,c=e)}m=i+l.totalSize}if(u&&(!o||o.moofOffset{var e,t,i,r,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&ri(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&ii(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&ei(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else{const e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Wt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Ft(e.data)}if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(this.internalTrack.info);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const s={codec:zi(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(s.displayAspectWidth=this.internalTrack.info.squarePixelWidth,s.displayAspectHeight=this.internalTrack.info.squarePixelHeight),s})()):null}}class xr extends Pr{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Cr=(e,t)=>{if(e.presentationTimestamps){const i=pe(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=pe(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)}},Br=(e,t)=>{if(!e.keySampleIndices)return Cr(e,t);if(e.presentationTimestamps){const i=pe(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!==me(e.keySampleIndices,i,e=>e))return i}return-1}{const i=Cr(e,t),r=pe(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Er=(e,t)=>{const i=pe(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=pe(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),n=e.sampleCompositionTimeOffsets[s];n&&t-n.startIndexe.startSampleIndex),l=e.sampleToChunk[c];j(l);const u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),h=e.chunkOffsets[u],d=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk;let f=0,m=h;if(1===e.sampleSizes.length)m+=o*(t-d),f+=o*l.samplesPerChunk;else for(let g=d;ge)}},_r=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=pe(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Rr=(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},Fr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Ar=e=>0===e.sampleSizes.length,Mr=e=>{var t;return e.currentFragmentState?(t=e.currentFragmentState).encryptionAuxInfo??(t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):e.encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},Dr=async(e,t,i)=>{if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{j(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[o],r=new Uint8Array(16);s>0?r.set(rc(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=nc(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Or=async(e,t,i,r)=>{j(e.encryptionInfo);const a=e.encryptionInfo;j(null!==a.defaultKid);const s=a.defaultKid;let n;const o=e.demuxer.decryptionKeyCache.get(s);if(o)n=await o;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(s));for(let e=0;e{j(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const a=new Uint8Array(16);a.set(i.iv,0);const s=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),n=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:a,length:64},s,e);return new Uint8Array(t)};if(!i.subsamples)return n(r);j(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Ur(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let c=0;for(const m of o)for(const e of m.perSubsample)c+=e.length;const l=new Uint8Array(c);let u=0;for(const m of o)for(const e of m.perSubsample)l.set(r.subarray(e.offset,e.offset+e.length),u),u+=e.length;const h=await n(l),d=new Uint8Array(r);let f=0;for(const m of o)for(const e of m.perSubsample)d.set(h.subarray(f,f+e.length),e.offset),f+=e.length;return d},zr=(e,t,i,r)=>{const a=new Sr;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,n=t.defaultSkipByteBlock;if(j(null!==s&&null!==n),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{const r=[],a=0!==t||0!==i;let s=0;for(const n of e){s+=n.clearLen;const e=[];if(a){let r=n.protectedLen,a=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:a,length:s}),a+=s,r-=s;const n=Math.min(16*i,r);a+=n,r-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;r.push({perSubsample:e})}return r};var qr,Wr;(Wr=qr||(qr={}))[Wr.EBML=440786851]="EBML",Wr[Wr.EBMLVersion=17030]="EBMLVersion",Wr[Wr.EBMLReadVersion=17143]="EBMLReadVersion",Wr[Wr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Wr[Wr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Wr[Wr.DocType=17026]="DocType",Wr[Wr.DocTypeVersion=17031]="DocTypeVersion",Wr[Wr.DocTypeReadVersion=17029]="DocTypeReadVersion",Wr[Wr.Void=236]="Void",Wr[Wr.Segment=408125543]="Segment",Wr[Wr.SeekHead=290298740]="SeekHead",Wr[Wr.Seek=19899]="Seek",Wr[Wr.SeekID=21419]="SeekID",Wr[Wr.SeekPosition=21420]="SeekPosition",Wr[Wr.Duration=17545]="Duration",Wr[Wr.Info=357149030]="Info",Wr[Wr.TimestampScale=2807729]="TimestampScale",Wr[Wr.MuxingApp=19840]="MuxingApp",Wr[Wr.WritingApp=22337]="WritingApp",Wr[Wr.Tracks=374648427]="Tracks",Wr[Wr.TrackEntry=174]="TrackEntry",Wr[Wr.TrackNumber=215]="TrackNumber",Wr[Wr.TrackUID=29637]="TrackUID",Wr[Wr.TrackType=131]="TrackType",Wr[Wr.FlagEnabled=185]="FlagEnabled",Wr[Wr.FlagDefault=136]="FlagDefault",Wr[Wr.FlagForced=21930]="FlagForced",Wr[Wr.FlagOriginal=21934]="FlagOriginal",Wr[Wr.FlagHearingImpaired=21931]="FlagHearingImpaired",Wr[Wr.FlagVisualImpaired=21932]="FlagVisualImpaired",Wr[Wr.FlagCommentary=21935]="FlagCommentary",Wr[Wr.FlagLacing=156]="FlagLacing",Wr[Wr.Name=21358]="Name",Wr[Wr.Language=2274716]="Language",Wr[Wr.LanguageBCP47=2274717]="LanguageBCP47",Wr[Wr.CodecID=134]="CodecID",Wr[Wr.CodecPrivate=25506]="CodecPrivate",Wr[Wr.CodecDelay=22186]="CodecDelay",Wr[Wr.SeekPreRoll=22203]="SeekPreRoll",Wr[Wr.DefaultDuration=2352003]="DefaultDuration",Wr[Wr.Video=224]="Video",Wr[Wr.PixelWidth=176]="PixelWidth",Wr[Wr.PixelHeight=186]="PixelHeight",Wr[Wr.DisplayWidth=21680]="DisplayWidth",Wr[Wr.DisplayHeight=21690]="DisplayHeight",Wr[Wr.DisplayUnit=21682]="DisplayUnit",Wr[Wr.AlphaMode=21440]="AlphaMode",Wr[Wr.Audio=225]="Audio",Wr[Wr.SamplingFrequency=181]="SamplingFrequency",Wr[Wr.Channels=159]="Channels",Wr[Wr.BitDepth=25188]="BitDepth",Wr[Wr.SimpleBlock=163]="SimpleBlock",Wr[Wr.BlockGroup=160]="BlockGroup",Wr[Wr.Block=161]="Block",Wr[Wr.BlockAdditions=30113]="BlockAdditions",Wr[Wr.BlockMore=166]="BlockMore",Wr[Wr.BlockAdditional=165]="BlockAdditional",Wr[Wr.BlockAddID=238]="BlockAddID",Wr[Wr.BlockDuration=155]="BlockDuration",Wr[Wr.ReferenceBlock=251]="ReferenceBlock",Wr[Wr.Cluster=524531317]="Cluster",Wr[Wr.Timestamp=231]="Timestamp",Wr[Wr.Cues=475249515]="Cues",Wr[Wr.CuePoint=187]="CuePoint",Wr[Wr.CueTime=179]="CueTime",Wr[Wr.CueTrackPositions=183]="CueTrackPositions",Wr[Wr.CueTrack=247]="CueTrack",Wr[Wr.CueClusterPosition=241]="CueClusterPosition",Wr[Wr.Colour=21936]="Colour",Wr[Wr.MatrixCoefficients=21937]="MatrixCoefficients",Wr[Wr.TransferCharacteristics=21946]="TransferCharacteristics",Wr[Wr.Primaries=21947]="Primaries",Wr[Wr.Range=21945]="Range",Wr[Wr.Projection=30320]="Projection",Wr[Wr.ProjectionType=30321]="ProjectionType",Wr[Wr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Wr[Wr.Attachments=423732329]="Attachments",Wr[Wr.AttachedFile=24999]="AttachedFile",Wr[Wr.FileDescription=18046]="FileDescription",Wr[Wr.FileName=18030]="FileName",Wr[Wr.FileMediaType=18016]="FileMediaType",Wr[Wr.FileData=18012]="FileData",Wr[Wr.FileUID=18094]="FileUID",Wr[Wr.Chapters=272869232]="Chapters",Wr[Wr.Tags=307544935]="Tags",Wr[Wr.Tag=29555]="Tag",Wr[Wr.Targets=25536]="Targets",Wr[Wr.TargetTypeValue=26826]="TargetTypeValue",Wr[Wr.TargetType=25546]="TargetType",Wr[Wr.TagTrackUID=25541]="TagTrackUID",Wr[Wr.TagEditionUID=25545]="TagEditionUID",Wr[Wr.TagChapterUID=25540]="TagChapterUID",Wr[Wr.TagAttachmentUID=25542]="TagAttachmentUID",Wr[Wr.SimpleTag=26568]="SimpleTag",Wr[Wr.TagName=17827]="TagName",Wr[Wr.TagLanguage=17530]="TagLanguage",Wr[Wr.TagString=17543]="TagString",Wr[Wr.TagBinary=17541]="TagBinary",Wr[Wr.ContentEncodings=28032]="ContentEncodings",Wr[Wr.ContentEncoding=25152]="ContentEncoding",Wr[Wr.ContentEncodingOrder=20529]="ContentEncodingOrder",Wr[Wr.ContentEncodingScope=20530]="ContentEncodingScope",Wr[Wr.ContentCompression=20532]="ContentCompression",Wr[Wr.ContentCompAlgo=16980]="ContentCompAlgo",Wr[Wr.ContentCompSettings=16981]="ContentCompSettings",Wr[Wr.ContentEncryption=20533]="ContentEncryption";const Hr=[qr.EBML,qr.Segment],Vr=[qr.SeekHead,qr.Info,qr.Cluster,qr.Tracks,qr.Cues,qr.Attachments,qr.Chapters,qr.Tags],jr=[...Hr,...Vr],Kr=16,Xr=e=>{if(e.remainingLength<1)return null;const t=ac(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=ac(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=Xr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===ac(e))return;e.skip(-1);const t=$r(e);return null===t?null:72057594037927940!==t?t:void 0},Jr=e=>{j(e.remainingLength>=2);const t=Qr(e);if(null===t)return null;const i=Yr(e);return null===i?null:{id:t,size:i}},Zr=(e,t)=>{const i=rc(e,t);let r=0;for(;r{const i=rc(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?kc(e):yc(e)},ia=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},ra=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;se.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,Kr);if(Xe(t)&&(t=await t),!t)break;const i=Jr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===qr.EBML){ya(a);let e=this.reader.requestSlice(s,a);if(Xe(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===qr.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===qr.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await ia(this.reader,s,jr,this.reader.fileSize)).pos-s}const e=X(this.segments);e&&(e.elementEndPos=s+a)}ya(a),e=s+a}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;null===this.currentSegment.elementEndPos||ie.id===a);if(-1!==o){const e=Ia[o].flag;this.currentSegment[e]=!0,ya(s);let t=this.reader.requestSlice(n,s);Xe(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===qr.Tags||a===qr.Attachments){a===qr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ya(s);let e=this.reader.requestSlice(n,s);Xe(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===qr.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Ia.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,Kr);if(Xe(i)&&(i=await i),!i)continue;const r=Jr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;ya(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);Xe(o)&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const n of this.currentSegment.tracks)null!==n.defaultDurationNs&&(n.defaultDuration=this.currentSegment.timestampFactor*n.defaultDurationNs/1e9);const r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const n of this.currentSegment.cuePoints){const e=r.get(n.trackId);e&&e.cuePoints.push(n)}for(const n of this.currentSegment.tracks){n.cuePoints.sort((e,t)=>e.time-t.time);for(let e=0;es&&(s=n.cuePoints.length,a=n);for(const n of this.currentSegment.tracks)0===n.cuePoints.length&&(n.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,2,Kr);Xe(i)&&(i=await i),j(i);const r=e,a=Jr(i);j(a);j(a.id===qr.Cluster);let s=a.size;const n=i.filePos;if(void 0===s){s=(await ia(this.reader,n,jr,t.elementEndPos)).pos-n}let o=this.reader.requestSlice(n,s);Xe(o)&&(o=await o);const c={segment:t,elementStartPos:r,elementEndPos:n+s,dataStartPos:n,timestamp:-1,trackData:new Map};if(this.currentCluster=c,o){const e=this.readContiguousElements(o,jr);c.elementEndPos=e}for(const[,l]of c.trackData){const e=l.track;j(l.blocks.length>0);let t=!1;for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const i=l.blocks[l.presentationTimestamps[0].blockIndex],a=l.blocks[X(l.presentationTimestamps).blockIndex];l.startTimestamp=i.timestamp,l.endTimestamp=a.timestamp+a.duration;const s=pe(e.clusterPositionCache,l.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:l.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=Jr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(ya(a),r){case qr.DocType:this.isWebM="webm"===Zr(e,a);break;case qr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case qr.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Gr(e,a)}break;case qr.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Gr(e,a)}break;case qr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Gr(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case qr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=ta(e,a);break;case qr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ht,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,a)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Ta.Block||e.data.algorithm!==va.HeaderStripping)&&(ct._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===aa)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===sa)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===na)this.currentTrack.info.codec="vp8";else if(t===oa)this.currentTrack.info.codec="vp9";else if(t===ca)this.currentTrack.info.codec="av1";else if(t===la){const e=this.currentTrack.codecPrivate?Z.decode(this.currentTrack.codecPrivate):"";Oi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Ea(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===ua?(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===ha?this.currentTrack.info.codec="mp3":t===da?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Wi):t===fa?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ma?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===pa?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ga?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ka?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new _a(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case qr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Gr(e,a);break;case qr.TrackType:{if(!this.currentTrack)break;const t=Gr(e,a);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...ce},alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case qr.FlagEnabled:if(!this.currentTrack)break;Gr(e,a)||(this.currentTrack=null);break;case qr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Gr(e,a);break;case qr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Gr(e,a);break;case qr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Gr(e,a);break;case qr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Gr(e,a);break;case qr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Gr(e,a);break;case qr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Gr(e,a);break;case qr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Zr(e,a);break;case qr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=rc(e,a);break;case qr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Gr(e,a);break;case qr.Name:if(!this.currentTrack)break;this.currentTrack.name=ea(e,a);break;case qr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Zr(e,a),Ae(this.currentTrack.languageCode)||(this.currentTrack.languageCode=xe);break;case qr.LanguageBCP47:{if(!this.currentTrack)break;const t=Zr(e,a).split("-")[0];this.currentTrack.languageCode=t||xe,this.currentTrack.hasLanguageBcp47=!0}break;case qr.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Gr(e,a);break;case qr.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Gr(e,a);break;case qr.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Gr(e,a);break;case qr.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Gr(e,a);break;case qr.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Gr(e,a);break;case qr.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Gr(e,a);break;case qr.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ne[t];this.currentTrack.info.colorSpace.matrix=i}break;case qr.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case qr.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ae[t];this.currentTrack.info.colorSpace.transfer=i}break;case qr.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ie[t];this.currentTrack.info.colorSpace.primaries=i}break;case qr.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-ta(e,a);try{this.currentTrack.info.rotation=K(t)}catch{}}break;case qr.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=ta(e,a);break;case qr.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Gr(e,a);break;case qr.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Gr(e,a);break;case qr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case qr.CueTime:this.currentCueTime=Gr(e,a);break;case qr.CueTrackPositions:{if(null===this.currentCueTime)break;j(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case qr.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Gr(e,a)}break;case qr.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;j(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Gr(e,a)}break;case qr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Gr(e,a);break;case qr.SimpleBlock:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=rc(e,a-(e.filePos-s)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case qr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case qr.Block:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e)>>1&3,o=rc(e,a-(e.filePos-s)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case qr.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case qr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case qr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=rc(e,a);break;case qr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Gr(e,a);break;case qr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Gr(e,a);break;case qr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case qr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case qr.Targets:this.readContiguousElements(e.slice(s,a));break;case qr.TargetTypeValue:50!==Gr(e,a)&&(this.currentTagTargetIsMovie=!1);break;case qr.TagTrackUID:case qr.TagEditionUID:case qr.TagChapterUID:case qr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case qr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case qr.TagName:this.currentSimpleTagName=ea(e,a);break;case qr.TagString:{if(!this.currentSimpleTagName)break;const t=ea(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.TagBinary:{if(!this.currentSimpleTagName)break;const t=rc(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new ut(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case qr.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;rt.order-e.order);break;case qr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ta.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case qr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Gr(e,a);break;case qr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Gr(e,a);break;case qr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:va.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case qr.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Gr(e,a);break;case qr.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=rc(e,a);break;case qr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){j(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(j(r.data),"decompress"===r.data.type)if(r.data.algorithm===va.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var i;if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??(r.raw={}),(i=r.raw)[e]??(i[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":r.title??(r.title=t);break;case"description":r.description??(r.description=t);break;case"artist":r.artist??(r.artist=t);break;case"album":r.album??(r.album=t);break;case"album_artist":r.albumArtist??(r.albumArtist=t);break;case"genre":r.genre??(r.genre=t);break;case"comment":r.comment??(r.comment=t);break;case"lyrics":r.lyrics??(r.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??(r.date=e))}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??(r.trackNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??(r.tracksTotal=a))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??(r.discNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??(r.discsTotal=a))}}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){j(r.trackBacking);const e=await r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=t??0,i}}class Ba{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ce(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=pe(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=we(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 j(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(-1===t)return null;const r=e.trackData.get(this.internalTrack.id).blocks[t];if(j(r),r.decoded||(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),r.decoded=!0),!r.postProcessed){if("prores"===this.internalTrack.info?.codec){if(!(r.data.length>=8&&105===r.data[4]&&99===r.data[5]&&112===r.data[6]&&102===r.data[7])){const e=new Uint8Array(r.data.length+8);J(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(r.data,8),r.data=e}}r.postProcessed=!0}const a=i.metadataOnly?rr:r.data,s=r.timestamp/this.internalTrack.segment.timestampFactor,n=r.duration/this.internalTrack.segment.timestampFactor,o={};r.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(o.alpha=i.metadataOnly?rr:r.mainAdditional,o.alphaByteLength=r.mainAdditional.byteLength);const c=new ar(a,r.isKeyFrame?"key":"delta",s,n,e.dataStartPos+t,r.data.byteLength,o);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,i,r,a){const{demuxer:s,segment:n}=this.internalTrack;let o=null,c=null,l=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(c=e,l=i)}const u=pe(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==u?this.internalTrack.cuePoints[u]:null,d=pe(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),f=-1!==d?this.internalTrack.clusterPositionCache[d]:null,m=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let p;for(e?null===m||e.elementStartPos>=m?(p=e.elementEndPos,o=e):p=m:p=m??n.clusterSeekStartPos;null===n.elementEndPos||p<=n.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,2,Kr);if(Xe(e)&&(e=await e),!e)break;const i=p,u=Jr(e);if(!u||!Vr.includes(u.id)&&u.id!==qr.Void){const e=await ra(s.reader,i,Vr,Math.min(n.elementEndPos??1/0,i+xa));if(e){p=e;continue}break}const h=u.id;let d=u.size;const f=e.filePos;if(h===qr.Cluster){o=await s.readCluster(i,n),d=o.elementEndPos-f;const{blockIndex:e,correctBlockFound:r}=t(o);if(r)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,l=e)}if(void 0===d){j(h!==qr.Cluster);d=(await ia(s.reader,f,jr,n.elementEndPos)).pos-f}const m=f+d;if(null===n.elementEndPos){let e=s.reader.requestSliceRange(m,2,Kr);if(Xe(e)&&(e=await e),!e)break;if(Qr(e)===qr.Segment){n.elementEndPos=m;break}}p=m}if(h&&(!c||c.elementStartPos{var e,t,i,r;let a=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(a=await this.getFirstPacket({}));const s={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&a?Ft(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?Wt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?ei(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?ii(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?ri(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(s);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const n={codec:zi(s),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})()):null}}class _a extends Ba{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Ra=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=uc(s),n=null!==e.fileSize?e.fileSize-a:null,o=Yi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&tr(o.header.channel)===tr(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Fa extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Aa(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Ra(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Qi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Xe(r)&&(r=await r),r){const a=uc(r);if(a===$i||a===Gi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Xe(t)&&(t=await t),t){const e=rc(t,12),i=J(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Zi.FrameCount?i.getUint32(4,!1):null,fileSize:r&Zi.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(Xe(a)&&(a=await a),!a)break;Rc(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Ic){let e=this.reader.requestSlice(this.reader.fileSize-Ic,Ic);Xe(e)&&(e=await e),j(e);"TAG"===bc(e,3)&&Bc(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Aa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(j(null!==e.firstFrameHeader),j(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,a=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(a<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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>>0&4294967295}const Na=e=>{const t=J(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let a=0;a>>24^t])>>>0}return t.setUint32(22,i,!0),r},Oa=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){j(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,n=(e[0]&s)>>1;if(n>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const c=t.vorbisInfo.modeBlockflags[n];if(a=t.vorbisInfo.blocksizes[c],1===c){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+a>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:ai[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},La=27,za=282,Ua=e=>{const t=e.filePos;if(hc(e)!==Ma)return null;e.skip(1);const i=ac(e),r=gc(e),a=hc(e),s=hc(e),n=hc(e),o=ac(e),c=new Uint8Array(o);for(let h=0;he+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},qa=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Ma)return!0;e.skip(1)}}return!1};class Wa extends ir{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,La,za);if(Xe(t)&&(t=await t),!t)break;const i=Ua(t);if(!i)break;if(!!!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const e=await this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?await this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&await this.readOpusMetadata(e,t),null!==t.codecInfo.codec&&this.trackBackings.push(new Ha(t,this)))}})())}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=await this.findNextPacketStart(r),!i)return;const a=await this.readPacket(i.startPage,i.startSegmentIndex);if(!a)return;if(3!==r.data[0]||5!==a.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const c=J(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&l),1<<(l>>4)],modeBlockflags:si(a.data).modeBlockflags},li(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const a=(e=>{const t=J(e),i=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}})(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=Wi,t.codecInfo.opusInfo={preSkip:a.preSkip},li(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){j(te+t.length,0);if(0===o)return null;const c=new Uint8Array(o);let l=0;for(let u=0;u{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Ha{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ue,this.internalSampleRate="opus"===e.codecInfo.codec?Wi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return j(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return j(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(j(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=Oa(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new ar(i.metadataOnly?rr:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),s}async getFirstPacket(e){j(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(j(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=await this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const a=i.timestampInSamples+i.durationInSamples,s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const i=Ce(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;j(this.bitstream.lastMetadataPacket);const r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let a=r.startPage,s=this.demuxer.reader.fileSize;const n=[a];e:for(;a.headerStartPos+a.totalSizei?s=l.headerStartPos:(a=l,n.push(l));continue e}r=l.headerStartPos+l.totalSize}}let o=r.startPage;for(const k of n){if(k.granulePosition===a.granulePosition)break;(!o||k.headerStartPos>o.headerStartPos)&&(o=k)}let c=o;const l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,La,za);Xe(t)&&(t=await t),j(t);const i=Ua(t);j(i),c=i,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}j(-1!==c.granulePosition);let u,h,d=null,f=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{u=0,h=!1;for(let t=c.lacingValues.length-1;t>=0;t--){if(c.lacingValues[t]<255){d=t+1;break}}if(null===d)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const e={data:rr,endPage:f,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){const e=ja(l,c,d);j(e);const t=Va(l,e.page,e.segmentIndex);t&&(c=t.page,d=t.segmentIndex)}else for(;;){const e=ja(l,c,d);if(!e)break;const t=Va(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,d=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,m=e.segmentIndex;break}}}let p=null,g=null;for(;null!==c;){j(null!==d);const e=await this.demuxer.readPacket(c,d);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&di||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,d=a.startSegmentIndex}return p}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=Ce(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=pe(this.sequentialScanCache,i,e=>e.timestampInSamples);let a;if(-1!==r){const e=this.sequentialScanCache[r];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let s=0;for(;a&&a.timestampe)break;if(a=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(a);j(e),this.sequentialScanCache.length>0&&j(X(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Va=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}j(-1===a);if(!(1&r.headerType)){a=0;break}const t=be(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=be(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);Xe(e)&&(e=await e),j(e);const t=bc(e,4),i="RIFX"!==t,r="RF64"===t,a=lc(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==bc(e,4))throw new Error("Invalid WAVE file - wrong format");let n=0,o=null,c=e.filePos;for(;null===s||c=18&&357!==a){const e=sc(r,i),s=t-18;if(Math.min(s,e)>=22&&a===Ka.EXTENSIBLE){r.skip(6);const e=rc(r,16);a=e[0]|e[1]<<8}}if(a!==Ka.MULAW&&a!==Ka.ALAW||(c=8),a!==Ka.PCM&&a!==Ka.IEEE_FLOAT&&a!==Ka.ALAW&&a!==Ka.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===Ka.PCM&&![8,16,24,32].includes(c))throw new Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(a===Ka.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,h,d,f;let m=this.reader.requestSlice(e,t);if(Xe(m)&&(m=await m),!m)return;const p=bc(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=bc(m,4),t=lc(m,i),p=rc(m,t);let k=0;for(let i=0;i0&&((c=this.metadataTags).trackNumber??(c.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((l=this.metadataTags).tracksTotal??(l.tracksTotal=i))}break;case"ICRD":case"IDIT":{const e=new Date(y);Number.isNaN(e.getTime())||((u=this.metadataTags).date??(u.date=e))}break;case"YEAR":{const e=Number.parseInt(y,10);Number.isInteger(e)&&e>0&&((h=this.metadataTags).date??(h.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(d=this.metadataTags).genre??(d.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(Xe(i)&&(i=await i),!i)return;const r=_c(i);if(r){const a=t-xc;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+xc,r.size);Rc(t,r,this.metadataTags)}}}getCodec(){if(j(this.audioInfo),this.audioInfo.format===Ka.MULAW)return"ulaw";if(this.audioInfo.format===Ka.ALAW)return"alaw";if(this.audioInfo.format===Ka.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===Ka.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}j(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Ga=2048;class Qa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(j(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht}}async getPacketAtIndex(e,t){j(e>=0),j(this.demuxer.audioInfo);const i=e*Ga*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(Ga*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(Xe(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=rr;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Xe(e)&&(e=await e),j(e),a=rc(e,r)}const s=e*Ga/this.demuxer.audioInfo.sampleRate,n=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new ar(a,"key",s,n,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){j(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ga,(this.demuxer.dataSize-1)/(Ga*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=await this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;j(null===this.demuxer.reader.fileSize);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){const e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){j(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ga);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ya=e=>{const t=e.filePos,i=rc(e,9),r=new dt(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const a=r.readBits(1),s=r.readBits(2)+1,n=r.readBits(4);if(15===n)return null;r.skipBits(1);const o=r.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const c=r.readBits(13);r.skipBits(11);const l=r.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===a?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:n,channelConfiguration:o,frameLength:c,numberOfAacFrames:l,crcCheck:u,startPos:t}},Ja=1024;class Za extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();j(this.firstFrameHeader),this.trackBackings=[new es(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ya(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=ft[t.samplingFrequencyIndex];j(void 0!==i);const r=Ja/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=Ja,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,xc);if(Xe(t)&&(t=await t),!t)break;const i=_c(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Xe(r)&&(r=await r),!r)break;Rc(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class es{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Ja}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getCodec(){return"aac"}getInternalCodecId(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){j(this.demuxer.firstFrameHeader);const e=mt[this.demuxer.firstFrameHeader.channelConfiguration];return j(void 0!==e),e}getSampleRate(){j(this.demuxer.firstFrameHeader);const e=ft[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return j(void 0!==e),e}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.dataSize)}return new ar(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=me(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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{var e;let t=0;for(;;){let e=this.reader.requestSlice(t,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=_c(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Xe(r)&&(r=await r),j(r),Rc(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:s.end-e,isLastFrame:!0};if(255===ac(s)){const t=s.filePos;if(ac(s)!==(1===this.blockingBit?249:248)){s.filePos=t;continue}s.skip(-2);const i=s.filePos-e,r=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!r){s.filePos=t;continue}if(0===this.blockingBit){if(r.num-n.num!==1){s.filePos=t;continue}}else if(r.num-n.num!==n.blockSize){s.filePos=t;continue}return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=rc(e,4),a=new dt(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){j(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){j(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");j(!t);if(0!==a.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(a.readBits(4));if(!s)return null;j(this.audioInfo);const n=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(a.readBits(4),this.audioInfo.sampleRate);if(!n)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const o=(e=>{let t=0;const i=new dt(rc(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new dt(rc(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?nc(e)+1:"uncommon-u8"===t?ac(e)+1:"number"===typeof t?t:(Te(t),void j(!1)))(e,s),l=((e,t)=>"uncommon-u16"===t?nc(e):"uncommon-u16-10"===t?10*nc(e):"uncommon-u8"===t?ac(e):"number"===typeof t?t:null)(e,n);if(null===l)return null;if(l!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,h=ac(e);e.skip(-u),e.skip(-1);const d=(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})(rc(e,u));return h!==d?null:{num:o,blockSize:c,sampleRate:l}}async advanceReader(){await this.readMetadata(),j(null!==this.lastLoadedPos),j(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class is{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return xe}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(j(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){await this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],a=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.byteSize)}j(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new ar(r,"key",a,s,e,i.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const rs=9e4,as=2**33,ss=188,ns="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.",os=new Set([133,134,162]),cs=new Set;class ls extends ir{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,205);Xe(e)&&(e=await e),j(e);const t=rc(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ss;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,r=null,a=!1,s=!1;for(;;){const e=await this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){i+=this.packetStride;continue}const t=await this.readSection(i,!0,!s);if(!t)break;const n=3,o=32;let c=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i);c=2===e.readBits(8)}}if(0!==t.pid||a)if(t.pid!==r&&!c||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=hs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(await this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const r=new gs(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,await r.markNextPacket(),"avc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=Ft(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];j(t);const i=Nt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const a=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;a>0&&s>0&&(a>s?(e.info.squarePixelWidth=Math.round(e.info.width*a/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/a))),e.info.colorSpace={primaries:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[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=Wt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===St.SPS_NUT).nalUnits[0];j(t);const i=qt(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:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:zi({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await r.markNextPacket(),!r.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=tc.tempFromBytes(r.suppliedPacket.data),i=Ya(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=mt[i.channelConfiguration],e.info.sampleRate=ft[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=uc(tc.tempFromBytes(r.suppliedPacket.data)),i=Yi(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=tr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=hi(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=ui[t.acmod]+t.lfeon,e.info.sampleRate=yt[t.fscod]}else if("eac3"===e.info.codec){const t=mi(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=pi(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=gi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ii(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:qi({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const a=e.readBits(10),c=e.pos+8*a;let l=!1;for(;e.pos=4){const t=e.readBits(32);l||(l=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=c;8*(r+n)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),a=e.pos+8*r;let s=!1,n=!1,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let c=null;const u=l&&os.has(t)?130:t;switch(u){case 27:case 36:c={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",c={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:n?c={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?c={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(c={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:cs.has(t)||(ct._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),cs.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}s=!0}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+n)-e.pos>o;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==r)throw new Error("Only files with a single program are supported.");r=i}}if(null===r)throw new Error("Program Association Table must link to a Program Map Table.");a=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!a)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const n of this.elementaryStreams)n.initialized&&("video"===n.info.type?this.trackBackingEntries.push(new fs(n)):this.trackBackingEntries.push(new ms(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),h=!!(1&e.adaptationFieldControl);let d=0;if(n&&(d=1+e.body[0],e===c&&d>1&&(u=e.body[1]>>6&1)),h&&(0===d?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(d)),o+=e.body.byteLength-d)),r=a,!t&&o>=64){l=!1;break}if(-1!==me(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=pe(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!c)return null;if(1===s.length)n=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);n=new Uint8Array(e);let t=0;for(const i of s)n.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:c.pid,payload:n,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(Xe(t)&&(t=await t),!t)return null;if(71!==ac(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=nc(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:ac(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,ss);if(Xe(t)&&(t=await t),!t)return null;const i=rc(t,ss);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=as-t?-8589934592:as}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new dt(t.payload);if(1!==r.readBits(24))return null;const a=r.readBits(8);if(r.skipBits(16),188===a||190===a||191===a||240===a||241===a||255===a||242===a||248===a)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let n=null;if(2===s||3===s)n=0,r.skipBits(4),n+=r.readBits(3)*(1<<30),r.skipBits(1),n+=32768*r.readBits(15),r.skipBits(1),n+=r.readBits(15),n=e.normalizeTimestamp(n);else if(i)throw new Error(ns);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},hs=(e,t,i)=>{j(null!==t.endPos);const r=us(e,t,i);if(!r)return null;const a=new dt(t.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const n=a.readBits(8),o=a.pos+8*n;a.pos=o;const c=o/8;j(Number.isInteger(c));const l=t.payload.subarray(c,s>0?6+s:t.payload.byteLength);return{...r,data:l}};class ds{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++,j(r instanceof ds),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 xe}getDisposition(){return{...ht,primary:!1}}getTimeResolution(){return rs}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new ar(i.metadataOnly?rr:e.data,r,e.pts/rs,Math.max(t/rs,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;j(t);const i=hs(this.elementaryStream.demuxer,t,!0);j(i);const r=new gs(this.elementaryStream,i),a=new ks(this,r),s=await a.readNext();if(!s)return null;const n=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(n,a),this.packetSectionStarts.set(n,s.packet.sectionStartPos),n}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const r=await i.readNext();if(!r)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(a,i),this.packetSectionStarts.set(a,r.packet.sectionStartPos),a}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const a=this.elementaryStream.demuxer,s=await a.readSection(r,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n);i=new ks(this,o);const c=e.sequenceNumber;for(;;){const e=await i.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){const r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){const r=Ce(e*rs),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:n}=a,o=this.elementaryStream.pid,c=async(e,t,i)=>{let r=e;for(;re.pts),m=-1!==f?d[f]:null;if(m&&r-m.pts<45e3)h=m.sectionStartPos;else{let e=0;if(null!==s.fileSize){const t=Math.ceil(s.fileSize/n);if(t>1){let i=0,s=t-1;for(e=i;i<=s;){const t=Math.floor((i+s)/2),o=_e(t*n,a.packetStride)+u.sectionStartPos,l=o+n,h=await c(o,l,!1);h?h.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}h=_e(e*n,a.packetStride)+u.sectionStartPos}const p=await c(h,s.fileSize??1/0,!1);let g=p?.pesPacketHeader??null;g||(g=u);const k=this.getReorderSize(),y=async(e,t)=>{const s=await a.readSection(e,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n),c=new ks(this,o);for(;;){if((X(c.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await c.readNextPacket()))break}const l=we(c.presentationOrderPackets,t);if(-1===l)return null;const u=c.presentationOrderPackets[l],h=0===l?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=h;const d=await c.readNext();j(d);const f=this.createEncodedPacket(d.packet,d.duration,i);return this.packetBuffers.set(f,c),this.packetSectionStarts.set(f,d.packet.sectionStartPos),f};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=g.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;g=e,ps(this.elementaryStream,g);break}}}e+=a.packetStride}}e:for(let e=0;e=a.packetOffset;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){g=e;break}}}e-=a.packetStride}}return y(g.sectionStartPos,e=>e.pts<=r)}{let e=h,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let h=null;const d=e<=u.sectionStartPos;let f,m=null;if(d)f=u,m=l;else{const t=await c(e,s.fileSize??1/0,i);f=t?.pesPacketHeader??null,m=t?.section??null}let p=!1,g=0;e:for(;f&&!(null!==t&&f.sectionStartPos>=t);){if(f.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===f.randomAccessIndicator;else{j(m);const t=hs(a,m,!0);j(t);const i=new gs(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(h=f)}if(f.pts>r&&(p=!0),p&&(g++,g>k))break;let e=f.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,i);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){f=e,m=t,ps(this.elementaryStream,f);break}}}e+=a.packetStride}}if(h){let e=h;if(0===g)e:for(let r=0;r=a.packetOffset;){const r=await a.readPacketHeader(t);if(!r)break e;if(r.pid===o&&1===r.payloadUnitStartIndicator){const r=await a.readSection(t,i);if(r){const t=us(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await y(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return j(t),t}if(d)return null;t=e,e=Math.max(_e(e-u.sectionStartPos-n,a.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}}class fs extends ds{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class ms extends ds{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const ps=(e,t)=>{const i=e.referencePesPackets,r=pe(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const a=i[r];if(t.pts<=a.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return j(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=l)break;u=e;const i=o+u;if(u+3>=l){this.seekTo(i);break}const h=c[u+1],d=c[u+2],f=c[u+3];let m=0;if(0===h&&0===d&&1===f?m=4:0===h&&1===d&&(m=3),0===m){u++;continue}const p=i;a??(a=p);const g=u+m,k=g+r,y=6;if(k+("avc"===t?y:1)>l){this.seekTo(i);break}const b=c[g];let w,T,S;if("avc"===t)w=Ct(b),T=w===wt.NON_IDR_SLICE||w===wt.SLICE_DPA||w===wt.IDR,S=w===wt.SEI||w===wt.SPS||w===wt.PPS||w===wt.AUD;else{w=Ut(b);if(((1&b)<<5|c[g+1]>>3)>0){u+=m;continue}T=w<=St.RASL_R||w>=St.BLA_W_LP&&w<=21,S=w>=St.VPS_NUT&&w<=37||w===St.PREFIX_SEI_NUT||w>=41&&w<=44||w>=48&&w<=55}let v=!1;if(T){let e;if("avc"===t){const t=c.subarray(k,k+y),i=$(new dt(t));e=!s||i<=n,n=i}else e=c[k]>>7===1;e&&(s?v=!0:s=!0)}else S&&s&&(v=!0);if(v){const e=p-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=m}if(ea){const e=this.endPos-a;return this.seekTo(a),this.supplyPacket(e,0)}}else{const t=e.info.codec,i=128;for(;;){let r=this.ensureBuffered(i);Xe(r)&&(r=await r);const a=this.currentPos;for(;this.currentPos-a>6,n=63&a[4];if(3===s||n>37){this.seekTo(t+1);continue}const o=di[3*n+s];j(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),Xe(r)&&(r=await r);const c=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,c)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(Xe(r)&&(r=await r),r<5)return;const a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}const s=2*(((7&a[2])<<8|a[3])+1),n=3===a[4]>>6?3:a[4]>>4&3,o=fi[n];this.seekTo(t),r=this.ensureBuffered(s),Xe(r)&&(r=await r);const c=256*o,l=Math.round(c*rs/e.info.sampleRate);return this.supplyPacket(r,l)}if("dts"===t){if(127!==i&&100!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(18);if(Xe(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=Ci(a);let n=s?null:Bi(a);if(!s&&!n){this.seekTo(t+1);continue}if(n&&!n.asset){this.seekTo(t);const e=Math.min(n.frameSize,4096);let i=this.ensureBuffered(e);Xe(i)&&(i=await i),n=Bi(this.readBytes(i))??n}let o=s?s.frameSize:n.frameSize;if(s){let e=4*Math.ceil(s.frameSize/4);for(;;){this.seekTo(t);const i=e+10;let r=this.ensureBuffered(i);if(Xe(r)&&(r=await r),r=0)}async readNext(){if(0===this.decodeOrderPackets.length){if(!(await this.readNextPacket()))return null}await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(j(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(j(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(await this.readNextPacket()))break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const ys="application/vnd.apple.mpegurl",bs="#EXT-X-STREAM-INF:",ws="#EXT-X-I-FRAME-STREAM-INF:",Ts="#EXT-X-MEDIA:",Ss="#EXTINF:",vs="#EXT-X-MAP:",Ps="#EXT-X-KEY:",Is="#EXT-X-MEDIA-SEQUENCE:",xs="#EXT-X-BYTERANGE:",Cs="#EXT-X-PROGRAM-DATE-TIME:",Bs="#EXT-X-TARGETDURATION:",Es="#EXT-X-PLAYLIST-TYPE:",_s=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Rs{constructor(e){this._attributes={};let t="",i="",r=!1,a=!1;for(let s=0;s{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,t,i))}else if("audio"===t.type){const i=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=await t.getTracks();for(const r of i)if("video"===r.type){const t=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,{id:e.length+1,type:"audio"},t))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let r;if(this.firstSegmentFirstTimestamps.has(i))r=this.firstSegmentFirstTimestamps.get(i);else{const e=this.getInputForSegment(i);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(i,r)}if(i===e)return i.timestamp-r;const a=await this.getFirstTimestampForInput(t),s=e.timestamp-i.timestamp,n=a-r-s;return Math.abs(n)<=Math.min(.25,s)?i.timestamp-r:e.timestamp-a}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class As{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var e;if((e=this.segmentedInput).firstSegment??(e.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let t=this.segmentedInput.firstSegment,i=null;for(;t;){const e=this.segmentedInput.getInputForSegment(t);if(i=(await e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,i)break;t=await this.segmentedInput.getNextSegment(t,{})}if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i,this.firstSegment=t})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),j(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){j(e.sequenceNumber>=0),j(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:Ee(e.timestamp+r,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s}async getFirstPacket(e){await this.hydrate(),j(this.firstInputTrack),j(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){const r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,i,t)}if(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait}),!i)break;const r=this.segmentedInput.getInputForSegment(i);t=(await r.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,i){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const a=i?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(a)return this.createAdjustedPacket(a,r.segment,r.track);let s=r.segment;for(;;){const e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),a=(await i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!a){s=e;continue}const n=await a._backing.getFirstPacket(t);return n?this.createAdjustedPacket(n,e,a):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){const a=this.segmentedInput.getInputForSegment(r),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const n=e-await this.segmentedInput.getMediaOffset(r,a),o=i?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(o)return this.createAdjustedPacket(o,r,s);r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null}}class Ms extends As{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Ds extends As{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}Ye();const Ns=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class Os extends st{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Zo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Ns),e=this._getFileSize(),j(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new Zo;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Js(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Ls(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Ls{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;j(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class zs extends Os{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 Os||e instanceof Ls))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof Os?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Xe(t)?t.then(i):i(t)}}const Us=(e,t)=>e.path===t.path;class qs extends zs{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 Os?e.ref():e;return this._root=t,this._rootRequest=null,t};Xe(e)?this._rootRequest=e.then(t):(t(e),j(this._root))}if(this._rootRequest)return this._rootRequest.then(a=>a.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const Ws="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class Hs extends Os{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),Ws?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Qs.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){j(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Ue()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),Ws?.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch{}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return ct._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)},js=new Set;class Ks extends zs{constructor(e,t={}){if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new Ks(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Vs,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...Ne(t.requestInit.headers)},r=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==r&&(i=e[r],delete e[r],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){i??(i=t);const r=new Request(e);r.headers.delete("Range"),this._url=r}}if(null!==i){const e=$s(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:Qs.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:Ie(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const a=this._offset,s=this._sequentialBacking?this._sequentialBacking._read(a+e,a+t):this._orchestrator.read(a+e,a+t,Math.max(a+i,a),a+Math.min(r,this._length??1/0)),n=e=>e?(e.offset-=this._offset,e):null;return Xe(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);r.redirected&&(this.rootPath=r.url);e:if(null===this._orchestrator.fileSize&&(206===r.status||"basic"===r.type&&!r.headers.has("Content-Encoding"))){const t=r.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=r.headers.get("Content-Length");if(i){const t=206===r.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==r.status){if(this._sequentialBacking)return void r.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||js.has(e.origin)||(ct._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),js.add(e.origin))}return void this._transitionToSequentialMode(r.body)}const a=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return i.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let r;try{r=await a.read()}catch(t){if(this._disposed)throw t;const e=this._getRetryDelay(1,t,this._url);if(null!==e){ct._error("Error while reading response stream. Attempting to resume.",t),await at(1e3*e);break}throw t}if(e.aborted)continue;const{done:s,value:n}=r;if(s){if(e.currentPos>=e.targetPos)return void this._orchestrator.onWorkerFinished(e);if(e.strictTarget)break;return void this._orchestrator.onWorkerFinished(e)}this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const a=new ReadableStream({pull:async e=>{for(;;){let s;try{s=await t.read()}catch(a){if(this._disposed)throw a;const e=this._getRetryDelay(1,a,this._url);if(null===e)throw a;ct._error("Error while reading response stream. Attempting to resume.",a),await at(1e3*e);const s=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=s.body.getReader(),r=206===s.status?0:i;continue}if(s.done)return void e.close();let n=s.value;if(r>0){const e=Math.min(r,n.length);r-=e,n=n.subarray(e)}if(0!==n.length)return i+=n.length,void e.enqueue(n)}},cancel:()=>t.cancel()}),s=new Gs(a,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const n=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)n.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)n.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of n){const e=s._read(o.start,o.start+o.bytes.length);Xe(e)?e.then(e=>{e?(j(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(j(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Xs=/^bytes=(\d+)-(\d*)$/,$s=e=>{const t=Xs.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=pe(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let a=e;const s=new Uint8Array(t-e);if(-1!==i)for(let l=i;l=t)break;const r=Math.max(e,i.start);r>a&&this._throwDueToCacheMiss();const n=Math.min(t,i.end);ra&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:c}=ke();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),n}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex0;){const e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new Zo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Qs={fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(Ge(e,t,r,a.targetPos)){const e=a.targetPos-a.startPos,r=Math.ceil((e+1)/i)*i,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,r);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+524288)}}};class Ys{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){j(!this.disposed);const a=this.options.prefetchProfile(e,t,this.workers),s=Math.max(a.start,i),n=Math.min(a.end,this.fileSize??1/0,r);j(s<=e&&t<=n);let o=null;const c=pe(this.cache,e,e=>e.start),l=-1!==c?this.cache[c]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,o={bytes:l.bytes,view:l.view,offset:l.start});const u=pe(this.cache,s,e=>e.start),h=o?null:new Uint8Array(t-e);let d=0,f=s;const m=[];if(-1!==u){for(let i=u;i=n)break;if(r.end<=s)continue;const a=Math.max(s,r.start),o=Math.min(n,r.end);if(j(a<=o),f=h.length&&(o={bytes:h,view:J(h),offset:e}),0===m.length)return j(o),o;const{promise:p,resolve:g,reject:k}=ke(),y=[];for(const w of m){const i=Math.max(e,w.start),r=Math.min(t,w.end);i===w.start&&r===w.end?y.push(w):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&w.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,w.end),i.strictTarget&&(i.strictTarget=e),b&&i.pendingSlices.push(b)):(t++,i={hole:{start:w.start,end:w.end},strictTarget:e,pendingSlices:b?[b]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.hole.end)break;i.hole.end=Math.max(i.hole.end,e.hole.end),i.pendingSlices.push(...e.pendingSlices),i.strictTarget&&(i.strictTarget=e.strictTarget),i.age=Math.min(i.age,e.age),this.queuedReads.splice(t+1,1)}}}return o?p.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(j(h),o=p.then(t=>t&&{bytes:t,view:J(t),offset:e})),o}checkHoleAgainstWorker(e,t,i){if(Ge(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=r),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const t=this.workers.indexOf(e);j(-1!==t),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=pe(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=J(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=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=J(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;ithis._length)return null;const a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return Xe(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var Zs=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},en=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const tn=/^0[xX][0-9a-fA-F]+$/,rn=/^data:.*;base64,/i;class an extends Fs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await at(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new ec(i.source),a=await r.requestEntireFile();j(a),e=wc(a,a.length,{ignore:_s}),i.source instanceof zs&&(this.rootPath=i.source.rootPath)}catch(y){t.error=y,t.hasError=!0}finally{en(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,n=null,o=0,c=null,l=null,u=null,h=null,d=null,f=null,m=!1,p=X(this.segments)??null;const g=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},k=e=>{o=e,p&&(j(null!==p.sequenceNumber),p.sequenceNumber0&&null!==f&&(r=o*f),m=!0);const e=y.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);s=a}else if(y.startsWith(vs)){const e=new Rs(y.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let o=null;if(null!==i&&(o=g(i)),o&&null===o.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!p){const e={path:Ze(this.rootPath,t),offset:o?.offset??0,length:o?.length??null};if("AES-128"===n?.method&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:d}}s=null,null===h?u=null:h=null}else if(y.startsWith(Ps)){const e=new Rs(y.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!tn.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(fr);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=J(t).getUint32(0);r=sr(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(y.startsWith(Is)){const e=y.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);k(t)}else if(y.startsWith(xs)){const e=g(y.slice(17));if(null===e.offset){if(null===u)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=u}h=e,u=e.offset+e.length}else if(y.startsWith(Cs)){if(p)continue;const e=y.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(d===s)continue;if(null===d&&this.segments.length>0){const e=X(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}d=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===y)c=null;else if(y.startsWith(Bs)){const e=y.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,f=t}else{if("#EXT-X-ENDLIST"===y){this.streamHasEnded=!0;break}if(y.startsWith(Es)){"vod"===y.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==y)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0}}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return 0===this.segments.length&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){0===this.segments.length&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=pe(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let r=null;(t.initSegment||t.firstSegment)&&(r=this.getInputForSegment(t.initSegment??t.firstSegment));const a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let i=e.psshBoxes;const{psshBox:r}=t.encryption;return null!==r.keyIds&&!r.keyIds.includes(e.keyId)||i.some(e=>nr(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new Yo({source:new qs(t.location.path,async e=>{j(e.isRoot);const i={...e,isRoot:!1};let r;const a=t.location.offset>0||null!==t.location.length;if(t.encryption&&"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method)if("AES-128"===t.encryption.method){const e=t.encryption;j(e.iv);let s=await this.input._getSourceCached(i);if(a){const e=s.source.slice(t.location.offset,t.location.length??void 0).ref();s.free(),s=e}const n=((e,t,i)=>{let r=!1,a=0;const s=new Sr;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(Xe(o)&&(o=await o),!o||0===o.length)throw new Error("Invalid ciphertext.");const c=o.length;if(c%16!==0)throw new Error("Invalid ciphertext.");const l=65552===c?c-16:c,u=rc(o,l),h=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=h.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new ec(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},Qo),!1),r=new ec(i.source),a=await r.requestSlice(0,fr);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:rc(a,fr),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{en(t)}},()=>{s.free()});r=new Gs(n).ref()}else j(!1);else if(r=await this.input._getSourceCached(i),a){const e=r.source.slice(t.location.offset,t.location.length??void 0).ref();r.free(),r=e}return r}),formats:this.input._formats.filter(e=>!(e instanceof Pn)),initInput:r??void 0,formatOptions:a});s._onFormatDetermined=e=>{if(("SAMPLE-AES"===t.encryption?.method||"SAMPLE-AES-CTR"===t.encryption?.method)&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:s,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=tt(this.inputCache,e=>e.age);j(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class sn extends ir{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{j(this.input._rootSource instanceof zs);const e=await this.input._reader.requestEntireFile();j(e);const t=wc(e,e.length,{ignore:_s}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let u=1;u"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],n=[...new Set(a.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=await Promise.all(r.map(async(e,t)=>{const r=[],o=e.attributes.get("codecs");let c;if(o)c=o.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=await t.getTrackBackings(),r=await Promise.all(i.map(async e=>({track:e,codec:await e.getCodec()})));c=await Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const l=e.attributes.get("video"),u=e.attributes.get("audio"),h=c.some(e=>_i.includes(ji(e))),d=c.some(e=>Fi.includes(ji(e)));if(null!==l&&!h){if(!s.includes(l))throw new Error(`Invalid M3U8 file; variant stream references video group "${l}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===l&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}if(null!==u&&!d){if(!n.includes(u))throw new Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}c=[...new Set(c)];let f=null,m=null;const p=e.attributes.getAsNumber("bandwidth");j(null!==p);const g=e.attributes.getAsNumber("average-bandwidth"),k=e.attributes.get("name");for(const i of c){const o=ji(i);if(null!==o)if(_i.includes(o)){if(null!==f)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");f=i;const n=e.attributes.get("video");if(null===n){const i=e.attributes.get("resolution");let a=null,s=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(a=Number(e[1]),s=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:xe,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:f,pairingMask:1n<0?a:null}})}else{if(!n.includes(s))throw new Error(`Invalid M3U8 file; variant stream references audio group "${s}" which is not defined in any #EXT-X-MEDIA tags.`);for(const i of a){const a=i.attributes.get("group-id"),n=i.attributes.get("type");if(a!==s||"audio"!==n.toLowerCase())continue;const o=i.attributes.get("channels")??e.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;r.push({id:-1,demuxer:this,backingTrack:null,default:ln(i.attributes),autoselect:ln(i.attributes)||un(i.attributes),languageCode:hn(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<0?c:null}})}}}}return r})),c=[],l=e=>{const t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||(t.default=e.default),t.autoselect||(t.autoselect=e.autoselect),t.lineNumber=Math.min(t.lineNumber,e.lineNumber),null!==e.peakBitrate&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),null!==e.averageBitrate&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===xe&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(const u of o)for(const e of u)l(e);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of c)"video"===u.info.type?this.trackBackings.push(new on(u)):this.trackBackings.push(new cn(u));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),j(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 an(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ys}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class nn{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof on){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{j(this instanceof cn);for(const e of i)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...ht,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(){j(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class on extends nn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ji(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class cn extends nn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ji(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const ln=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}".`)},un=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}".`)},hn=e=>{if(null===e)return xe;const t=e.split("-")[0];return t||xe};class dn{constructor(){this._isIsobmff=!1}}class fn extends dn{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return null;t.skip(4);const i=bc(t,4);return"ftyp"!==i&&"styp"!==i?null:bc(t,4)}_createDemuxer(e){return new vr(e)}}class mn extends fn{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(Xe(t)&&(t=await t),!t)return!1;let r=uc(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Xe(t)&&(t=await t),!t)return!1;r=mc(t),a=16}if(r8)return!1;if(Gr(i,r)!==qr.EBML)return!1;const a=Yr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(Xe(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Jr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case qr.EBMLVersion:if(1!==Gr(s,r))return!1;break;case qr.EBMLReadVersion:if(1!==Gr(s,r))return!1;break;case qr.DocType:if(Zr(s,r)!==t)return!1;break;case qr.DocTypeVersion:if(Gr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Ca(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class kn extends gn{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class yn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}const i=await Ra(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=Qi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(Xe(s)&&(s=await s),!s)return!1;const n=uc(s);if(n===$i||n===Gi)return!0;t=i.startPos+i.header.totalSize;const o=await Ra(e._reader,t,t+4);if(!o)return!1;const c=o.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new Fa(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class bn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return!1;const i=bc(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===bc(t,4)}_createDemuxer(e){return new $a(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class wn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return Xe(t)&&(t=await t),!!t&&"OggS"===bc(t,4)}_createDemuxer(e){return new Wa(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Tn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Xe(i)&&(i=await i),!!i&&"fLaC"===bc(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ts(e)}}class Sn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Xe(i)&&(i=await i),!i)return!1;const r=Ya(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Xe(i)&&(i=await i),!i)return!1;const a=Ya(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new Za(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class vn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(Xe(t)&&(t=await t),!t)return!1;const i=rc(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 ls(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Pn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(Xe(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===bc(t,7)))return!1;if(!(e._rootSource instanceof zs))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 sn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return ys}}const In=new mn,xn=new pn,Cn=new gn,Bn=new kn,En=new yn,_n=new bn,Rn=new wn,Fn=new Sn,An=new Tn,Mn=new vn,Dn=new Pn,Nn=[Dn,In,xn,Cn,Bn,_n,Rn,An,En,Fn,Mn],On=[Dn,In,xn,En,Fn,Mn];var Ln=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});Ye();let zn=-1/0,Un=-1/0,qn=null;"undefined"!==typeof FinalizationRegistry&&(qn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-zn>=1e3&&(ct._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."),zn=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Un>=1e3&&(ct._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."),Un=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Wn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Hn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Vn=new Set(Hn);class jn{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(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!Vn.has(t.format))throw new TypeError("init.format must be one of: "+Hn.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&&rt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??to(t.format,t.codedWidth,t.codedHeight);let r=t.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?Y(e):Y(e).slice(),this._layout=i,this.colorSpace=new Qn(r)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==t?.visibleRect&&rt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Qn(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&rt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new jn(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Me),duration:Math.trunc((t.duration??0)*Me)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const a=t.visibleRect??{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(a.width,a.height),n=s.getContext("2d",{alpha:We(),willReadFrequently:!0});if(!n)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");n.drawImage(e,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Qn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Wn))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!Hn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=it({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),qn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return j(null!==this._data),this._data instanceof Wn?new jn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Yn(this._data)?new jn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(j(this._layout),new jn(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new jn(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(qn?.unregister(this),this._data instanceof Wn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Yn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(eo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(e.format??this.format))throw new Error("Cannot get allocation size when format is null.");if(Yn(this._data))return this._data.allocationSize(e);return ro(this,e).allocationSize}async copyTo(e,t={}){if(!le(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(eo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(j(null!==this._data),Yn(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof Wn)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(i,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(r instanceof jn))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(r.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${r.format}' instead.`);return await r.copyTo(e,t)}catch(c){i.error=c,i.hasError=!0}finally{Ln(i)}}}const i=ro(this,t);j(this.format);const r=Y(e);if(r.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=e}else if(this._data instanceof Uint8Array)j(this._layout),j(this._layout.length===a.length),s=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");j(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:Y(t.data),stride:4*this.codedWidth}]}const n=[],o=a.length;for(let l=0;la.byteLength)throw new Error("Source buffer OOB read.");if(c+u>r.byteLength)throw new Error("Destination buffer OOB write.");const i=a.subarray(o,o+u);r.set(i,c),o+=t,c+=e.destinationStride}n.push(h)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const a=[];for(const s of e)i.set(s.data,r),a.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:a[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Yn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(j(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,h=this.displayWidth,d=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,h=r,d=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=h,g=d)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:h,sHeight:d}=this._rotateSourceRegion(l,u,h,d,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,h,d,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Zn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,h=t.crop;h&&(h=Jn(h,s,n));const{sx:d,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],h="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*h,u=a*h,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?Gn(u,h):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,h)):m||f.clearRect(0,0,u,h),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(d,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(d,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(j(null!==this._data),this._data instanceof Wn||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(e){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&Zn(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=K(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=Jn(a,i,r));const s=a?a.width:i,n=a?a.height:r,o=s/n;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/o):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*o):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=n),c=Be(c,e.roundDimensionsTo??1),l=Be(l,e.roundDimensionsTo??1);const u={width:c,height:l,fit:e.fit??"fill",rotation:t,crop:a??{left:0,top:0,width:i,height:r},alpha:e.alpha??"keep"};for(const m of Kn){let e=m(this,u);if(Xe(e)&&(e=await e),null!==e)return e}const{canvas:h,context:d,isNew:f}=Gn(u.width,u.height);return this._drawWithFitAndMipmapping(h,d,{fit:u.fit,rotation:u.rotation,crop:u.crop,targetIsFresh:f,fillBlack:"discard"===u.alpha}),new jn(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Kn=[],Xn=[];let $n=0;const Gn=(e,t)=>{for(const a of Xn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=$n++,{canvas:a.canvas,context:a.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Xn.length>=3&&Xn.splice(tt(Xn,e=>e.age),1),Xn.push({canvas:i,context:r,age:$n++}),{canvas:i,context:r,isNew:!0}};class Qn{constructor(e){if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(te);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(re);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(se);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!==typeof e.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Yn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Jn=(e,t,i)=>{const r=Math.min(e.left,t),a=Math.min(e.top,i),s=Math.min(e.width,t-r),n=Math.min(e.height,i-a);return j(s>=0),j(n>=0),{left:r,top:a,width:s,height:n}},Zn=(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.")},eo=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.")}},to=(e,t,i)=>{const r=io(e),a=[];let s=0;for(const n of r){const e=Math.ceil(t/n.widthDivisor),r=Math.ceil(i/n.heightDivisor),o=e*n.sampleBytes,c=o*r;a.push({offset:s,stride:o}),s+=c}return a},io=e=>{const t=(e,t,i,r,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Te(e),j(!1)}},ro=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=ao(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let n;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");n=t.format}else n=e.format;return no(a,n,s)},ao=(e,t,i,r,a)=>{const s={...e};if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!so(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},so=(e,t)=>{if(null===e)return!0;const i=io(e);for(let r=0;r{const r=io(t),a=r.length;if(void 0!==i&&i.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const n=[],o=[];for(let c=0;c4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(d),s=Math.max(s,d);for(let e=0;e 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(uo(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*uo(this.format);if(i.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const a=uo(t),s=ho(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?r:r*this.numberOfChannels)*a}copyTo(e,t){if(!le(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&&!oo.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:a}=t;let{planeIndex:s}=t,n=this.format;const o=i??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:c-u;if(h>c-u)throw new RangeError("frameCount out of range");const d=uo(o),f=ho(o);if(f&&s>=l)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?h:h*l)*d;if(e.byteLength2&&o!==n)return void go(this._data,p,n,o,l,s,u,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:h,format:o})}catch(S){if("f32-planar"===o)throw S;n="f32-planar"}}const k=fo(n),y=uo(n),b=ho(n);let w;if(this._data instanceof co){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=c*y*(b?1:l);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)w=e(s),s=0;else{w=new Uint8Array(c*y*l);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new lo({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(qn?.unregister(this),this._data instanceof co?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof co?this._createAudioDataFromData():po(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(ho(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const a=Math.min(s,o),c=new Float32Array(i*a);for(let t=0;t0;){const a=Math.min(s,o),l=new Float32Array(i*a);for(let t=0;t{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")}},ho=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},fo=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)}},mo=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,Ie(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,Ie(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,Ie(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},po=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,go=(e,t,i,r,a,s,n,o)=>{const c=fo(i),l=mo(r),u=uo(i),h=uo(r),d=ho(i);if(ho(r))if(d){const r=new ArrayBuffer(o*u),a=J(r);e.copyTo(r,{planeIndex:s,frameOffset:n,frameCount:o,format:i});for(let e=0;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.")},wo=e=>{if(!Je(e))throw new TypeError("timestamp must be a number.")},To=(e,t,i)=>i.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const i=await e.determinePacketType(t);return i&&(t.type=i),t}):t;class So{constructor(e){if(!(e instanceof Oo))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(bo(e),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){bo(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i}async getNextKeyPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,t):i}packets(e,t,i={}){if(void 0!==e&&!(e instanceof ar))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof ar))throw new TypeError("endPacket must be an EncodedPacket.");if(bo(i),this._track.input._disposed)throw new Zo;const r=[];let{promise:a,resolve:s}=ke(),{promise:n,resolve:o}=ke(),c=!1,l=!1,u=null,h=!1;const d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=ke()),await n):(r.push(u),s(),({promise:a,resolve:s}=ke()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{h||(u=e,h=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Zo;if(l)return{value:void 0,done:!0};if(h)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class vo{constructor(e,t){this.onSample=e,this.onError=t}}class Po{mediaSamplesInRange(e=-1/0,t=1/0,i){wo(e),wo(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=ke(),{promise:c,resolve:l}=ke(),u=!1,h=!1,d=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(h=!0),h?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=ke())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!h&&!this._track.input._disposed;){const e=Io(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=ke()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),d||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,h=!0,y(),new Zo;if(d)return{value:void 0,done:!0};if(p)throw d=!0,h=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,h=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:n}=ke(),{promise:o,resolve:c}=ke(),l=!1,u=!1,h=null,d=null,f=!1;const m=e=>{a.push(e),n(),({promise:s,resolve:n}=ke())},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(d=e,f=!0,n())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=async()=>{j(s),j(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:c}=ke()),await o;if(u)break;const r=await e.getNextPacket(t,p);j(r),h.decode(r),t=r}g=-1},y=async()=>{j(h),await h.flush();for(let e=0;e{f||(d=e,f=!0,n())}).finally(()=>{h?.close()});const g=this._track,k=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(g.input._disposed)throw u=!0,k(),new Zo;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),d;if(a.length>0){const e=a.shift();return j(void 0!==e),c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await s}},return:async()=>(u=!0,c(),n(),k(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Io=e=>0===e?40:8;class xo extends vo{constructor(e,t,i,r,a,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=a,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const n=ko.find(e=>e.supports(i,r));if(n)this.customDecoder=new n,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof jn))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();j(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(Ve()){if("avc"===i&&this.decoderConfig.description){const e=Mt(Y(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Nt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Lt(t),this.decoderConfig={...this.decoderConfig,description:At(e)}))}}oe(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(j(this.decoder),Ue()||ge(this.inputTimestamps,e.timestamp,e=>e),Ve()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of xt(e.data,this.decoderConfig)){const r=Ct(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===wt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(a.offset,a.offset+a.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&Y(t.description)[4];return Rt(e,i+1)}return _t(e)})(t,this.decoderConfig);e=new ar(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Jt(e.data,this.decoderConfig);t&&(e=new ar(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new Bo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();j(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();j(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=ni(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of zt(e,this.decoderConfig)){const i=Ut(e[t.offset]);if(i===St.RASL_N||i===St.RASL_R)return!0}return!1}sampleHandler(e){if(Ue()){if(this.sampleQueue.length>0&&e.timestamp>=X(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ge(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();j(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){const i=ke();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){j(this.merger);const i=await this.merger.merge(e,t);r.sample=new jn(i)}else r.sample=new jn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){ye(this.finalSamples,r),this.onError(a)}finally{ye(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Ue()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let Co=null;class Bo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Co){const e=new Blob([`(${Eo.toString()})()`],{type:"application/javascript"});Co=URL.createObjectURL(e)}const e=Ie(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=ke();this.pendingRequests.set(i,r);const a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Eo=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:a,alpha:s}=e.data;i=i.then(async()=>{try{const e=await r(a,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{a.close(),s.close()}})});const r=async(e,t)=>{const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),c=i.includes("P12"),l=r.includes("P10"),u=r.includes("P12");if(l!==o||u!==c)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return await a(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return await s(e,t,i);if("NV12"===i)return await n(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)},a=async(e,t,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=new Uint8Array(4*s);await e.copyTo(n);const c=await o(t,r,a,1);for(let o=0,u=3;o{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=i.includes("P10"),n=i.includes("P12"),c=s||n?2:1;let l,u;i.startsWith("I420")?(l=Math.ceil(r/2),u=Math.ceil(a/2)):i.startsWith("I422")?(l=Math.ceil(r/2),u=a):(l=r,u=a);const h=r*a,d=h*c,f=l*u*c,m=new Uint8Array(d+2*f+h*c);await e.copyTo(m);const p=await o(t,r,a,c),g=d+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,h=s+n,d=s;for(let o=0;o{const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e);const n=t.format;if("RGBA"===n||"BGRA"===n||"RGBX"===n||"BGRX"===n){const t="RGBA"===n||"RGBX"===n?0:2,a=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class Ro extends Po{constructor(e,t={}){if(!(e instanceof Uo))throw new TypeError("videoTrack must be an InputVideoTrack.");_o(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(je("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getRotation();let a=await this._track.getDecoderConfig();const s=await this._track.getTimeResolution();return j(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new xo(e,t,i,a,r,s)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Fo{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Uo))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&&Zn(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&_o(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ro(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[s,n]=i%180===0?[r,a]:[a,r];let o=e.crop;o&&(o=Jn(o,s,n));let[c,l]=o?[o.width,o.height]:[s,n];const u=c/l;void 0!==e.width&&void 0===e.height?(c=e.width,l=Math.round(c/u)):void 0===e.width&&void 0!==e.height?(l=e.height,c=Math.round(l*u)):void 0!==e.width&&void 0!==e.height&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=i,this._crop=o})())}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],a=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||We()});j(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&We()});const n={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e,t){wo(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*Pe(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Pe(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Ao extends vo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const a=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=yo.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 lo))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new lo(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(j(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Mo extends vo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,j(Ri.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=Vi(this.codec);switch(this.inputSampleSize=a,a){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const a=(1<(e=>{let t=0,i=0,r=85^e;128&r&&(r&=-129,t=-1),i=4+((240&r)>>4);let a=0;return a=4!==i?1<e.getUint16(t,s)-32768:"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):j(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Se(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Se(e,t,i)<<8>>8)(e,t,s):j(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-2**31:"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):j(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):j(!1);break;default:Te(a),j(!1)}switch(a){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:Te(a),j(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=J(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(r),s=new DataView(a);for(let l=0;l=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const c=new lo({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Do extends Po{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(je("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getDecoderConfig();return j(i&&r),Ri.includes(r.codec)?new Mo(e,t,r):new Ao(e,t,i,r)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class No{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Do(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){wo(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return Pe(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Pe(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Oo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Uo}isAudioTrack(){return this instanceof qo}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Lo(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Lo(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Lo(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Lo(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return null!==await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Lo(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return Ee((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new So(this);let r=1/0,a=-1/0,s=0,n=0;for await(const o of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-r)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-r)).toPrecision(16)):0}}async isLive(){return null!==await this._backing.getLiveRefreshInterval()}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Oo))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&0n!==(this._backing.getPairingMask()&e._backing.getPairingMask())}async getPairableTracks(e){return this.input.getTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=zo(e));const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Lo=(e,t,i)=>{if(Xe(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},zo=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 Xe(r)?r.then(i):i(r)}:void 0};class Uo extends Oo{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??"prores"===await this._backing.getCodec()}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Lo(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Lo(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Lo(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Lo(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Lo(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:Lo(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Lo(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){const e=await(this._backing.getMetadataDisplayWidth?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(void 0!==e){const t=Lo(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Lo(t,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await(this._backing.getMetadataDisplayHeight?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(void 0!==e){const t=Lo(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Lo(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),ko.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(null===t)return null;const i=await this.getDecoderConfig();return j(i),ni(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!Je(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,r=new So(this),a=[];let s=-1/0,n=0;for await(const I of r.packets(void 0,void 0,{metadataOnly:!0})){if(a.length>=i&&I.timestamp>=s)break;a.push(I.timestamp),s=Math.max(s,I.timestamp),n++}const o=new Float64Array(a.length);for(let I=0;Ie-t),b=k-1>>1,w=k>>1;let T=0,S=0,v=0;for(const I of y)if(v+=f.get(I),0===T&&v>b&&(T=I),v>w){S=I;break}const P=(h/T+h/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:Go(P),minFrameRate:h/p,maxFrameRate:h/m,averageFrameRate:h*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class qo extends Oo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Lo(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Lo(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),yo.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Wo=e=>-(e??-1/0),Ho=e=>-e,Vo=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 Xe(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return Xe(r)?r.then(i):i(r)}:void 0}},jo=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return Xe(r)?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Xe(r)||Xe(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),Ko=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>Xe(e))){const t=await Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!t?.sortBy)return i;const r=i.map(e=>t.sortBy(e)),a=r.some(e=>Xe(e))?await Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{const i=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(i.length,r.length);for(let s=0;se.track)},Xo=(e,t)=>{const i=1e6,r=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let T=1;T0))return null;s[T-1]=t}const n=s.slice();n.sort();let o=n[Math.floor(.05*n.length)];for(let T=0;T<6;T++){let e=0,t=0;for(const a of s){const i=Math.max(1,Math.round(a/o));Math.abs(a-i*o)>=r||(e+=a,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let c=0,l=0,u=0;for(const T of s){const e=Math.max(1,Math.round(T/o));Math.abs(T-e*o)>=r||(c++,l+=T,u+=e)}if(c/s.length<.98)return null;o=l/u;const h=1/Math.min(u,1e3),d=Math.max(Number.EPSILON,o-h),f=o+h,m=t/f,p=t/d,g=t/o;let k=null,y=1/0;for(const T of a){if(Tp)continue;const e=Math.abs(T/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,a=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof dn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Os||e.source instanceof Ls))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Os&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Yo))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Os?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){j(this._rootSource instanceof zs);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){const i=this._sourceCache.find(i=>i.cacheGroup===t&&Us(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Us(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(et(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=tt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);j(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),ye(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);j(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:a}),a.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new ec(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)}throw new Jo})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),j(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Jo)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=await Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e),r=(await Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)}async getTracks(e){e&&(e=Vo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Ko(t,e)}async getVideoTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return Ko(t,e)}async getAudioTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return Ko(t,e)}async getPrimaryVideoTrack(e){e&&(e=Vo(e));const t=jo(e,{sortBy:async e=>[Ho((await e.getDisposition()).default),Ho(await e.hasPairableAudioTrack()),Ho(!(await e.hasOnlyKeyPackets())),Wo(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Vo(e));const t=await this.getPrimaryVideoTrack(),i=jo(e,{sortBy:async e=>[Ho(!t||e.canBePairedWith(t)),Ho((await e.getDisposition()).default),Wo(await e.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new Uo(this,e):new qo(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class Jo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Zo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class ec{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new Zo;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 tc(t,J(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Ns);return Xe(r)?r.then(t=>t?new tc(t.bytes,t.view,t.offset,e,i):null):r?new tc(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Zo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(j(null!==this.fileSizeNonStrict),this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i)));return Xe(r)?r.then(a):a(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(async()=>{const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(Xe(i)&&(i=await i),!i||0===i.length)break;const r=rc(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new tc(i,J(i),0,0,t)})()}}class tc{constructor(e,t,i,r,a){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=a,this.bufferPos=r-i}static tempFromBytes(e){return new tc(e,J(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new tc(this.bytes,this.view,this.offset,e,e+t)}}const ic=(e,t)=>{if(e.filePose.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.`)},rc=(e,t)=>{ic(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},ac=e=>(ic(e,1),e.view.getUint8(e.bufferPos++)),sc=(e,t)=>{ic(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},nc=e=>{ic(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},oc=e=>{ic(e,3);const t=Se(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},cc=e=>{ic(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},lc=(e,t)=>{ic(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},uc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},hc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},dc=e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},fc=(e,t)=>{let i,r;return t?(i=lc(e,!0),r=lc(e,!0)):(r=lc(e,!1),i=lc(e,!1)),4294967296*r+i},mc=e=>4294967296*uc(e)+uc(e),pc=e=>4294967296*dc(e)+uc(e),gc=e=>{const t=hc(e),i=(e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},kc=e=>{ic(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},yc=e=>{ic(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},bc=(e,t)=>{ic(e,t);let i="";for(let r=0;rZ.decode(rc(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Tc,Sc,vc,Pc;(Sc=Tc||(Tc={}))[Sc.Unsynchronisation=128]="Unsynchronisation",Sc[Sc.ExtendedHeader=64]="ExtendedHeader",Sc[Sc.ExperimentalIndicator=32]="ExperimentalIndicator",Sc[Sc.Footer=16]="Footer",(Pc=vc||(vc={}))[Pc.ISO_8859_1=0]="ISO_8859_1",Pc[Pc.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Pc[Pc.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Pc[Pc.UTF_8=3]="UTF_8";const Ic=128,xc=10,Cc=["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"],Bc=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=rc(e,Ic-3)),e.filePos=r;const a=Ec(e,30);a&&(t.title??(t.title=a));const s=Ec(e,30);s&&(t.artist??(t.artist=s));const n=Ec(e,30);n&&(t.album??(t.album=n));const o=Ec(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=rc(e,30);let u;if(0===l[28]&&0!==l[29]){const i=l[29];i>0&&(t.trackNumber??(t.trackNumber=i)),e.skip(-30),u=Ec(e,28),e.skip(2)}else e.skip(-30),u=Ec(e,30);u&&(t.comment??(t.comment=u));const h=ac(e);h{const i=rc(e,t),r=$e(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=bc(e,3),r=ac(e),a=ac(e),s=ac(e),n=uc(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=Ji(n);return s&Tc.Footer&&(o+=xc),{majorVersion:r,revision:a,flags:s,size:o}},Rc=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void ct._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Tc.Footer?t.size-xc:t.size,l=rc(e,c),u=new Fc(t,l);if(t.flags&Tc.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Tc.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let h=!1,d=!1,f=!1;if(3===t.majorVersion?(h=!!(64&e.flags),d=!!(128&e.flags)):4===t.majorVersion&&(h=!!(4&e.flags),d=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&Tc.Unsynchronisation)),h)ct._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(d)ct._warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=l;else{if(f&&u.ununsynchronizeRegion(u.pos,l),i.raw??(i.raw={}),"TXXX"===e.id){const e=(r=i.raw).TXXX??(r.TXXX={}),t=u.readId3V2TextEncoding(),a=u.readId3V2Text(t,l),s=u.readId3V2Text(t,l);e[a]??(e[a]=s)}else"T"===e.id[0]?(a=i.raw)[s=e.id]??(a[s]=u.readId3V2EncodingAndText(l)):(n=i.raw)[o=e.id]??(n[o]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":i.title??(i.title=u.readId3V2EncodingAndText(l));break;case"TIT3":case"TT3":i.description??(i.description=u.readId3V2EncodingAndText(l));break;case"TPE1":case"TP1":i.artist??(i.artist=u.readId3V2EncodingAndText(l));break;case"TALB":case"TAL":i.album??(i.album=u.readId3V2EncodingAndText(l));break;case"TPE2":case"TP2":i.albumArtist??(i.albumArtist=u.readId3V2EncodingAndText(l));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.trackNumber??(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.tracksTotal??(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.discNumber??(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.discsTotal??(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(l);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}i.genre??(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(l),t=new Date(e);Number.isNaN(t.getTime())||(i.date??(i.date=t))}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(l),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.lyrics??(i.lyrics=u.readId3V2Text(e,l))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.comment??(i.comment=u.readId3V2Text(e,l))}break;case"APIC":case"PIC":{const e=u.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=u.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=u.readId3V2Text(e,l);const a=u.readU8(),s=u.readId3V2Text(e,l).trimEnd(),n=l-u.pos;if(n>=0){const e=u.readBytes(n);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===a?"coverFront":4===a?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=l}}};class Fc{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{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:Ji(t);s(e)&&(i=e)}return this.pos=a,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case vc.ISO_8859_1:{let e="";for(let t=0;t0===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=$e(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=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}case vc.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=$e(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 vc.UTF_8:{const e=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ac{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch{i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(a){try{r?.disconnect()}catch(s){console.warn("MediaBunny gain setup cleanup:",s)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),a}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{t?.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Mc{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(a){r=!0,i=a}try{e.disconnect()}catch(a){r||(r=!0,i=a)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const a=function(e,t,i,r){const a=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(a+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(a,r),offset:a=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===a.offset?s.start(a.startAt):s.start(a.startAt,a.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,a.endMediaTime)}catch(n){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw n}}}const Dc=Symbol("cancelled");class Nc{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Dc);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function Oc(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class Lc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}async stopIterator(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),await t}cancel(){this.task?.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}async run(e){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Nc;this.task=r;let a=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!a||this.host.audioIterator===a);try{for(a=t.buffers(this.host.currentTime),this.host.audioIterator=a;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=await r.wait(a.next());if(i===Dc||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if(await r.wait(this.contexts.resume(i))===Dc||!s())return;Oc(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(await r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(await r.delay(50))||!s())return}}catch(n){if(s())throw n}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}}}class zc{constructor(e,h){N(this,u),N(this,t,!1),N(this,i,0),N(this,r),N(this,a),N(this,s),N(this,n,null),N(this,o,null),N(this,c,null),N(this,l),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,O(this,r,new Ac(this)),O(this,a,new Mc(this)),O(this,s,new Lc(this,D(this,r),D(this,a))),O(this,l,h)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){D(this,r).ensure(e)}updateGain(){D(this,r).updateGain()}stopQueuedNodes(){D(this,a).stop()}async stopIterator(){await D(this,s).stopIterator()}handleNoAudioTrack(){D(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){z(this,i)._++;try{this.pause()}finally{O(this,c,null),this.input=null,this.audioSink=null}}async load(e,r){if(D(this,t))return;this.cancelPending();const a=D(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>L(this,u,h).call(this,e,a,r));O(this,c,s);try{await s}finally{D(this,c)===s&&O(this,c,null)}}async runIterator(e){D(this,t)||await D(this,s).run(e)}async play(){if(D(this,t))return;if(D(this,o))return D(this,o);if(!this.paused)return;const e=new Nc;O(this,n,e);const r=D(this,i),a=L(this,u,f).call(this,e,r);O(this,o,a);try{await a}finally{D(this,n)===e&&(O(this,n,null),O(this,o,null))}}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,D(this,n)?.cancel(),O(this,n,null),O(this,o,null),D(this,s).cancel(),this.stopQueuedNodes()}async seek(e){if(D(this,t))return;const i=!this.paused;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext?.currentTime??0,this.latestScheduledEndTime=this.playbackTimeAtStart;const r=++this.asyncId;i&&L(this,u,d).call(this,r)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(D(this,t)||e===this.playbackRate)return;const i=this.currentTime;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=i,this.audioContextStartTime=this.audioContext?.currentTime??0,this.playbackRate=e,this.latestScheduledEndTime=i;const r=++this.asyncId;this.paused||L(this,u,d).call(this,r)}destroy(){if(D(this,t))return;O(this,t,!0),z(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>D(this,r).destroy()])try{t()}catch(a){e.push(a)}if(this.input=null,this.audioSink=null,O(this,c,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,a=new WeakMap,s=new WeakMap,n=new WeakMap,o=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakSet,h=async function({input:e,audioTrack:r,duration:a},s,n){const o=()=>!D(this,t)&&D(this,i)===s;if(o()){this.input=e,this.duration=a;try{const e=r&&null!==r.codec&&await r.canDecode();if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new No(r)}else this.handleNoAudioTrack();o()&&n?.()}catch(c){if(o())throw c}}},d=function(e){this.runIterator(e).catch(i=>{if(!D(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{D(this,l)?D(this,l).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=async function(e,a){const s=()=>!D(this,t)&&!e.cancelled&&D(this,i)===a;try{const t=D(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if(await e.wait(D(this,r).resume(t))===Dc||!s())return}if(D(this,c)){if(await e.wait(D(this,c))===Dc||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,L(this,u,d).call(this,++this.asyncId)}catch(n){if(s())throw n}};const Uc=new WeakMap;async function qc(e,t,i){const{input:r,loadSeq:a}=e;if(!e.media?.isHls||!r||e.destroyed)return;const s={};Uc.set(e,s);const n=()=>!e.destroyed&&e.loadSeq===a&&e.input===r&&Uc.get(e)===s;for(;n();){const a=e.media;if(!a?.isHls)return;let s;try{s=await i(r,a,t,n)}catch(o){if(!n())return;if(e.media===a)throw o;continue}if(!n())return;if(e.media===a){if(s)try{await e.replaceTracks(s)}catch(o){if(n())throw o}return}}}async function Wc(e,t,i,r){const a=await e.getVideoTracks();if(!r())return null;const s="auto"===i?await e.getPrimaryVideoTrack():a.find(e=>e.id===i)??t.videoTrack;if(!r()||!s)return null;let n=t.audioTrack,o=t.audioMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableAudioTrack(),o="auto"),{videoTrack:s,audioTrack:n,videoMode:"auto"===i?"auto":"manual",audioMode:o}}async function Hc(e,t,i,r){const a=await e.getAudioTracks();if(!r())return null;const s="auto"===i?t.videoTrack?await t.videoTrack.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack():a.find(e=>e.id===i)??t.audioTrack;if(!r()||!s)return null;let n=t.videoTrack,o=t.videoMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableVideoTrack(),o="auto"),{videoTrack:n,audioTrack:s,videoMode:o,audioMode:"auto"===i?"auto":"manual"}}async function Vc(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const jc=/\.m3u8(?:$|[?#])/i;function Kc(e){return"string"===typeof e&&jc.test(e)}function Xc(e){const t=function(e){return"string"===typeof e?new Ks(e):e instanceof Blob?new Hs(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Gs(e):e??null}(e);return t?new Yo({source:t,formats:Kc(e)?On:Nn}):null}class $c{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){return this.controller?.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}async wait(e,t){try{await Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,e?.dispose()}cancel(){if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),this.controller?.abort(),this.disposeInput()}}}async function Gc({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),a=t||i,s=Boolean(a&&await a.isLive());let n=Number.NaN;return r.length>0&&(n=await e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==n||s||(n=await e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:n??Number.NaN}function Qc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class Yc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return{...Qc(),source:this.host.loadSeq,complete:Qc()}}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,e?.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,e?.complete.resolve(),e?.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}async runPlay(e){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(await this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,await this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),Oc(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}}seek(e,t){return this.position(async t=>{const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();await Promise.all([i,r])},["seeked"],!1,t)}replace(e,t){return this.position(async i=>{e.duration=await Gc(e),i()&&(this.host.media=e,await Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(await Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))},["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=r??(this.seeking?this.wanted:!this.host.paused),this.cancelPlay();const a=this.seeking,s=this.operation();return this.seeking=s,a?.complete.resolve(),a?.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}async runPosition(e,t,i,r){const a=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!a())return;if(this.host.ended=!1,this.host.seeking=!0,Oc(this.host.events,a,["seeking","waiting"]),!a())return;if(r||this.stop(),!a())return;if(await t(a),!a())return;if(this.host.seeking=!1,e.complete.resolve(),Oc(this.host.events,a,i),!a())return;this.seeking=null,s=this.wanted}catch(n){if(!a())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(n),n}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&await this.play()}}const Jc=new WeakMap,Zc=new WeakMap;function el(e){const t=Zc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>e.value??null);Zc.set(e,i);const r=()=>{Zc.get(e)===i&&Zc.delete(e)};return i.then(r,r),i}function tl(e,t,i,r,a){const s=i?Math.max(.06,r/Math.max(1,a)):0;return i&&e{if(this.image===a&&t()){this.cancel();try{i(a)}catch(e){r(e)}}},a.onerror=()=>{this.image===a&&this.cancel()},a.src=e}}class rl{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}async update(e){const t=this.host.videoIterator;if(!t||!this.ready()||!this.current(e)||this.host.isFetching)return;const i={};this.fetching=i,this.host.isFetching=!0;const r=()=>this.current(e)&&this.host.videoIterator===t;try{for(;r();){const e=await el(t);if(!r()||!e)return;const i=this.host.audioClock?.currentTime;if(void 0===i)return;const a=tl(e.timestamp,i,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==a){if("draw"!==a)return void(this.host.nextFrame=e);this.draw(e)}}}catch(a){if(r())throw a}finally{this.fetching===i&&(this.fetching=null,this.host.isFetching=!1)}}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void Oc(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(Oc(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!D(this,w),e=>L(this,P,E).call(this,e,!0),e=>L(this,P,C).call(this,e)))}async preflight(e,t,i){return async function(e,t,i,r,a=()=>!0){if(r?.aborted||!a())return!1;if(!t||"string"!==typeof e||Kc(e))return!0;try{const t=await fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if(r?.aborted||!a())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!(r?.aborted||!a())&&(console.warn("Preflight check failed:",s),!0)}}(e,this.preflightRange,this.events,t,i)}drawPoster(){if(D(this,b)||!this.poster||this.posterDrawn)return;const e=D(this,m);D(this,T).draw(this.poster,()=>L(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,L(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>L(this,P,C).call(this,e))}async stopIterator(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,await function(e){if(!e)return Promise.resolve();const t=Jc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return Jc.set(e,i),i}(e)}clear(){L(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){z(this,m)._++,z(this,p)._++,this.stop(),L(this,P,B).call(this),D(this,T).cancel(),O(this,w,!1),O(this,g,null),O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null}async load(e,t){if(D(this,b))return;this.cancelPending();const i=D(this,m),r=D(this,p);O(this,w,!0);const a=Promise.resolve().then(()=>L(this,P,_).call(this,e,i,r,t));O(this,g,a);try{await a}finally{D(this,g)===a&&O(this,g,null)}}handleNoVideoTrack(){D(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}async resetIterator(e){if(D(this,b))return;const t=D(this,m),i=++z(this,p)._,r=D(this,g);this.stop(),D(this,T).cancel(),O(this,w,!0);try{r&&await r,await L(this,P,R).call(this,e,t,i)}catch(a){if(L(this,P,I).call(this,t)&&D(this,p)===i)throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}}async updateNextFrame(e){await D(this,S).update(e)}render(){D(this,S).render()}start(e){D(this,S).start(e)}stop(){D(this,S).stop()}async seek(e){await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){D(this,b)||(O(this,b,!0),z(this,m)._++,D(this,S).destroy(),D(this,T).cancel(),L(this,P,B).call(this),this.posterDrawn=!1,O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,w=new WeakMap,T=new WeakMap,S=new WeakMap,v=new WeakMap,P=new WeakSet,I=function(e){return!D(this,b)&&D(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){D(this,b)||(L(this,P,B).call(this),D(this,v)?D(this,v).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){D(this,T).cancel(),t&&this.clear(),L(this,P,x).call(this).drawImage(e.canvas,0,0)},_=async function(e,t,i,r){if(L(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:a,videoTrack:s,duration:n}=e;if(this.input=a,this.duration=n,!s)return this.handleNoVideoTrack(),void r?.();const o=null!==s.codec&&await s.canDecode();if(!L(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void r?.();const c=await s.canBeTransparent();if(!L(this,P,I).call(this,t))return;O(this,k,()=>new Fo(s,{poolSize:2,fit:"contain",alpha:c})),this.videoSink=D(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,r?.(),L(this,P,I).call(this,t)&&await L(this,P,R).call(this,0,t,i)}catch(a){if(L(this,P,I).call(this,t))throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}},R=async function(e,t,i){if(!L(this,P,I).call(this,t)||D(this,p)!==i)return;L(this,P,B).call(this),D(this,k)&&this.videoSink===D(this,y)&&(this.videoSink=D(this,k).call(this));const r=this.videoSink;if(!r||!L(this,P,I).call(this,t))return;O(this,y,r);const a=r.canvases(e);this.videoIterator=a;const s=()=>L(this,P,I).call(this,t)&&D(this,p)===i&&this.videoIterator===a,n=await el(a);if(!s())return;const o=await el(a);s()&&(this.nextFrame=o,n?L(this,P,E).call(this,n,!1):this.drawPoster())};class sl{constructor({canvas:e,ctx:t,events:i,option:r={}}){N(this,F),this.events=i,this.option=r,this.audio=new zc(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new al({canvas:e,ctx:t,events:i,timeupdateInterval:r.timeupdateInterval??250,avSyncTolerance:r.avSyncTolerance??.12,dropLateFrames:r.dropLateFrames??!1,poster:r.poster??"",preflightRange:r.preflightRange??!1,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,O(this,F,new Yc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,D(this,F).ended(),this.audio.pause())})}async load(e){if(this.destroyed)return;const t=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),this.loadSession?.cancel(),t!==this.loadSeq||this.destroyed)return;if(this.pause(),t!==this.loadSeq||this.destroyed)return;this.disposeInput();const i=new $c;this.loadSession=i,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,i.defer(()=>this.events.emit("waiting")),i.defer(()=>this.events.emit("loadstart"));const r=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout??0:0;try{await i.wait(this.performLoad(e,t,i),r)}catch(a){if(t!==this.loadSeq)return;const e=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),i.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}}async performLoad(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(await this.video.preflight(e,i.signal,r))||!r())return;const a=Xc(e);if(!a)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(a);const s=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await Gc({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Kc(t);return{input:e,videoTrack:i,audioTrack:r,duration:a,isLive:!Number.isFinite(a)&&Boolean(s&&await s.isLive()),isHls:n,videoMode:n?"auto":"manual",audioMode:n?"auto":"manual"}}(a,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=a,this.media=s;const n=function(e,t){let i=!1,r=!1,a=!1;function s(s){t()&&!a&&("video"===s?i=!0:r=!0,i&&r&&(a=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,Oc(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,n.video),t=r()?this.audio.load(s,n.audio):Promise.resolve();if(await Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,Oc(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){this.loadSession?.disposeInput(),this.input=null,this.media=null}async replaceTracks(e){if(this.media&&!this.destroyed)return D(this,F).replace({...this.media,...e},this.currentTime)}async selectHlsQuality(e){return function(e,t){return qc(e,t,Wc)}(this,e)}async selectHlsAudio(e){return function(e,t){return qc(e,t,Hc)}(this,e)}async getHlsState(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=await async function(e){if(!e?.isHls||!e.input)return null;const[t,i]=await Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[r,a]=await Promise.all([Promise.all(t.map(async(e,t)=>({id:e.id,track:e,index:t,name:await e.getName(),height:await e.getDisplayHeight(),bitrate:await Vc(e)}))),Promise.all(i.map(async(e,t)=>{const i=await e.getName(),r=await e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:await Vc(e)}}))]);return{levels:r,audios:a,currentLevel:e.videoTrack?r.find(t=>t.id===e.videoTrack?.id)??null:null,currentAudio:e.audioTrack?a.find(t=>t.id===e.audioTrack?.id)??null:null,videoMode:e.videoMode??"auto",audioMode:e.audioMode??"auto"}}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}}async play(){return D(this,F).play()}pause(){D(this,F).pause()}async seek(e){return D(this,F).seek(e)}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,D(this,F).invalidate();const e=[];for(const i of[()=>this.loadSession?.cancel(),()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){return this.media?.duration??this.audio.duration??this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}F=new WeakMap;const nl=new WeakMap;function ol(e){let t=nl.get(e);return t||(t={closed:!1,frames:new Set},nl.set(e,t)),t}class cl{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new V,this.engine=new sl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=r.volume??.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:e.option?.url&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=ol(e);if(i.closed)return 0;const r=requestAnimationFrame(a=>{i.frames.delete(r),i.closed||t(a,{presentationTime:e.engine.currentTime,expectedDisplayTime:a+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:a,receiveTime:a,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){ol(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=ol(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,a=r("canvas"),s=a.getContext("2d"),n=new cl({art:t,canvas:a,ctx:s,option:e});t.mediabunny=n;const o={};for(const e in a)"function"===typeof a[e]&&(o[e]=a[e].bind(a));const c=new Set([...Object.getOwnPropertyNames(n),...Object.getOwnPropertyNames(Object.getPrototypeOf(n))]);for(const e of c)"constructor"!==e&&(e in a||Object.defineProperty(a,e,{get(){const t=n[e];return"function"===typeof t?t.bind(n):t},set(t){n[e]=t},configurable:!0,enumerable:!0}));for(const e in o)a[e]=(...t)=>o[e](...t);function l(){const e=t.template?.$player;e&&!t.option.autoSize&&Object.assign(a.style,{width:"100%",height:"100%",objectFit:"contain"})}return t.on("resize",l),t.on("video:loadedmetadata",l),H({art:t,shim:n,option:e}),t.on("destroy",()=>{delete t.mediabunny,n.destroy()}),a}}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,a,s,n,o,c,l,u,h,d,f,m,p,g,k,y,b,w,T,S,v,P,I,x,C,B,E,_,R,F,A=e=>{throw TypeError(e)},M=(e,t,i)=>t.has(e)||A("Cannot "+i),D=(e,t,i)=>(M(e,t,"read from private field"),i?i.call(e):t.get(e)),N=(e,t,i)=>t.has(e)?A("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),O=(e,t,i,r)=>(M(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),L=(e,t,i)=>(M(e,t,"access private method"),i),z=(e,t,i,r)=>({set _(r){O(e,t,r,i)},get _(){return D(e,t,r)}});function U(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function q(e,t,i){const r={control:!1,setting:!1};let a=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function n(){a=null,U([()=>s("control"),()=>s("setting")])}return{update:function(o,c,l,u){if(!o)return void n();a=o;const h=()=>a===o&&l(),d=async e=>h()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html;c.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:d})):s("control"),h()&&(c.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:d})):s("setting"))},clear:n}}function W(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function H({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,a=0,s=0;const n=q(e,"mediabunny-quality",''),o=q(e,"mediabunny-audio",''),c=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;async function l(){if(r||t.engine.destroyed)return;const e=++a,s=t.engine.loadSeq,l=()=>e===a&&c(s);try{const e=await t.getM3u8State();if(!l())return;const r=i.m3u8?.quality||{},a=function(e,t,i){if(!t.control&&!t.setting||!e?.levels.length)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||`${e.height}P`),s=e.currentLevel?a(e.currentLevel):r,n=[];for(const l of e.levels){if(!i())return null;n.push({html:a(l),value:l.id,default:e.currentLevel?.id===l.id})}const o=new Map(e.levels.map(e=>[e.id,e.height])),c=W(n).sort((e,t)=>("auto"===t.value?0:o.get(t.value)||0)-("auto"===e.value?0:o.get(e.value)||0));return c.push({html:r,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:s,selector:c}}(e,r,l);if(!l())return;if(n.update(a,r,()=>c(s),(e,t)=>u("quality",e,t)),!l())return;const h=i.m3u8?.audio||{},d=function(e,t,i){if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const r=t.auto||"Auto",a=t.getName||(e=>e.name||e.lang||e.language),s=e.currentAudio?a(e.currentAudio):r,n=[];for(const c of e.audios){if(!i())return null;n.push({html:a(c),value:c.id,default:e.currentAudio?.id===c.id})}const o=W(n);return o.push({html:r,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:s,selector:o}}(e,h,l);l()&&o.update(d,h,()=>c(s),(e,t)=>u("audio",e,t))}catch(h){if(l())throw h}}async function u(i,r,n){const o=++s,u=t.engine.loadSeq;a++;const d=()=>o===s&&c(u);try{"quality"===i?await t.switchM3u8Quality(r.value):await t.switchM3u8Audio(r.value),d()&&(await l(),d()&&(e.notice.show=`${n}: ${r.html}`))}catch(f){if(d()&&(await h(),d()))throw f}return r.html}function h(){return l().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function d(){a++,s++;try{U([n.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}function f(){if(!r){r=!0,d();try{U([()=>e.off("video:loadedmetadata",h),()=>e.off("restart",h),()=>e.off("video:loadstart",d),()=>e.off("video:error",d),()=>e.off("destroy",f)])}catch(t){console.warn("MediaBunny HLS listener cleanup:",t)}}}try{e.on("video:loadedmetadata",h),e.on("restart",h),e.on("video:loadstart",d),e.on("video:error",d),e.on("destroy",f)}catch(m){throw f(),m}return{update:l,destroy:f}}class V{constructor(){N(this,e,!1),this.listeners=new Map}addEventListener(t,i){D(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),this.listeners.get(t)?.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){if(D(this,e))return;const r=Object.assign(new Event(t),{detail:i});this.listeners.get(t)?.forEach(t=>{D(this,e)||t(r)})}destroy(){O(this,e,!0),this.listeners.clear()}}function j(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const K=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},X=e=>e&&e[e.length-1],$=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-2**r)},Q=e=>{const t=$(e);return 0===(1&t)?-(t>>1):t+1>>1},Y=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),J=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),Z=new TextDecoder,ee=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),te={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ie=ee(te),re={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},ae=ee(re),se={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},ne=ee(se),oe=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,ce={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},le=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class ue{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}async acquire(){let e;const t=new Promise(t=>{let i=!1;e=()=>{i||(t(),this.pending--,i=!0)}}),i=this.currentPromise;return this.currentPromise=t,this.pending++,await i,e}}const he=/^[0-9a-fA-F]+$/,de=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),fe=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,me=(e,t,i)=>{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+a>>1,o=i(e[n]);o===t?(s=n,a=n-1):o{let r=0,a=e.length-1,s=-1;for(;r<=a;){const n=r+(a-r+1)/2|0;i(e[n])<=t?(s=n,r=n+1):a=n-1}return s},ge=(e,t,i)=>{const r=pe(e,i(t),i);e.splice(r+1,0,t)},ke=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},ye=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},be=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},we=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Te=e=>{throw new Error(`Unexpected value: ${e}`)},Se=(e,t,i)=>{const r=e.getUint8(t),a=e.getUint8(t+1),s=e.getUint8(t+2);return i?r|a<<8|s<<16:r<<16|a<<8|s},ve=(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)},Pe=(e,t)=>({async next(){const i=await e.next();return i.done?{value:void 0,done:!0}:{value:t(i.value),done:!1}},return:()=>e.return(),throw:t=>e.throw(t),[Symbol.asyncIterator](){return this}}),Ie=(e,t,i)=>Math.max(t,Math.min(i,e)),xe="und",Ce=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Be=(e,t)=>Math.round(e/t)*t,Ee=(e,t)=>Math.round(e*t)/t,_e=(e,t)=>Math.floor(e/t)*t,Re=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},Fe=/^[a-z]{3}$/,Ae=e=>Fe.test(e),Me=1e6*(1+Number.EPSILON),De=(e,t)=>{const i={...e,...t};if(e.headers||t.headers){const r=e.headers?Ne(e.headers):{},a=t.headers?Ne(t.headers):{},s={...r};Object.entries(a).forEach(([e,t])=>{const i=Object.keys(s).find(t=>t.toLowerCase()===e.toLowerCase());i&&delete s[i],s[e]=t}),i.headers=s}return i},Ne=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},Oe=async(e,t,i,r,a)=>{let s=0;for(;;)try{return await e(t,i)}catch(n){if(a())throw n;s++;const e=r(s,n,t);if(null===e)throw n;if(ct._error("Retrying failed fetch. Error:",n),!Number.isFinite(e)||e<0)throw new TypeError("Retry delay must be a non-negative finite number.");if(e>0&&await at(1e3*e),a())throw n}};class Le{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let ze=null;const Ue=()=>null!==ze?ze:ze=!("undefined"===typeof navigator||!(navigator.vendor?.match(/apple/i)||/AppleWebKit/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)||/\b(iPad|iPhone|iPod)\b/.test(navigator.userAgent)));let qe=null;const We=()=>null!==qe?qe:qe="undefined"!==typeof navigator&&navigator.userAgent?.includes("Firefox");let He=null;const Ve=()=>null!==He?He:He=!("undefined"===typeof navigator||!navigator.vendor?.includes("Google Inc")&&!/Chrome/.test(navigator.userAgent)),je=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,Ke=(async()=>{})().constructor,Xe=e=>e instanceof Ke||e instanceof Promise||"function"===typeof e?.then,$e=(e,t)=>-1!==e?e:t,Ge=(e,t,i,r)=>e<=r&&i<=t,Qe=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{Symbol.dispose??(Symbol.dispose=Symbol("Symbol.dispose"))},Je=e=>"number"===typeof e&&!Number.isNaN(e),Ze=(e,t)=>{if(t.includes("://"))return t;if(e.includes("://")){const t=e.indexOf("?");-1!==t&&(e=e.slice(0,t))}let i;if(t.startsWith("/")){const r=e.indexOf("://");if(-1===r)i=t;else{const a=e.indexOf("/",r+3);i=-1===a?e+t:e.slice(0,a)+t}}else{const r=e.lastIndexOf("/");i=-1===r?t:e.slice(0,r+1)+t}let r="";const a=i.indexOf("://");if(-1!==a){const e=i.indexOf("/",a+3);-1!==e&&(r=i.slice(0,e),i=i.slice(e))}const s=i.split("/"),n=[];for(const o of s)".."===o?n.pop():"."!==o&&n.push(o);return r+n.join("/")},et=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let a=0;a{j(Number.isInteger(e.num)),j(Number.isInteger(e.den)),j(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}},rt=(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.`)},at=e=>new Promise(t=>setTimeout(t,e));class st{constructor(){this._listeners=new Map}on(e,t,i){this._listeners.has(e)||this._listeners.set(e,new Set);const r={fn:t,once:i?.once??!1};return this._listeners.get(e).add(r),()=>{this._listeners.get(e)?.delete(r)}}_emit(...e){const[t,i]=e,r=this._listeners.get(t);if(r)for(const s of r){try{s.fn(i)}catch(a){console.error(a)}s.once&&r.delete(s)}}}var nt,ot;(ot=nt||(nt={}))[ot.Silent=0]="Silent",ot[ot.Errors=1]="Errors",ot[ot.Warnings=2]="Warnings",ot[ot.Info=3]="Info";class ct{constructor(){}static get level(){return ct._level}static set level(e){if(e!==nt.Silent&&e!==nt.Errors&&e!==nt.Warnings&&e!==nt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");ct._level=e}static get _emitter(){return ct._emitterInstance??(ct._emitterInstance=new st)}static on(e,t,i){return ct._emitter.on(e,t,i)}static _error(...e){ct._emitter._emit("error",e),ct._level>=nt.Errors&&console.error(...e)}static _warn(...e){ct._emitter._emit("warn",e),ct._level>=nt.Warnings&&console.warn(...e)}static _info(...e){ct._emitter._emit("info",e),ct._level>=nt.Info&&console.info(...e)}}ct._level=nt.Info,ct._emitterInstance=null;class lt{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 ut{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 ht={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class dt{constructor(e){this.bytes=e,this.pos=0}seekToByte(e){this.pos=8*e}readBit(){const e=Math.floor(this.pos/8),t=this.bytes[e]??0,i=7-(7&this.pos),r=(t&1<>i;return this.pos++,r}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}readAlignedByte(){if(this.pos%8!==0)throw new Error("Bitstream is not byte-aligned.");const e=this.pos/8,t=this.bytes[e]??0;return this.pos+=8,t}skipBits(e){this.pos+=e}getBitsLeft(){return 8*this.bytes.length-this.pos}clone(){const e=new dt(this.bytes);return e.pos=this.pos,e}}const ft=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],mt=[-1,1,2,3,4,5,6,8],pt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new dt(e),i=gt(t),{frequencyIndex:r,sampleRate:a}=kt(t),s=t.readBits(4);let n=null;s>=1&&s<=7&&(n=mt[s]);let o=i,c=!1,l=a;if(5===i||29===i)c=29===i,l=kt(t).sampleRate,o=gt(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===gt(t)&&t.readBits(1)&&(l=kt(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(c=!!t.readBits(1)));break}t.pos=e+1}return null!==n&&n>1&&(c=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:l,outputNumberOfChannels:c&&1===n?2:n}},gt=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},kt=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let a=0;t+3i&&(yield{offset:i,length:t-i}),i=t+a,t=i):t++}-1!==i&&i{if(t.description){const i=3&Y(t.description)[4];return It(e,i+1)}return Pt(e)},Ct=e=>31&e,Bt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+Et.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const a of e)i.set(Et,r),r+=Et.byteLength,i.set(a,r),r+=a.byteLength;return i},Rt=(e,t)=>{const i=e.reduce((e,i)=>e+t+i.byteLength,0),r=new Uint8Array(i);let a=0;for(const s of e){const e=new DataView(r.buffer,r.byteOffset,r.byteLength);switch(t){case 1:e.setUint8(a,s.byteLength);break;case 2:e.setUint16(a,s.byteLength,!1);break;case 3:ve(e,a,s.byteLength);break;case 4:e.setUint32(a,s.byteLength,!1)}a+=t,r.set(s,a),a+=s.byteLength}return r},Ft=e=>{try{const t=[],i=[],r=[];for(const o of Pt(e)){const a=e.subarray(o.offset,o.offset+o.length),s=Ct(a[0]);s===wt.SPS?t.push(a):s===wt.PPS?i.push(a):s===wt.SPS_EXT&&r.push(a)}if(0===t.length)return null;if(0===i.length)return null;const a=t[0],s=Nt(a);j(null!==s);const n=100===s.profileIdc||110===s.profileIdc||122===s.profileIdc||144===s.profileIdc;return{configurationVersion:1,avcProfileIndication:s.profileIdc,profileCompatibility:s.constraintFlags,avcLevelIndication:s.levelIdc,lengthSizeMinusOne:3,sequenceParameterSets:t,pictureParameterSets:i,chromaFormat:n?s.chromaFormatIdc:null,bitDepthLumaMinus8:n?s.bitDepthLumaMinus8:null,bitDepthChromaMinus8:n?s.bitDepthChromaMinus8:null,sequenceParameterSetExt:n?r:null}}catch(t){return ct._error("Error building AVC Decoder Configuration Record:",t),null}},At=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=t.getUint8(i++),n=t.getUint8(i++),o=3&t.getUint8(i++),c=31&t.getUint8(i++),l=[];for(let f=0;f{try{const t=Bt(e),i=new dt(t);i.skipBits(1),i.skipBits(2);if(7!==i.readBits(5))return null;const r=i.readAlignedByte(),a=i.readAlignedByte(),s=i.readAlignedByte();$(i);let n=1,o=0,c=0,l=0;if(100===r||110===r||122===r||244===r||44===r||83===r||86===r||118===r||128===r){n=$(i),3===n&&(l=i.readBits(1)),o=$(i),c=$(i),i.skipBits(1);if(i.readBits(1))for(let e=0;e<(3!==n?8:12);e++){if(i.readBits(1)){const t=e<6?16:64;let r=8,a=8;for(let e=0;ee.level>=s)??X(Ai),r=Math.min(Math.floor(i.maxDpbMbs/(e*t)),16);v=r,P=r}else v=0,P=0}return j(null!==P),{emulationUnpreventedBytes:t,profileIdc:r,constraintFlags:a,levelIdc:s,frameMbsOnlyFlag:k,chromaFormatIdc:n,bitDepthLumaMinus8:o,bitDepthChromaMinus8:c,codedWidth:f,codedHeight:m,displayWidth:p,displayHeight:g,pixelAspectRatio:S,colourPrimaries:y,matrixCoefficients:w,transferCharacteristics:b,fullRangeFlag:T,numReorderFrames:v,maxDecFrameBuffering:P,vuiParametersFlagBitOffset:C,bitstreamRestrictionFlagBitOffset:I,bitstreamRestrictionFlag:x}}catch(t){return ct._error("Error parsing AVC SPS:",t),null}},Ot=e=>{const t=$(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)$(e),$(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},Lt=e=>{j(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new dt(e.emulationUnpreventedBytes),r=new dt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(j(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),G(r,2),G(r,1),G(r,16),G(r,16),G(r,e.numReorderFrames),G(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const a=r.pos/8;return j(Number.isInteger(a)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,a))},zt=(e,t)=>{if(t.description){const i=3&Y(t.description)[21];return It(e,i+1)}return Pt(e)},Ut=e=>e>>1&63,qt=e=>{try{const t=new dt(Bt(e));t.skipBits(16),t.readBits(4);const i=t.readBits(3),r=t.readBits(1),{general_profile_space:a,general_tier_flag:s,general_profile_idc:n,general_profile_compatibility_flags:o,general_constraint_indicator_flags:c,general_level_idc:l}=Ht(t,i);$(t);const u=$(t);let h=0;3===u&&(h=t.readBits(1));const d=$(t),f=$(t);let m=d,p=f;if(t.readBits(1)){const e=$(t),i=$(t),r=$(t),a=$(t);let s=1,n=1;const o=0===h?u:0;1===o?(s=2,n=2):2===o&&(s=2,n=1),m-=(e+i)*s,p-=(r+a)*n}const g=$(t),k=$(t);$(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)$(t),b=$(t),$(t);$(t),$(t),$(t),$(t),$(t),$(t),t.readBits(1)&&t.readBits(1)&&Vt(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),$(t),$(t),t.skipBits(1));const w=$(t);if(jt(t,w),t.readBits(1)){const e=$(t);for(let i=0;i{try{const t=[],i=[],r=[],a=[];for(const c of Pt(e)){const s=e.subarray(c.offset,c.offset+c.length),n=Ut(s[0]);n===St.VPS_NUT?t.push(s):n===St.SPS_NUT?i.push(s):n===St.PPS_NUT?r.push(s):n!==St.PREFIX_SEI_NUT&&n!==St.SUFFIX_SEI_NUT||a.push(s)}if(0===i.length||0===r.length)return null;const s=qt(i[0]);if(!s)return null;let n=0;if(r.length>0){const e=r[0],t=new dt(Bt(e));t.skipBits(16),$(t),$(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),$(t),$(t),Q(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&$(t),Q(t),Q(t),t.skipBits(1),t.skipBits(1),t.skipBits(1),t.skipBits(1);const i=t.readBits(1),a=t.readBits(1);n=i||a?i&&!a?2:!i&&a?3:0:0}const o=[...t.length?[{arrayCompleteness:1,nalUnitType: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}]:[],...a.length?[{arrayCompleteness:1,nalUnitType:Ut(a[0][0]),nalUnits:a}]:[]];return{configurationVersion:1,generalProfileSpace:s.generalProfileSpace,generalTierFlag:s.generalTierFlag,generalProfileIdc:s.generalProfileIdc,generalProfileCompatibilityFlags:s.generalProfileCompatibilityFlags,generalConstraintIndicatorFlags:s.generalConstraintIndicatorFlags,generalLevelIdc:s.generalLevelIdc,minSpatialSegmentationIdc:s.minSpatialSegmentationIdc,parallelismType:n,chromaFormatIdc:s.chromaFormatIdc,bitDepthLumaMinus8:s.bitDepthLumaMinus8,bitDepthChromaMinus8:s.bitDepthChromaMinus8,avgFrameRate:0,constantFrameRate:0,numTemporalLayers:s.spsMaxSubLayersMinus1+1,temporalIdNested:s.spsTemporalIdNestingFlag,lengthSizeMinusOne:3,arrays:o}}catch(t){return ct._error("Error building HEVC Decoder Configuration Record:",t),null}},Ht=(e,t)=>{const i=e.readBits(2),r=e.readBits(1),a=e.readBits(5);let s=0;for(let u=0;u<32;u++)s=s<<1|e.readBits(1);const n=new Uint8Array(6);for(let u=0;u<6;u++)n[u]=e.readBits(8);const o=e.readBits(8),c=[],l=[];for(let u=0;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&Q(e);for(let t=0;t{const i=[];for(let r=0;r{let a=0,s=0,n=0;if(0!==t&&(s=e.readBits(1)),s){if(t===i){n=t-($(e)+1)}else n=t-1;e.readBits(1),$(e);const s=r[n]??0;for(let t=0;t<=s;t++){e.readBits(1)||e.readBits(1)}a=r[n]}else{const t=$(e),i=$(e);for(let r=0;r{let i=2,r=2,a=2,s=0,n=0,o={num:1,den:1};if(e.readBits(1)){const t=e.readBits(8);if(255===t)o={num:e.readBits(16),den:e.readBits(16)};else{const e=Dt[t];e&&(o=e)}}return e.readBits(1)&&e.readBits(1),e.readBits(1)&&(e.readBits(3),s=e.readBits(1),e.readBits(1)&&(i=e.readBits(8),r=e.readBits(8),a=e.readBits(8))),e.readBits(1)&&($(e),$(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&($(e),$(e),$(e),$(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&$(e),e.readBits(1)&&$t(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),n=$(e),$(e),$(e),$(e),$(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:a,fullRangeFlag:s,minSpatialSegmentationIdc:n}},$t=(e,t,i)=>{let r=!1,a=!1,s=!1;r=1===e.readBits(1),a=1===e.readBits(1),(r||a)&&(s=1===e.readBits(1),s&&(e.readBits(8),e.readBits(5),e.readBits(1),e.readBits(5)),e.readBits(4),e.readBits(4),s&&e.readBits(4),e.readBits(5),e.readBits(5),e.readBits(5));for(let n=0;n<=i;n++){let t=!0;1===e.readBits(1)||(t=1===e.readBits(1));let i=!1;t?$(e):i=1===e.readBits(1);let n=1;if(!i){n=$(e)+1}r&&Gt(e,n,s),a&&Gt(e,n,s)}},Gt=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=Qt.audAllowed;for(const s of zt(e,t)){if(r===Qt.noMoreDataAllowed){i.add(s.offset);continue}const t=Ut(e[s.offset]);if(r===Qt.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let a=!1;35===t?r>Qt.audAllowed?a=!0:r=Qt.beforeFirstVcl:t<=31?r>Qt.afterFirstVcl?a=!0:r=Qt.afterFirstVcl:36===t?r!==Qt.afterFirstVcl?a=!0:r=Qt.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>Qt.beforeFirstVcl?a=!0:r=Qt.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&Y(t.description)[21];return Rt(e,i+1)}return _t(e)})(a,t)},Zt={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},ei=e=>{const t=new dt(e);if(2!==t.readBits(2))return null;const i=t.readBits(1),r=(t.readBits(1)<<1)+i;3===r&&t.skipBits(1);if(1===t.readBits(1))return null;if(0!==t.readBits(1))return null;t.skipBits(2);if(4817730!==t.readBits(24))return null;let a=8;if(r>=2){a=t.readBits(1)?12:10}const s=t.readBits(3);let n=0,o=0;if(7!==s){if(o=t.readBits(1),1===r||3===r){const e=t.readBits(1),i=t.readBits(1);n=e||i?e&&!i?2:1:3,t.skipBits(1)}else n=1}else n=3,o=1;const c=(t.readBits(16)+1)*(t.readBits(16)+1);let l=X(Mi).level;for(const h of Mi)if(c<=h.maxPictureSize){l=h.level;break}const u=Zt[s];return{profile:r,level:l,bitDepth:a,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:u?.colourPrimaries??2,transferCharacteristics:u?.transferCharacteristics??2,matrixCoefficients:u?.matrixCoefficients??2}},ti=function*(e){const t=new dt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*2**(7*i),!(128&r))break;if(7===i&&128&r)return null}return e>2**32-1?null:e};for(;t.getBitsLeft()>=8;){t.skipBits(1);const r=t.readBits(4),a=t.readBits(1),s=t.readBits(1);let n;if(t.skipBits(1),a&&t.skipBits(8),s){const e=i();if(null===e)return;n=e}else n=Math.floor(t.getBitsLeft()/8);j(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+n)},t.skipBits(8*n)}},ii=e=>{for(const{type:t,data:i}of ti(e)){if(1!==t)continue;const e=new dt(i),r=e.readBits(3);e.readBits(1);const a=e.readBits(1);let s=0,n=0,o=0;if(a)s=e.readBits(5);else{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let a=0;a<=r;a++){e.skipBits(12);const r=e.readBits(5);if(0===a&&(s=r),r>7){const t=e.readBits(1);0===a&&(n=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const c=e.readBits(4),l=e.readBits(4),u=c+1;e.skipBits(u);const h=l+1;e.skipBits(h);let d=0;if(d=a?0:e.readBits(1),d&&(e.skipBits(4),e.skipBits(3)),e.skipBits(1),e.skipBits(1),e.skipBits(1),!a){e.skipBits(1),e.skipBits(1),e.skipBits(1),e.skipBits(1);const t=e.readBits(1);t&&(e.skipBits(1),e.skipBits(1));let i=0;if(i=e.readBits(1)?2:e.readBits(1),i>0){e.readBits(1)||e.skipBits(1)}t&&e.skipBits(3)}e.skipBits(1),e.skipBits(1),e.skipBits(1);const f=e.readBits(1);let m=8;if(2===r&&f){m=e.readBits(1)?12:10}else r<=2&&(m=f?10:8);let p=0;1!==r&&(p=e.readBits(1));let g=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,w=1,T=1,S=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,w=0,T=0):(b=e.readBits(1),0===r?(w=1,T=1):1===r?(w=0,T=0):12===m?(w=e.readBits(1),T=w?e.readBits(1):0):(w=1,T=0),w&&T&&(S=e.readBits(2))),{profile:r,level:s,tier:n,bitDepth:m,monochrome:p,chromaSubsamplingX:w,chromaSubsamplingY:T,chromaSamplePosition:S,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},ri=e=>{if(e.length<36)return null;const t=J(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},ai=[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],si=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;u97;)if(1===r.readBits(1)){a=r.pos;break}if(0===a)throw new Error("Invalid Setup header: framing bit not found.");let s=0,n=!1,o=0;for(;r.getBitsLeft()>=97;){const e=r.pos,t=r.readBits(8),i=r.readBits(16),a=r.readBits(16);if(t>63||0!==i||0!==a){r.pos=e;break}if(r.skipBits(1),s++,s>64)break;r.clone().readBits(6)+1===s&&(n=!0,o=s)}if(!n)throw new Error("Invalid Setup header: mode header not found.");if(o>63)throw new Error(`Unsupported mode count: ${o}.`);const c=o;r.pos=0,r.skipBits(a);const l=Array(c).fill(0);for(let u=c-1;u>=0;u--)r.skipBits(40),l[u]=r.readBits(1);return{modeBlockflags:l}},ni=(e,t,i)=>{switch(e){case"avc":for(const e of xt(i,t)){const t=i[e.offset],r=Ct(t);if(r>=wt.NON_IDR_SLICE&&r<=wt.SLICE_DPC)return"delta";if(r===wt.IDR)return"key";if(r===wt.SEI&&!Ve()){const t=i.subarray(e.offset,e.offset+e.length),r=Bt(t);let a=1;do{let e=0;for(;;){const t=r[a++];if(void 0===t)break;if(e+=t,t<255)break}let t=0;for(;;){const e=r[a++];if(void 0===e)break;if(t+=e,e<255)break}if(e===6){const e=new dt(r);e.pos=8*a;const t=$(e),i=e.readBits(1);if(0===t&&1===i)return"key"}a+=t}while(a{var i,r;const a=J(e);let s=0;const n=a.getUint32(s,!0);s+=4;const o=Z.decode(e.subarray(s,s+n));s+=n,n>0&&(t.raw??(t.raw={}),(i=t.raw).vendor??(i.vendor=o));const c=a.getUint32(s,!0);s+=4;for(let l=0;l0&&(t.trackNumber??(t.trackNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.tracksTotal??(t.tracksTotal=r))}break;case"TRACKTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.tracksTotal??(t.tracksTotal=e))}break;case"DISCNUMBER":{const e=l.split("/"),i=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(t.discNumber??(t.discNumber=i)),r&&Number.isInteger(r)&&r>0&&(t.discsTotal??(t.discsTotal=r))}break;case"DISCTOTAL":{const e=Number.parseInt(l,10);Number.isInteger(e)&&e>0&&(t.discsTotal??(t.discsTotal=e))}break;case"DATE":{const e=new Date(l);Number.isNaN(e.getTime())||(t.date??(t.date=e))}break;case"GENRE":t.genre??(t.genre=l);break;case"METADATA_BLOCK_PICTURE":{const e=Qe(l),i=J(e),r=i.getUint32(0,!1),a=i.getUint32(4,!1),s=String.fromCharCode(...e.subarray(8,8+a)),n=i.getUint32(8+a,!1),o=Z.decode(e.subarray(12+a,12+a+n)),c=i.getUint32(a+n+28),u=e.subarray(a+n+32,a+n+32+c);t.images??(t.images=[]),t.images.push({data:u,mimeType:s,kind:3===r?"coverFront":4===r?"coverBack":"unknown",name:void 0,description:o||void 0})}}}},ui=[2,1,2,3,3,4,4,5],hi=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16),t.skipBits(16);const i=t.readBits(2);if(3===i)return null;const r=t.readBits(6),a=t.readBits(5);if(a>8)return null;const s=t.readBits(3),n=t.readBits(3);0!==(1&n)&&1!==n&&t.skipBits(2),0!==(4&n)&&t.skipBits(2),2===n&&t.skipBits(2);return{fscod:i,bsid:a,bsmod:s,acmod:n,lfeon:t.readBits(1),bitRateCode:Math.floor(r/2)}},di=[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],fi=[1,2,3,6],mi=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new dt(e);t.skipBits(16);const i=t.readBits(2);if(t.skipBits(3),0!==i&&2!==i)return null;const r=t.readBits(11),a=t.readBits(2);let s,n=0;3===a?(n=t.readBits(2),s=3):s=t.readBits(2);const o=t.readBits(3),c=t.readBits(1),l=t.readBits(5);if(l<11||l>16)return null;const u=fi[s];let h;h=a<3?yt[a]/1e3:bt[n]/1e3;return{dataRate:Math.round((r+1)*h/(16*u)),substreams:[{fscod:a,fscod2:n,bsid:l,bsmod:0,acmod:o,lfeon:c,numDepSub:0,chanLoc:0}]}},pi=e=>{const t=e.substreams[0];return j(t),t.fscod<3?yt[t.fscod]:null!==t.fscod2&&t.fscod2<3?bt[t.fscod2]:null},gi=e=>{const t=e.substreams[0];j(t);let i=ui[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},ki=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],yi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],bi=[16,16,20,20,0,24,24,0],wi=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Ti=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Si=[32e3,44100,48e3,0],vi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Pi=[512,1024,2048,4096],Ii=e=>{const t=Ci(e),i=J(e);let r=t?4*Math.ceil(t.frameSize/4):0,a=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Bi(e.subarray(r));if(!t)break;a??(a=t),r+=t.frameSize}if(t)return{frameSize:a?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==a};if(!a?.asset)return null;const{asset:s}=a;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},xi=e=>{const t=Ii(e);return t?.core?t.hasExtensions?"dtsh":"dtsc":null},Ci=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new dt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const a=t.readBits(14)+1;if(a<96)return null;const s=t.readBits(6);if(s>=wi.length)return null;const n=ki[t.readBits(4)];if(0===n)return null;const o=yi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const c=t.readBits(2);if(3===c)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const l=bi[t.readBits(3)];if(0===l)return null;const u=0!==c;return{frameSize:a,sampleRate:n,numberOfChannels:wi[s]+(u?1:0),sampleCount:32*r,channelLayout:Ti[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:l}},Bi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new dt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),a=8+4*r,s=16+4*r;t.skipBits(a);const n=t.readBits(s)+1,o={frameSize:n,asset:null};if(!t.readBits(1))return o;const c=Si[t.readBits(2)],l=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,h=t.readBits(3)+1,d=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===c||t.getBitsLeft()<0?o:{frameSize:n,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(l*m/c),channelLayout:g,pcmResolution:f}}},Ei=e=>Re(e)+Re(44646&e),_i=["avc","hevc","vp9","av1","vp8","prores"],Ri=["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"],Fi=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Ri],Ai=[{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}],Mi=[{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}],Di=".01.01.01.01.00",Ni=".0.110.01.01.01.0",Oi=["ap4x","ap4h","apch","apcn","apcs","apco"],Li=["dtsc","dtsh","dtsl","dtse"],zi=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:a,hevcCodecInfo:s,vp9CodecInfo:n,av1CodecInfo:o,proresFormat:c}=e;if("avc"===t){if(j(null!==e.avcType),a){const t=new Uint8Array([a.avcProfileIndication,a.profileCompatibility,a.avcLevelIndication]);return`avc${e.avcType}.${de(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}.${de(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,a,n,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=fe(s.generalProfileCompatibilityFlags),a=s.generalTierFlag,n=s.generalLevelIdc,o=[...s.generalConstraintIndicatorFlags];else{if(!i||i.byteLength<23)throw new TypeError("HEVC decoder description is not provided or is not at least 23 bytes long.");const s=J(i),c=s.getUint8(1);e=c>>6&3,t=31&c,r=fe(s.getUint32(2)),a=c>>5&1,n=s.getUint8(12),o=[];for(let e=0;e<6;e++)o.push(s.getUint8(6+e))}let c="hev1.";for(c+=["","A","B","C"][e]+t,c+=".",c+=r.toString(16).toUpperCase(),c+=".",c+=0===a?"L":"H",c+=n;o.length>0&&0===o[o.length-1];)o.pop();return o.length>0&&(c+=".",c+=o.map(e=>e.toString(16).toUpperCase()).join(".")),c}if("vp8"===t)return"vp8";if("vp9"===t){if(!n){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`vp09.00.${i.toString().padStart(2,"0")}.08`}let t=`vp09.${n.profile.toString().padStart(2,"0")}.${n.level.toString().padStart(2,"0")}.${n.bitDepth.toString().padStart(2,"0")}.${n.chromaSubsampling.toString().padStart(2,"0")}`;return t+=`.${n.colourPrimaries.toString().padStart(2,"0")}.${n.transferCharacteristics.toString().padStart(2,"0")}.${n.matrixCoefficients.toString().padStart(2,"0")}.${n.videoFullRangeFlag.toString().padStart(2,"0")}`,t.endsWith(Di)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=X(Mi).level;for(const e of Mi)if(t<=e.maxPictureSize){i=e.level;break}return`av01.0.${i.toString().padStart(2,"0")}M.08`}const t=o.profile,i=o.level.toString().padStart(2,"0"),a=o.tier?"H":"M",s=o.bitDepth.toString().padStart(2,"0"),n=o.monochrome?"1":"0",c=100*o.chromaSubsamplingX+10*o.chromaSubsamplingY+1*(o.chromaSubsamplingX&&o.chromaSubsamplingY?o.chromaSamplePosition:0),l=r?.primaries?te[r.primaries]:1,u=r?.transfer?re[r.transfer]:1,h=r?.matrix?se[r.matrix]:1,d=r?.fullRange?1:0;let f=`av01.${t}.${i}${a}.${s}`;return f+=`.${n}.${c.toString().padStart(3,"0")}`,f+=`.${l.toString().padStart(2,"0")}`,f+=`.${u.toString().padStart(2,"0")}`,f+=`.${h.toString().padStart(2,"0")}`,f+=`.${d}`,f.endsWith(Ni)&&(f=f.slice(0,-17)),f}if("prores"===t)return c??"apch";throw null!==t&&Te(t),new TypeError(`Unhandled codec '${t}'.`)},Ui=e=>{switch(e.codec){case"avc":{let t=e.avcCodecInfo?.sequenceParameterSets[0];if(!t&&e.codecDescription&&(t=Mt(e.codecDescription)?.sequenceParameterSets[0]),t){const e=Nt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=e.hevcCodecInfo?.arrays.find(e=>e.nalUnitType===St.SPS_NUT)?.nalUnits[0];if(!t&&e.codecDescription&&(t=(e=>{try{const t=J(e);let i=0;const r=t.getUint8(i++),a=t.getUint8(i++),s=a>>6&3,n=a>>5&1,o=31&a,c=t.getUint32(i,!1);i+=4;const l=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),h=(15&t.getUint8(i++))<<8|t.getUint8(i++),d=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,w=k>>2&1,T=3&k,S=t.getUint8(i++),v=[];for(let P=0;P>7&1,s=63&r,n=t.getUint16(i,!1);i+=2;const o=[];for(let c=0;ce.nalUnitType===St.SPS_NUT)?.nalUnits[0]),t){const e=qt(t);if(e)return{primaries:ie[e.colourPrimaries],transfer:ae[e.transferCharacteristics],matrix:ne[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ie[e.vp9CodecInfo.colourPrimaries],transfer:ae[e.vp9CodecInfo.transferCharacteristics],matrix:ne[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ie[e.av1CodecInfo.colourPrimaries],transfer:ae[e.av1CodecInfo.transferCharacteristics],matrix:ne[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ie[e.proresCodecInfo.colourPrimaries],transfer:ae[e.proresCodecInfo.transferCharacteristics],matrix:ne[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},qi=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:a}=e;if("aac"===t){if(!r)throw new TypeError("AAC codec info must be provided.");if(r.isMpeg2)return"mp4a.67";{let e;if(null!==r.objectType)e=r.objectType;else{e=pt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return a??"dtsc";if(t&&Ri.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},Wi=48e3,Hi=/^pcm-([usf])(\d+)(be)?$/,Vi=e=>{if(j(Ri.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=Hi.exec(e);let i;j(t),i="u"===t[1]?"unsigned":"s"===t[1]?"signed":"float";return{dataType:i,sampleSize:Number(t[2])/8,littleEndian:"be"!==t[3],silentValue:"pcm-u8"===e?128:0}},ji=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":Oi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":Li.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":Hi.test(e)?e:"webvtt"===e?"webvtt":null,Ki=[44100,48e3,32e3],Xi=[-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],$i=1483304551,Gi=1231971951,Qi=(e,t)=>3===e?3===t?21:36:3===t?13:21,Yi=(e,t)=>{const i=e>>>24,r=e>>>16&255,a=e>>>8&255,s=255&e;if(255!==i&&255!==r&&255!==a&&255!==s)return{header:null,bytesAdvanced:4};if(255!==i)return{header:null,bytesAdvanced:1};if(224!==(224&r))return{header:null,bytesAdvanced:1};let n=0,o=0;16&r?n=8&r?0:1:(n=1,o=1);const c=r>>3&3,l=r>>1&3,u=(a>>2&3)%3,h=s>>6&3,d=s>>4&3,f=s>>3&1,m=s>>2&1,p=3&s,g=Xi[16*n*4+16*l+(a>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=Ki[u]>>n+o,b=((e,t,i,r,a)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var Zi,er;(er=Zi||(Zi={}))[er.FrameCount=1]="FrameCount",er[er.FileSize=2]="FileSize",er[er.Toc=4]="Toc";const tr=e=>3===e?1:2;class ir{constructor(e){this.input=e}dispose(){}}const rr=new Uint8Array(0);class ar{constructor(e,t,i,r,a=-1,s,n){if(this.data=e,this.type=t,this.timestamp=i,this.duration=r,this.sequenceNumber=a,e===rr&&void 0===s)throw new Error("Internal error: byteLength must be explicitly provided when constructing metadata-only packets.");if(void 0===s&&(s=e.byteLength),!(e instanceof Uint8Array))throw new TypeError("data must be a Uint8Array.");if("key"!==t&&"delta"!==t)throw new TypeError('type must be either "key" or "delta".');if(!Number.isFinite(i))throw new TypeError("timestamp must be a number.");if(!Number.isFinite(r)||r<0)throw new TypeError("duration must be a non-negative number.");if(!Number.isFinite(a))throw new TypeError("sequenceNumber must be a number.");if(!Number.isInteger(s)||s<0)throw new TypeError("byteLength must be a non-negative integer.");if(void 0!==n&&("object"!==typeof n||!n))throw new TypeError("sideData, when provided, must be an object.");if(void 0!==n?.alpha&&!(n.alpha instanceof Uint8Array))throw new TypeError("sideData.alpha, when provided, must be a Uint8Array.");if(void 0!==n?.alphaByteLength&&(!Number.isInteger(n.alphaByteLength)||n.alphaByteLength<0))throw new TypeError("sideData.alphaByteLength, when provided, must be a non-negative integer.");this.byteLength=s,this.sideData=n??{},this.sideData.alpha&&void 0===this.sideData.alphaByteLength&&(this.sideData.alphaByteLength=this.sideData.alpha.byteLength)}get isMetadataOnly(){return this.data===rr}get microsecondTimestamp(){return Math.trunc(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){if(!(e instanceof EncodedVideoChunk||e instanceof EncodedAudioChunk))throw new TypeError("chunk must be an EncodedVideoChunk or EncodedAudioChunk.");const i=new Uint8Array(e.byteLength);return e.copyTo(i),new ar(i,e.type,e.timestamp/1e6,(e.duration??0)/1e6,void 0,void 0,t)}clone(e){if(void 0!==e&&("object"!==typeof e||null===e))throw new TypeError("options, when provided, must be an object.");if(void 0!==e?.data&&!(e.data instanceof Uint8Array))throw new TypeError("options.data, when provided, must be a Uint8Array.");if(void 0!==e?.type&&"key"!==e.type&&"delta"!==e.type)throw new TypeError('options.type, when provided, must be either "key" or "delta".');if(void 0!==e?.timestamp&&!Number.isFinite(e.timestamp))throw new TypeError("options.timestamp, when provided, must be a number.");if(void 0!==e?.duration&&!Number.isFinite(e.duration))throw new TypeError("options.duration, when provided, must be a number.");if(void 0!==e?.sequenceNumber&&!Number.isFinite(e.sequenceNumber))throw new TypeError("options.sequenceNumber, when provided, must be a number.");if(void 0!==e?.sideData&&("object"!==typeof e.sideData||null===e.sideData))throw new TypeError("options.sideData, when provided, must be an object.");return new ar(e?.data??this.data,e?.type??this.type,e?.timestamp??this.timestamp,e?.duration??this.duration,e?.sequenceNumber??this.sequenceNumber,this.byteLength,e?.sideData??this.sideData)}}const sr=e=>{const t=J(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const a=de(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=uc(e);const i=bc(e,4);let r=8;1===t&&(t=mc(e),r=16);const a=t-r;return a<0?null:{name:i,totalSize:t,headerSize:r,contentSize:a}},cr=e=>dc(e)/65536,lr=e=>dc(e)/1073741824,ur=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=ac(e);if(t|=127&i,0===(128&i))break}return t},hr=e=>{let t=nc(e);return e.skip(2),t=Math.min(t,e.remainingLength),Z.decode(rc(e,t))},dr=e=>{const t=or(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=uc(e);e.skip(4);const r=rc(e,t.contentSize-8);switch(i){case 1:return Z.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new lt(r,"image/jpeg");case 14:return new lt(r,"image/png");case 27:return new lt(r,"image/bmp");default:return r}},fr=16,mr=new Uint32Array(256),pr=new Uint32Array(256),gr=new Uint32Array(256),kr=new Uint32Array(256),yr=new Uint32Array(256),br=new Uint32Array(256),wr=new Uint32Array(10);let Tr=!1;class Sr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(fr/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(fr),this.out=new Uint8Array(fr),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){j(16===e.byteLength),j(16===t.byteLength),Tr||(()=>{const e=new Uint8Array(256),t=new Uint8Array(256),i=new Uint8Array(256);for(let s=0,n=1;s<256;s++)i[s]=n,t[n]=s,n=n^n<<1^(128&n?283:0);const r=(e,r)=>e&&r?i[(t[e]+t[r])%255]:0;e[0]=99;for(let s=1;s<256;s++){const r=i[255-t[s]];let a=r^r<<1^r<<2^r<<3^r<<4;a=a>>>8^255&a^99,e[s]=a}for(let s=0;s<256;s++){const t=e[s],i=e.indexOf(s);mr[s]=t<<24|t<<16|t<<8|t,br[s]=i<<24|i<<16|i<<8|i;const a=r(i,14)<<24|r(i,9)<<16|r(i,13)<<8|r(i,11);pr[s]=a,gr[s]=a>>>8|a<<24,kr[s]=a>>>16|a<<16,yr[s]=a>>>24|a<<8}let a=1;for(let s=0;s<10;s++)wr[s]=a<<24,a=a<<1^(128&a?283:0);Tr=!0})();const i=new DataView(e.buffer,e.byteOffset,e.byteLength),r=new DataView(t.buffer,t.byteOffset,t.byteLength);this.roundkey[0]=i.getUint32(0,!1),this.roundkey[1]=i.getUint32(4,!1),this.roundkey[2]=i.getUint32(8,!1),this.roundkey[3]=i.getUint32(12,!1),this.iv[0]=r.getUint32(0,!1),this.iv[1]=r.getUint32(4,!1),this.iv[2]=r.getUint32(8,!1),this.iv[3]=r.getUint32(12,!1);for(let a=4;a<44;a+=4){const e=this.roundkey[a-1];this.roundkey[a]=this.roundkey[a-4]^4278190080&mr[e>>>16&255]^16711680&mr[e>>>8&255]^65280&mr[e>>>0&255]^255&mr[e>>>24&255]^wr[a/4-1],this.roundkey[a+1]=this.roundkey[a-3]^this.roundkey[a],this.roundkey[a+2]=this.roundkey[a-2]^this.roundkey[a+1],this.roundkey[a+3]=this.roundkey[a-1]^this.roundkey[a+2]}for(let a=0,s=40;a>>24&255]]^gr[255&mr[t>>>16&255]]^kr[255&mr[t>>>8&255]]^yr[255&mr[t>>>0&255]]}}decrypt(){let e=this.inView.getUint32(0,!1)^this.roundkey[0],t=this.inView.getUint32(4,!1)^this.roundkey[1],i=this.inView.getUint32(8,!1)^this.roundkey[2],r=this.inView.getUint32(12,!1)^this.roundkey[3];const a=this.inView.getUint32(0,!1),s=this.inView.getUint32(4,!1),n=this.inView.getUint32(8,!1),o=this.inView.getUint32(12,!1);let c,l,u,h;for(let g=1;g<10;g++){const a=4*g;c=pr[e>>>24]^gr[r>>>16&255]^kr[i>>>8&255]^yr[255&t]^this.roundkey[a],l=pr[t>>>24]^gr[e>>>16&255]^kr[r>>>8&255]^yr[255&i]^this.roundkey[a+1],u=pr[i>>>24]^gr[t>>>16&255]^kr[e>>>8&255]^yr[255&r]^this.roundkey[a+2],h=pr[r>>>24]^gr[i>>>16&255]^kr[t>>>8&255]^yr[255&e]^this.roundkey[a+3],e=c,t=l,i=u,r=h}const d=4278190080&br[e>>>24&255]^16711680&br[r>>>16&255]^65280&br[i>>>8&255]^255&br[t>>>0&255]^this.roundkey[40],f=4278190080&br[t>>>24&255]^16711680&br[e>>>16&255]^65280&br[r>>>8&255]^255&br[i>>>0&255]^this.roundkey[41],m=4278190080&br[i>>>24&255]^16711680&br[t>>>16&255]^65280&br[e>>>8&255]^255&br[r>>>0&255]^this.roundkey[42],p=4278190080&br[r>>>24&255]^16711680&br[i>>>16&255]^65280&br[t>>>8&255]^255&br[e>>>0&255]^this.roundkey[43];this.outView.setUint32(0,d^this.iv[0],!1),this.outView.setUint32(4,f^this.iv[1],!1),this.outView.setUint32(8,m^this.iv[2],!1),this.outView.setUint32(12,p^this.iv[3],!1),this.iv[0]=a,this.iv[1]=s,this.iv[2]=n,this.iv[3]=o}}class vr extends ir{constructor(e){super(e),this.moovSlice=null,this.currentTrack=null,this.tracks=[],this.metadataPromise=null,this.movieTimescale=-1,this.movieDurationInTimescale=-1,this.isQuickTime=!1,this.metadataTags={},this.currentMetadataKeys=null,this.isFragmented=!1,this.fragmentTrackDefaults=[],this.psshBoxes=[],this.currentFragment=null,this.lastReadFragment=null,this.decryptionKeyCache=new Map,this.reader=e._reader}async getTrackBackings(){return await this.readMetadata(),this.tracks.map(e=>e.trackBacking)}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isQuickTime?"quicktime":"mp4");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({isQuickTime:this.isQuickTime,hasVideo:this.tracks.some(e=>"video"===e.info?.type),hasAudio:this.tracks.some(e=>"audio"===e.info?.type),codecStrings:t.filter(Boolean)})}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(Xe(r)&&(r=await r),!r)break;const a=e,s=or(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=bc(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(Xe(e)&&(e=await e),!e)break;this.moovSlice=e,this.readContiguousBoxes(this.moovSlice);for(const t of this.tracks){const e=t.editListPreviousSegmentDurations/this.movieTimescale;t.editListOffset-=Math.round(e*t.timescale)}t=this.isFragmented&&null!==this.reader.fileSize&&this.reader.fileSize>a+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');await this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=a+s.totalSize}if(!i&&this.input._initInput&&await this.copyMetadataFromInitInput(this.input._initInput),t){j(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);Xe(e)&&(e=await e),j(e);const t=uc(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(Xe(e)&&(e=await e),e){const t=or(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);Xe(i)&&(i=await i),i&&this.readContiguousBoxes(i)}}}}})())}async copyMetadataFromInitInput(e){const t=await e._getDemuxer();if(t.constructor!==vr)throw new Error("Init input must match the input's format.");await t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const i of t.tracks){const e={id:i.id,demuxer:this,trackBacking:null,disposition:i.disposition,timescale:i.timescale,durationInMediaTimescale:i.durationInMediaTimescale,durationInMovieTimescale:i.durationInMovieTimescale,rotation:i.rotation,internalCodecId:i.internalCodecId,name:i.name,languageCode:i.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:i.editListPreviousSegmentDurations,editListOffset:i.editListOffset,encryptionInfo:i.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:i.info};if(i.trackBacking)if(j(e.info),"video"===e.info.type&&-1!==e.info.width){const t=e;e.trackBacking=new Ir(t),this.tracks.push(e)}else if("audio"===e.info.type&&-1!==e.info.numberOfChannels){const t=e;e.trackBacking=new xr(t),this.tracks.push(e)}}}getSampleTableForTrack(e){if(e.sampleTable)return e.sampleTable;const t={sampleTimingEntries:[],sampleCompositionTimeOffsets:[],sampleSizes:[],keySampleIndices:null,chunkOffsets:[],sampleToChunk:[],presentationTimestamps:null,presentationTimestampIndexMap:null};if(e.sampleTable=t,null===e.sampleTableByteOffset)return t;j(this.moovSlice);const i=this.moovSlice.slice(e.sampleTableByteOffset);this.currentTrack=e,this.traverseBox(i),this.currentTrack=null;if("audio"===e.info?.type&&e.info.codec&&Ri.includes(e.info.codec)&&0===t.sampleCompositionTimeOffsets.length){j("audio"===e.info?.type);const i=Vi(e.info.codec),r=[],a=[];for(let s=0;se.startIndex),u=t.sampleTimingEntries[l],h=pe(t.sampleTimingEntries,c,e=>e.startIndex),d=t.sampleTimingEntries[h],f=u.startDecodeTimestamp+(o-u.startIndex)*u.delta,m=d.startDecodeTimestamp+(c-d.startIndex)*d.delta-f,p=X(r);p&&p.delta===m?p.count++:r.push({startIndex:n.startChunkIndex+s,startDecodeTimestamp:f,count:1,delta:m});const g=n.samplesPerChunk*i.sampleSize*e.info.numberOfChannels;a.push(g)}n.startSampleIndex=n.startChunkIndex,n.samplesPerChunk=1}t.sampleTimingEntries=r,t.sampleSizes=a}if(t.sampleCompositionTimeOffsets.length>0){t.presentationTimestamps=[];for(const e of t.sampleTimingEntries)for(let i=0;ie.presentationTimestamp-t.presentationTimestamp),t.presentationTimestampIndexMap=Array(t.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===a.moofOffset);if(i)Rr(s,i.timestamp);else{const e=pe(t,a.moofOffset-1,e=>e.moofOffset);if(-1!==e){const i=t[e];Rr(s,i.endTimestamp)}}s.startTimestampIsFinal=!0}const i=pe(t,s.startTimestamp,e=>e.startTimestamp);if(-1!==i&&t[i].moofOffset===a.moofOffset||t.splice(i+1,0,{moofOffset:a.moofOffset,startTimestamp:s.startTimestamp,endTimestamp:s.endTimestamp}),s.encryptionAuxInfo&&e.encryptionInfo){const t=await Dr(this.reader,e.encryptionInfo,s.encryptionAuxInfo);for(let e=0;e0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ae(t.languageCode)||(t.languageCode=xe)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=bc(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:{...ce},avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=M,this.readContiguousBoxes(e.slice(N,D.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=ac(e);e.skip(3);const r=uc(e);for(let a=0;a0&&(1===n?(e.skip(4),c=8*uc(e),e.skip(8)):2===n&&(e.skip(4),l=yc(e),o=uc(e),e.skip(4),c=uc(e),u=uc(e),e.skip(8))),t.info.numberOfChannels=o,t.info.sampleRate=l,t.frmaCodecString=null,this.readContiguousBoxes(e.slice(e.filePos,r+a.totalSize-e.filePos));const h="enca"===s?t.frmaCodecString:s;if(t.frmaCodecString=null,"mp4a"===h);else if("opus"===h)t.info.codec="opus",t.info.sampleRate=Wi;else if("flac"===h)t.info.codec="flac";else if("ulaw"===h)t.info.codec="ulaw";else if("alaw"===h)t.info.codec="alaw";else if("ac-3"===h)t.info.codec="ac3";else if("ec-3"===h)t.info.codec="eac3";else if(Li.includes(h))t.info.codec="dts",t.info.dtsFormat=h;else if("twos"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(ct._warn(`Unsupported sample size ${c} for codec 'twos'.`),t.info.codec=null);else if("sowt"===h)8===c?t.info.codec="pcm-s8":16===c?t.info.codec="pcm-s16":(ct._warn(`Unsupported sample size ${c} for codec 'sowt'.`),t.info.codec=null);else if("raw "===h)t.info.codec="pcm-u8";else if("in24"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s24":"pcm-s24be";else if("in32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-s32":"pcm-s32be";else if("fl32"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f32":"pcm-f32be";else if("fl64"===h)t.info.codec=t.info.pcmLittleEndian?"pcm-f64":"pcm-f64be";else if("ipcm"===h){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":(ct._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":(ct._warn(`Invalid ipcm sample size ${e}.`),t.info.codec=null)}else if("fpcm"===h){const e=t.info.pcmSampleSize;t.info.pcmLittleEndian?32===e?t.info.codec="pcm-f32":64===e?t.info.codec="pcm-f64":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(ct._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null)}else if("lpcm"===h&&null!==u){const e=c+7>>3,i=Boolean(1&u),r=Boolean(2&u),a=4&u?-1:0;c>0&&c<=64&&(i?32===c&&(t.info.codec=r?"pcm-f32be":"pcm-f32"):a&1<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==ac(e),t.encryptionInfo.defaultPerSampleIvSize=ac(e),t.encryptionInfo.defaultKid=de(rc(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=ac(e),r=new Uint8Array(16);r.set(rc(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(j(t.info),0===D.contentSize)break;t.info.codecDescription=rc(e,D.contentSize)}break;case"vpcC":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(4);const i=ac(e),r=ac(e),a=ac(e),s=a>>4,n=a>>1&7,o=1&a,c=ac(e),l=ac(e),u=ac(e);t.info.vp9CodecInfo={profile:i,level:r,bitDepth:s,chromaSubsampling:n,videoFullRangeFlag:o,colourPrimaries:c,transferCharacteristics:l,matrixCoefficients:u}}break;case"av1C":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type),e.skip(1);const i=ac(e),r=i>>5,a=31&i,s=ac(e),n=s>>7,o=s>>6&1,c=s>>4&1,l=s>>3&1,u=s>>2&1,h=3&s,d=2===r&&o?s>>5&1?12:10:o?10:8;e.skip(1);const f=rc(e,D.contentSize-4),m=ii(f);t.info.av1CodecInfo={profile:r,level:a,tier:n,bitDepth:d,monochrome:c,chromaSubsamplingX:l,chromaSubsamplingY:u,chromaSamplePosition:h,videoFullRangeFlag:m?.videoFullRangeFlag??0,colourPrimaries:m?.colourPrimaries??2,transferCharacteristics:m?.transferCharacteristics??2,matrixCoefficients:m?.matrixCoefficients??2}}break;case"colr":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=bc(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=nc(e),a=nc(e),s=nc(e);let n;"nclx"===i&&(n=Boolean(128&ac(e))),t.info.colorSpace={primaries:ie[r],transfer:ae[a],matrix:ne[s],fullRange:n}}break;case"pasp":{const t=this.currentTrack;if(!t)break;j("video"===t.info?.type);const i=uc(e),r=uc(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==t.info?.type)break;e.skip(4);j(3===ac(e)),ur(e),e.skip(2);const i=ac(e),r=0!==(64&i),a=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=ac(e);e.skip(t)}a&&e.skip(2);j(4===ac(e));const s=ur(e),n=e.filePos,o=ac(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":ct._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-n){j(5===ac(e));const i=ur(e);if(t.info.codecDescription=rc(e,i),"aac"===t.info.codec){const e=pt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),t.info.pcmLittleEndian=!!(255&nc(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=ac(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=ac(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(1);const i=ac(e),r=nc(e),a=uc(e),s=cc(e),n=ac(e);let o;o=0!==n?rc(e,2+i):new Uint8Array(0);const c=new Uint8Array(19+o.byteLength),l=new DataView(c.buffer);l.setUint32(0,1332770163,!1),l.setUint32(4,1214603620,!1),l.setUint8(8,1),l.setUint8(9,i),l.setUint16(10,r,!0),l.setUint32(12,a,!0),l.setInt16(16,s,!0),l.setUint8(18,n),c.set(o,19),t.info.codecDescription=c,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type),e.skip(4);const i=127,r=128,a=e.filePos;for(;e.filePos>>12,a=1+(i>>9&7);t.info.sampleRate=r,t.info.numberOfChannels=a,e.skip(20)}else e.skip(s);if(a&r)break}const s=e.filePos;e.filePos=a;const n=rc(e,s-a),o=new Uint8Array(4+n.byteLength);new DataView(o.buffer).setUint32(0,1716281667,!1),o.set(n,4),t.info.codecDescription=o}break;case"dac3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=rc(e,3),r=new dt(i),a=r.readBits(2);r.skipBits(8);const s=r.readBits(3),n=r.readBits(1);a<3&&(t.info.sampleRate=yt[a]),t.info.numberOfChannels=ui[s]+n}break;case"dec3":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<2)return null;const t=new dt(e),i=t.readBits(13),r=t.readBits(3),a=[];for(let s=0;s<=r&&!(Math.ceil(t.pos/8)+3>e.length);s++){const e=t.readBits(2),i=t.readBits(5);t.skipBits(1),t.skipBits(1);const r=t.readBits(3),s=t.readBits(3),n=t.readBits(1);t.skipBits(3);const o=t.readBits(4);let c=0;o>0?c=t.readBits(9):t.skipBits(1),a.push({fscod:e,fscod2:null,bsid:i,bsmod:r,acmod:s,lfeon:n,numDepSub:o,chanLoc:c})}return 0===a.length?null:{dataRate:i,substreams:a}})(rc(e,D.contentSize));if(!i){ct._warn("Invalid dec3 box contents, ignoring.");break}const r=pi(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=gi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;j("audio"===t.info?.type);const i=(e=>{if(e.length<20)return null;const t=J(e),i=t.getUint32(0);if(0===i)return null;const r=new dt(e);r.seekToByte(13);const a=r.readBits(2);r.skipBits(5);const s=r.readBits(1),n=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let c=null;return 0!==o?c=Ei(o):ne.id===i);if(!r)break;const a=uc(e),s=(12&a)>>2,n=3&a,o=[ac,nc,oc,uc],c=o[(48&a)>>4],l=o[s],u=o[n],h=uc(e);for(let d=0;de.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let a=0;ae.id===l);if(!u)break;const h=this.fragmentTrackDefaults.find(e=>e.trackId===l);this.currentTrack=u,u.currentFragmentState={baseDataOffset:this.currentFragment.implicitBaseDataOffset,sampleDescriptionIndex:h?.defaultSampleDescriptionIndex??null,defaultSampleDuration:h?.defaultSampleDuration??null,defaultSampleSize:h?.defaultSampleSize??null,defaultSampleFlags:h?.defaultSampleFlags??null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=mc(e):c&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=uc(e)),a&&(u.currentFragmentState.defaultSampleDuration=uc(e)),s&&(u.currentFragmentState.defaultSampleSize=uc(e)),n&&(u.currentFragmentState.defaultSampleFlags=uc(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;j(t.currentFragmentState);const i=ac(e);e.skip(3);const r=0===i?uc(e):mc(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;j(this.currentFragment),j(t.currentFragmentState);const i=ac(e),r=oc(e),a=Boolean(1&r),s=Boolean(4&r),n=Boolean(256&r),o=Boolean(512&r),c=Boolean(1024&r),l=Boolean(2048&r),u=uc(e);let h=null;a&&(h=dc(e));let d,f=null;s&&(f=uc(e)),this.currentFragment.trackData.has(t.id)?(d=this.currentFragment.trackData.get(t.id),null!==h&&(d.currentOffset=t.currentFragmentState.baseDataOffset+h)):(d={track:t,currentTimestamp:0,currentOffset:t.currentFragmentState.baseDataOffset+(h??0),startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,samples:[],presentationTimestamps:[],startTimestampIsFinal:!1,encryptionAuxInfo:null},this.currentFragment.trackData.set(t.id,d));for(let m=0;m0&&(a=rc(e,r));const s=Mr(t);s.defaultSampleInfoSize=i,s.sampleSizes=a,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=ac(e);if(1&oc(e)){const i=bc(e,4),r=uc(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=uc(e);if(0===r)break;r>1&&ct._warn("Multiple saio entries are not supported; using the first offset only.");let a=0===i?uc(e):Number(mc(e));this.currentFragment&&(a+=this.currentFragment.moofOffset);Mr(t).offset=a}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;j(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=oc(e),a=Boolean(2&r),s=uc(e),n=t.encryptionInfo.defaultPerSampleIvSize;j(null!==n);for(let o=0;o0?r.set(rc(e,n),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(a){const t=nc(e);s=[];for(let i=0;i0&&((B=this.metadataTags).trackNumber??(B.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((E=this.metadataTags).tracksTotal??(E.tracksTotal=i))}break;case"trkn":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((_=this.metadataTags).trackNumber??(_.trackNumber=t)),i>0&&((R=this.metadataTags).tracksTotal??(R.tracksTotal=i))}break;case"disc":case"disk":if(a instanceof Uint8Array&&a.length>=6){const e=J(a),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&((F=this.metadataTags).discNumber??(F.discNumber=t)),i>0&&((A=this.metadataTags).discsTotal??(A.discsTotal=i))}}}}}return e.filePos=O,!0}}class Pr{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.internalTrack;if(e.durationInMediaTimescale<=0)return null;j(e.trackBacking);const t=await e.trackBacking.getFirstPacket({metadataOnly:!0});return(t?.timestamp??0)+e.durationInMediaTimescale/e.timescale}async getLiveRefreshInterval(){return null}async getFirstPacket(e){const t=await this.fetchPacketForSampleIndex(0,e);return t||!this.internalTrack.demuxer.isFragmented?t:this.performFragmentedLookup(null,e=>e.trackData.get(this.internalTrack.id)?{sampleIndex:0,correctSampleFound:!0}:{sampleIndex:-1,correctSampleFound:!1},-1/0,1/0,e)}mapTimestampIntoTimescale(e){return Ce(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}async getPacket(e,t){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),a=Cr(r,i),s=await this.fetchPacketForSampleIndex(a,t);return Ar(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=pe(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=we(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 j(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)}async fetchPacketForSampleIndex(e,t){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=Er(i,e);if(!r)return null;let a;if(t.metadataOnly)a=rr;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(Xe(t)&&(t=await t),!t)return null;if(a=rc(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=await Dr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),u=-1!==l?this.internalTrack.fragmentLookupTable[l]:null,h=pe(this.internalTrack.fragmentPositionCache,i,e=>e.startTimestamp),d=-1!==h?this.internalTrack.fragmentPositionCache[h]:null,f=Math.max(u?.moofOffset??0,d?.moofOffset??0)||null;let m;for(e?null===f||e.moofOffset>=f?(m=e.moofOffset+e.moofSize,n=e):m=f:m=f??0;;){if(n){const e=n.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(m,8,16);if(Xe(e)&&(e=await e),!e)break;const i=m,l=or(e);if(!l)break;if("moof"===l.name){n=await s.readFragment(i);const{sampleIndex:e,correctSampleFound:r}=t(n);if(r)return this.fetchPacketInFragment(n,e,a);-1!==e&&(o=n,c=e)}m=i+l.totalSize}if(u&&(!o||o.moofOffset{var e,t,i,r,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=await this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&ri(e.data)}}else{const e=await this.getFirstPacket({}),t=e&&ii(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const e=await this.getFirstPacket({}),t=e&&ei(e.data);t&&(this.internalTrack.info.vp9CodecInfo={...this.internalTrack.info.vp9CodecInfo??t,videoFullRangeFlag:t.videoFullRangeFlag,colourPrimaries:t.colourPrimaries,transferCharacteristics:t.transferCharacteristics,matrixCoefficients:t.matrixCoefficients})}else{const e=await this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&Wt(e.data)}else{const e=await this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&Ft(e.data)}if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(this.internalTrack.info);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const s={codec:zi(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(s.displayAspectWidth=this.internalTrack.info.squarePixelWidth,s.displayAspectHeight=this.internalTrack.info.squarePixelHeight),s})()):null}}class xr extends Pr{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi(this.internalTrack.info),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Cr=(e,t)=>{if(e.presentationTimestamps){const i=pe(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=pe(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)}},Br=(e,t)=>{if(!e.keySampleIndices)return Cr(e,t);if(e.presentationTimestamps){const i=pe(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!==me(e.keySampleIndices,i,e=>e))return i}return-1}{const i=Cr(e,t),r=pe(e.keySampleIndices,i,e=>e);return e.keySampleIndices[r]??-1}},Er=(e,t)=>{const i=pe(e.sampleTimingEntries,t,e=>e.startIndex),r=e.sampleTimingEntries[i];if(!r||r.startIndex+r.count<=t)return null;let a=r.startDecodeTimestamp+(t-r.startIndex)*r.delta;const s=pe(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),n=e.sampleCompositionTimeOffsets[s];n&&t-n.startIndexe.startSampleIndex),l=e.sampleToChunk[c];j(l);const u=l.startChunkIndex+Math.floor((t-l.startSampleIndex)/l.samplesPerChunk),h=e.chunkOffsets[u],d=l.startSampleIndex+(u-l.startChunkIndex)*l.samplesPerChunk;let f=0,m=h;if(1===e.sampleSizes.length)m+=o*(t-d),f+=o*l.samplesPerChunk;else for(let g=d;ge)}},_r=(e,t)=>{if(!e.keySampleIndices)return t+1;const i=pe(e.keySampleIndices,t,e=>e);return e.keySampleIndices[i+1]??-1},Rr=(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},Fr=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Ar=e=>0===e.sampleSizes.length,Mr=e=>{var t;return e.currentFragmentState?(t=e.currentFragmentState).encryptionAuxInfo??(t.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null}):e.encryptionAuxInfo??(e.encryptionAuxInfo={defaultSampleInfoSize:0,sampleSizes:null,sampleCount:0,offset:null,resolved:null})},Dr=async(e,t,i)=>{if(i.resolved)return i.resolved;if(null===i.offset||0===i.sampleCount)throw new Error("Incomplete saiz/saio info; cannot resolve encryption data.");let r=0;if(i.defaultSampleInfoSize>0)r=i.defaultSampleInfoSize*i.sampleCount;else{j(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[o],r=new Uint8Array(16);s>0?r.set(rc(a,s),0):r.set(t.defaultConstantIv,0);let c=null;if(e>s){const e=nc(a);c=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Or=async(e,t,i,r)=>{j(e.encryptionInfo);const a=e.encryptionInfo;j(null!==a.defaultKid);const s=a.defaultKid;let n;const o=e.demuxer.decryptionKeyCache.get(s);if(o)n=await o;else{if(!e.demuxer.input._formatOptions.isobmff?.resolveKeyId)throw new Error("Encrypted media samples encountered. To decrypt them, please provide a callback for InputOptions.formatOptions.isobmff.resolveKeyId.");const t=(async()=>{let t=e.demuxer.psshBoxes;if(r){t=[...t,...r.psshBoxes].filter(e=>null===e.keyIds||e.keyIds.includes(s));for(let e=0;e{j(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;i{const a=new Uint8Array(16);a.set(i.iv,0);const s=await crypto.subtle.importKey("raw",e,{name:"AES-CTR"},!1,["decrypt"]),n=async e=>{const t=await crypto.subtle.decrypt({name:"AES-CTR",counter:a,length:64},s,e);return new Uint8Array(t)};if(!i.subsamples)return n(r);j(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=Ur(i.subsamples,t.defaultCryptByteBlock,t.defaultSkipByteBlock);let c=0;for(const m of o)for(const e of m.perSubsample)c+=e.length;const l=new Uint8Array(c);let u=0;for(const m of o)for(const e of m.perSubsample)l.set(r.subarray(e.offset,e.offset+e.length),u),u+=e.length;const h=await n(l),d=new Uint8Array(r);let f=0;for(const m of o)for(const e of m.perSubsample)d.set(h.subarray(f,f+e.length),e.offset),f+=e.length;return d},zr=(e,t,i,r)=>{const a=new Sr;a.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,n=t.defaultSkipByteBlock;if(j(null!==s&&null!==n),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;i{const r=[],a=0!==t||0!==i;let s=0;for(const n of e){s+=n.clearLen;const e=[];if(a){let r=n.protectedLen,a=s;for(;r>0&&!(r<16*t);){const s=16*t;e.push({offset:a,length:s}),a+=s,r-=s;const n=Math.min(16*i,r);a+=n,r-=n}s+=n.protectedLen}else n.protectedLen>0&&e.push({offset:s,length:n.protectedLen}),s+=n.protectedLen;r.push({perSubsample:e})}return r};var qr,Wr;(Wr=qr||(qr={}))[Wr.EBML=440786851]="EBML",Wr[Wr.EBMLVersion=17030]="EBMLVersion",Wr[Wr.EBMLReadVersion=17143]="EBMLReadVersion",Wr[Wr.EBMLMaxIDLength=17138]="EBMLMaxIDLength",Wr[Wr.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",Wr[Wr.DocType=17026]="DocType",Wr[Wr.DocTypeVersion=17031]="DocTypeVersion",Wr[Wr.DocTypeReadVersion=17029]="DocTypeReadVersion",Wr[Wr.Void=236]="Void",Wr[Wr.Segment=408125543]="Segment",Wr[Wr.SeekHead=290298740]="SeekHead",Wr[Wr.Seek=19899]="Seek",Wr[Wr.SeekID=21419]="SeekID",Wr[Wr.SeekPosition=21420]="SeekPosition",Wr[Wr.Duration=17545]="Duration",Wr[Wr.Info=357149030]="Info",Wr[Wr.TimestampScale=2807729]="TimestampScale",Wr[Wr.MuxingApp=19840]="MuxingApp",Wr[Wr.WritingApp=22337]="WritingApp",Wr[Wr.Tracks=374648427]="Tracks",Wr[Wr.TrackEntry=174]="TrackEntry",Wr[Wr.TrackNumber=215]="TrackNumber",Wr[Wr.TrackUID=29637]="TrackUID",Wr[Wr.TrackType=131]="TrackType",Wr[Wr.FlagEnabled=185]="FlagEnabled",Wr[Wr.FlagDefault=136]="FlagDefault",Wr[Wr.FlagForced=21930]="FlagForced",Wr[Wr.FlagOriginal=21934]="FlagOriginal",Wr[Wr.FlagHearingImpaired=21931]="FlagHearingImpaired",Wr[Wr.FlagVisualImpaired=21932]="FlagVisualImpaired",Wr[Wr.FlagCommentary=21935]="FlagCommentary",Wr[Wr.FlagLacing=156]="FlagLacing",Wr[Wr.Name=21358]="Name",Wr[Wr.Language=2274716]="Language",Wr[Wr.LanguageBCP47=2274717]="LanguageBCP47",Wr[Wr.CodecID=134]="CodecID",Wr[Wr.CodecPrivate=25506]="CodecPrivate",Wr[Wr.CodecDelay=22186]="CodecDelay",Wr[Wr.SeekPreRoll=22203]="SeekPreRoll",Wr[Wr.DefaultDuration=2352003]="DefaultDuration",Wr[Wr.Video=224]="Video",Wr[Wr.PixelWidth=176]="PixelWidth",Wr[Wr.PixelHeight=186]="PixelHeight",Wr[Wr.DisplayWidth=21680]="DisplayWidth",Wr[Wr.DisplayHeight=21690]="DisplayHeight",Wr[Wr.DisplayUnit=21682]="DisplayUnit",Wr[Wr.AlphaMode=21440]="AlphaMode",Wr[Wr.Audio=225]="Audio",Wr[Wr.SamplingFrequency=181]="SamplingFrequency",Wr[Wr.Channels=159]="Channels",Wr[Wr.BitDepth=25188]="BitDepth",Wr[Wr.SimpleBlock=163]="SimpleBlock",Wr[Wr.BlockGroup=160]="BlockGroup",Wr[Wr.Block=161]="Block",Wr[Wr.BlockAdditions=30113]="BlockAdditions",Wr[Wr.BlockMore=166]="BlockMore",Wr[Wr.BlockAdditional=165]="BlockAdditional",Wr[Wr.BlockAddID=238]="BlockAddID",Wr[Wr.BlockDuration=155]="BlockDuration",Wr[Wr.ReferenceBlock=251]="ReferenceBlock",Wr[Wr.Cluster=524531317]="Cluster",Wr[Wr.Timestamp=231]="Timestamp",Wr[Wr.Cues=475249515]="Cues",Wr[Wr.CuePoint=187]="CuePoint",Wr[Wr.CueTime=179]="CueTime",Wr[Wr.CueTrackPositions=183]="CueTrackPositions",Wr[Wr.CueTrack=247]="CueTrack",Wr[Wr.CueClusterPosition=241]="CueClusterPosition",Wr[Wr.Colour=21936]="Colour",Wr[Wr.MatrixCoefficients=21937]="MatrixCoefficients",Wr[Wr.TransferCharacteristics=21946]="TransferCharacteristics",Wr[Wr.Primaries=21947]="Primaries",Wr[Wr.Range=21945]="Range",Wr[Wr.Projection=30320]="Projection",Wr[Wr.ProjectionType=30321]="ProjectionType",Wr[Wr.ProjectionPoseRoll=30325]="ProjectionPoseRoll",Wr[Wr.Attachments=423732329]="Attachments",Wr[Wr.AttachedFile=24999]="AttachedFile",Wr[Wr.FileDescription=18046]="FileDescription",Wr[Wr.FileName=18030]="FileName",Wr[Wr.FileMediaType=18016]="FileMediaType",Wr[Wr.FileData=18012]="FileData",Wr[Wr.FileUID=18094]="FileUID",Wr[Wr.Chapters=272869232]="Chapters",Wr[Wr.Tags=307544935]="Tags",Wr[Wr.Tag=29555]="Tag",Wr[Wr.Targets=25536]="Targets",Wr[Wr.TargetTypeValue=26826]="TargetTypeValue",Wr[Wr.TargetType=25546]="TargetType",Wr[Wr.TagTrackUID=25541]="TagTrackUID",Wr[Wr.TagEditionUID=25545]="TagEditionUID",Wr[Wr.TagChapterUID=25540]="TagChapterUID",Wr[Wr.TagAttachmentUID=25542]="TagAttachmentUID",Wr[Wr.SimpleTag=26568]="SimpleTag",Wr[Wr.TagName=17827]="TagName",Wr[Wr.TagLanguage=17530]="TagLanguage",Wr[Wr.TagString=17543]="TagString",Wr[Wr.TagBinary=17541]="TagBinary",Wr[Wr.ContentEncodings=28032]="ContentEncodings",Wr[Wr.ContentEncoding=25152]="ContentEncoding",Wr[Wr.ContentEncodingOrder=20529]="ContentEncodingOrder",Wr[Wr.ContentEncodingScope=20530]="ContentEncodingScope",Wr[Wr.ContentCompression=20532]="ContentCompression",Wr[Wr.ContentCompAlgo=16980]="ContentCompAlgo",Wr[Wr.ContentCompSettings=16981]="ContentCompSettings",Wr[Wr.ContentEncryption=20533]="ContentEncryption";const Hr=[qr.EBML,qr.Segment],Vr=[qr.SeekHead,qr.Info,qr.Cluster,qr.Tracks,qr.Cues,qr.Attachments,qr.Chapters,qr.Tags],jr=[...Hr,...Vr],Kr=16,Xr=e=>{if(e.remainingLength<1)return null;const t=ac(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=ac(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=Xr(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===ac(e))return;e.skip(-1);const t=$r(e);return null===t?null:72057594037927940!==t?t:void 0},Jr=e=>{j(e.remainingLength>=2);const t=Qr(e);if(null===t)return null;const i=Yr(e);return null===i?null:{id:t,size:i}},Zr=(e,t)=>{const i=rc(e,t);let r=0;for(;r{const i=rc(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?kc(e):yc(e)},ia=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}},ra=async(e,t,i,r)=>{const a=new Set(i);let s=t;for(;se.tracks.map(e=>e.trackBacking))}async getMimeType(){await this.readMetadata();const e=await this.getTrackBackings(),t=await Promise.all(e.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)));return(e=>{let t=(e.hasVideo?"video/":e.hasAudio?"audio/":"application/")+(e.isWebM?"webm":"x-matroska");e.codecStrings.length>0&&(t+=`; codecs="${[...new Set(e.codecStrings.filter(Boolean))].join(", ")}"`);return t})({isWebM:this.isWebM,hasVideo:this.segments.some(e=>e.tracks.some(e=>"video"===e.info?.type)),hasAudio:this.segments.some(e=>e.tracks.some(e=>"audio"===e.info?.type)),codecStrings:t.filter(Boolean)})}async getMetadataTags(){await this.readMetadata();for(const t of this.segments)t.metadataTagsCollected||(null!==this.reader.fileSize&&await this.loadSegmentMetadata(t),t.metadataTagsCollected=!0);let e={};for(const t of this.segments)e={...e,...t.metadataTags};return e}readMetadata(){return this.readMetadataPromise??(this.readMetadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,Kr);if(Xe(t)&&(t=await t),!t)break;const i=Jr(t);if(!i)break;const r=i.id;let a=i.size;const s=t.filePos;if(r===qr.EBML){ya(a);let e=this.reader.requestSlice(s,a);if(Xe(e)&&(e=await e),!e)break;this.readContiguousElements(e)}else if(r===qr.Segment){if(await this.readSegment(s,a),void 0===a)break;if(null===this.reader.fileSize)break}else if(r===qr.Cluster){if(null===this.reader.fileSize)break;if(void 0===a){a=(await ia(this.reader,s,jr,this.reader.fileSize)).pos-s}const e=X(this.segments);e&&(e.elementEndPos=s+a)}ya(a),e=s+a}})())}async readSegment(e,t){this.currentSegment={seekHeadSeen:!1,infoSeen:!1,tracksSeen:!1,cuesSeen:!1,tagsSeen:!1,attachmentsSeen:!1,timestampScale:-1,timestampFactor:-1,duration:-1,seekEntries:[],tracks:[],cuePoints:[],dataStartPos:e,elementEndPos:void 0===t?null:e+t,clusterSeekStartPos:e,lastReadCluster:null,metadataTags:{},metadataTagsCollected:!1},this.segments.push(this.currentSegment);let i=e;for(;null===this.currentSegment.elementEndPos||ie.id===a);if(-1!==o){const e=Ia[o].flag;this.currentSegment[e]=!0,ya(s);let t=this.reader.requestSlice(n,s);Xe(t)&&(t=await t),t&&this.readContiguousElements(t)}else if(a===qr.Tags||a===qr.Attachments){a===qr.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,ya(s);let e=this.reader.requestSlice(n,s);Xe(e)&&(e=await e),e&&this.readContiguousElements(e)}else if(a===qr.Cluster){this.currentSegment.clusterSeekStartPos=t;break}if(void 0===s)break;i=n+s}if(this.currentSegment.seekEntries.sort((e,t)=>e.segmentPosition-t.segmentPosition),null!==this.reader.fileSize)for(const n of this.currentSegment.seekEntries){const t=Ia.find(e=>e.id===n.id);if(!t)continue;if(this.currentSegment[t.flag])continue;let i=this.reader.requestSliceRange(e+n.segmentPosition,2,Kr);if(Xe(i)&&(i=await i),!i)continue;const r=Jr(i);if(!r)continue;const{id:a,size:s}=r;if(a!==t.id)continue;ya(s),this.currentSegment[t.flag]=!0;let o=this.reader.requestSlice(i.filePos,s);Xe(o)&&(o=await o),o&&this.readContiguousElements(o)}-1===this.currentSegment.timestampScale&&(this.currentSegment.timestampScale=1e6,this.currentSegment.timestampFactor=1e3);for(const n of this.currentSegment.tracks)null!==n.defaultDurationNs&&(n.defaultDuration=this.currentSegment.timestampFactor*n.defaultDurationNs/1e9);const r=new Map(this.currentSegment.tracks.map(e=>[e.id,e]));for(const n of this.currentSegment.cuePoints){const e=r.get(n.trackId);e&&e.cuePoints.push(n)}for(const n of this.currentSegment.tracks){n.cuePoints.sort((e,t)=>e.time-t.time);for(let e=0;es&&(s=n.cuePoints.length,a=n);for(const n of this.currentSegment.tracks)0===n.cuePoints.length&&(n.cuePoints=a.cuePoints);this.currentSegment=null}async readCluster(e,t){if(t.lastReadCluster?.elementStartPos===e)return t.lastReadCluster;let i=this.reader.requestSliceRange(e,2,Kr);Xe(i)&&(i=await i),j(i);const r=e,a=Jr(i);j(a);j(a.id===qr.Cluster);let s=a.size;const n=i.filePos;if(void 0===s){s=(await ia(this.reader,n,jr,t.elementEndPos)).pos-n}let o=this.reader.requestSlice(n,s);Xe(o)&&(o=await o);const c={segment:t,elementStartPos:r,elementEndPos:n+s,dataStartPos:n,timestamp:-1,trackData:new Map};if(this.currentCluster=c,o){const e=this.readContiguousElements(o,jr);c.elementEndPos=e}for(const[,l]of c.trackData){const e=l.track;j(l.blocks.length>0);let t=!1;for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let r=0;r({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const i=l.blocks[l.presentationTimestamps[0].blockIndex],a=l.blocks[X(l.presentationTimestamps).blockIndex];l.startTimestamp=i.timestamp,l.endTimestamp=a.timestamp+a.duration;const s=pe(e.clusterPositionCache,l.startTimestamp,e=>e.startTimestamp);-1!==s&&e.clusterPositionCache[s].elementStartPos===r||e.clusterPositionCache.splice(s+1,0,{elementStartPos:c.elementStartPos,startTimestamp:l.startTimestamp})}return t.lastReadCluster=c,c}getTrackDataInCluster(e,t){let i=e.trackData.get(t);if(!i){const r=e.segment.tracks.find(e=>e.id===t);if(!r)return null;i={track:r,startTimestamp:0,endTimestamp:0,firstKeyFrameTimestamp:null,blocks:[],presentationTimestamps:[]},e.trackData.set(t,i)}return i}expandLacedBlocks(e,t){for(let i=0;i=2;){const i=e.filePos;if(!this.traverseElement(e,t))return i}return e.filePos}traverseElement(e,t){const i=Jr(e);if(!i)return!1;if(t&&t.includes(i.id))return!1;const{id:r,size:a}=i,s=e.filePos;switch(ya(a),r){case qr.DocType:this.isWebM="webm"===Zr(e,a);break;case qr.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case qr.SeekID:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=Gr(e,a)}break;case qr.SeekPosition:{const t=this.currentSegment?.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=Gr(e,a)}break;case qr.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=Gr(e,a),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case qr.Duration:if(!this.currentSegment)break;this.currentSegment.duration=ta(e,a);break;case qr.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:{...ht,primary:!1},trackBacking:null,codecId:null,codecPrivate:null,defaultDuration:null,defaultDurationNs:null,name:null,languageCode:"eng",hasLanguageBcp47:!1,decodingInstructions:[],info:null},this.readContiguousElements(e.slice(s,a)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>"decompress"!==e.data?.type||e.scope!==Ta.Block||e.data.algorithm!==va.HeaderStripping)&&(ct._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===aa)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===sa)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===na)this.currentTrack.info.codec="vp8";else if(t===oa)this.currentTrack.info.codec="vp9";else if(t===ca)this.currentTrack.info.codec="av1";else if(t===la){const e=this.currentTrack.codecPrivate?Z.decode(this.currentTrack.codecPrivate):"";Oi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Ea(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===ua?(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===ha?this.currentTrack.info.codec="mp3":t===da?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=Wi):t===fa?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ma?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===pa?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ga?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===ka?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new _a(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case qr.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=Gr(e,a);break;case qr.TrackType:{if(!this.currentTrack)break;const t=Gr(e,a);1===t?this.currentTrack.info={type:"video",width:-1,height:-1,displayWidth:null,displayHeight:null,displayUnit:null,squarePixelWidth:-1,squarePixelHeight:-1,rotation:0,codec:null,codecDescription:null,colorSpace:{...ce},alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case qr.FlagEnabled:if(!this.currentTrack)break;Gr(e,a)||(this.currentTrack=null);break;case qr.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!Gr(e,a);break;case qr.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!Gr(e,a);break;case qr.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!Gr(e,a);break;case qr.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!Gr(e,a);break;case qr.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!Gr(e,a);break;case qr.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!Gr(e,a);break;case qr.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=Zr(e,a);break;case qr.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=rc(e,a);break;case qr.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=Gr(e,a);break;case qr.Name:if(!this.currentTrack)break;this.currentTrack.name=ea(e,a);break;case qr.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=Zr(e,a),Ae(this.currentTrack.languageCode)||(this.currentTrack.languageCode=xe);break;case qr.LanguageBCP47:{if(!this.currentTrack)break;const t=Zr(e,a).split("-")[0];this.currentTrack.languageCode=t||xe,this.currentTrack.hasLanguageBcp47=!0}break;case qr.Video:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.PixelWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.width=Gr(e,a);break;case qr.PixelHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.height=Gr(e,a);break;case qr.DisplayWidth:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayWidth=Gr(e,a);break;case qr.DisplayHeight:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayHeight=Gr(e,a);break;case qr.DisplayUnit:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.displayUnit=Gr(e,a);break;case qr.AlphaMode:if("video"!==this.currentTrack?.info?.type)break;this.currentTrack.info.alphaMode=1===Gr(e,a);break;case qr.Colour:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.MatrixCoefficients:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ne[t];this.currentTrack.info.colorSpace.matrix=i}break;case qr.Range:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case qr.TransferCharacteristics:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ae[t];this.currentTrack.info.colorSpace.transfer=i}break;case qr.Primaries:{if("video"!==this.currentTrack?.info?.type)break;const t=Gr(e,a),i=ie[t];this.currentTrack.info.colorSpace.primaries=i}break;case qr.Projection:if("video"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.ProjectionPoseRoll:{if("video"!==this.currentTrack?.info?.type)break;const t=-ta(e,a);try{this.currentTrack.info.rotation=K(t)}catch{}}break;case qr.Audio:if("audio"!==this.currentTrack?.info?.type)break;this.readContiguousElements(e.slice(s,a));break;case qr.SamplingFrequency:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.sampleRate=ta(e,a);break;case qr.Channels:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.numberOfChannels=Gr(e,a);break;case qr.BitDepth:if("audio"!==this.currentTrack?.info?.type)break;this.currentTrack.info.bitDepth=Gr(e,a);break;case qr.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(s,a)),this.currentCueTime=null;break;case qr.CueTime:this.currentCueTime=Gr(e,a);break;case qr.CueTrackPositions:{if(null===this.currentCueTime)break;j(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(s,a)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case qr.CueTrack:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=Gr(e,a)}break;case qr.CueClusterPosition:{const t=this.currentSegment?.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;j(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+Gr(e,a)}break;case qr.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=Gr(e,a);break;case qr.SimpleBlock:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e),o=n>>1&3;let c=!!(128&n);"audio"===i.track.info?.type&&i.track.info.codec&&(c=!0);const l=rc(e,a-(e.filePos-s)),u=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:c,data:l,lacing:o,decoded:!u,postProcessed:!1,mainAdditional:null})}break;case qr.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(s,a)),this.currentBlock=null;break;case qr.Block:{if(!this.currentCluster)break;const t=$r(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=cc(e),n=ac(e)>>1&3,o=rc(e,a-(e.filePos-s)),c=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:o,lacing:n,decoded:!c,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case qr.BlockAdditions:this.readContiguousElements(e.slice(s,a));break;case qr.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(s,a)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case qr.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=rc(e,a);break;case qr.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=Gr(e,a);break;case qr.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=Gr(e,a);break;case qr.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case qr.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(s,a));break;case qr.Targets:this.readContiguousElements(e.slice(s,a));break;case qr.TargetTypeValue:50!==Gr(e,a)&&(this.currentTagTargetIsMovie=!1);break;case qr.TagTrackUID:case qr.TagEditionUID:case qr.TagChapterUID:case qr.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case qr.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(s,a));break;case qr.TagName:this.currentSimpleTagName=ea(e,a);break;case qr.TagString:{if(!this.currentSimpleTagName)break;const t=ea(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.TagBinary:{if(!this.currentSimpleTagName)break;const t=rc(e,a);this.processTagValue(this.currentSimpleTagName,t)}break;case qr.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(s,a));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(t.raw??(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new ut(this.currentAttachedFile.fileData,this.currentAttachedFile.fileMediaType??void 0,this.currentAttachedFile.fileName??void 0,this.currentAttachedFile.fileDescription??void 0)),this.currentAttachedFile.fileMediaType?.startsWith("image/")&&this.currentAttachedFile.fileData){const e=this.currentAttachedFile.fileName;let i="unknown";if(e){const t=e.toLowerCase();t.startsWith("cover.")?i="coverFront":t.startsWith("back.")&&(i="coverBack")}t.images??(t.images=[]),t.images.push({data:this.currentAttachedFile.fileData,mimeType:this.currentAttachedFile.fileMediaType,kind:i,name:this.currentAttachedFile.fileName??void 0,description:this.currentAttachedFile.fileDescription??void 0})}this.currentAttachedFile=null}break;case qr.FileUID:if(!this.currentAttachedFile)break;this.currentAttachedFile.fileUid=((e,t)=>{if(t<1)throw new Error("Bad unsigned int size "+t);let i=0n;for(let r=0;rt.order-e.order);break;case qr.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ta.Block,data:null},this.readContiguousElements(e.slice(s,a)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case qr.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=Gr(e,a);break;case qr.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=Gr(e,a);break;case qr.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:va.Zlib,settings:null},this.readContiguousElements(e.slice(s,a));break;case qr.ContentCompAlgo:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.algorithm=Gr(e,a);break;case qr.ContentCompSettings:if("decompress"!==this.currentDecodingInstruction?.data?.type)break;this.currentDecodingInstruction.data.settings=rc(e,a);break;case qr.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=s+a,!0}decodeBlockData(e,t){j(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(j(r.data),"decompress"===r.data.type)if(r.data.algorithm===va.HeaderStripping)if(r.data.settings&&r.data.settings.length>0){const e=r.data.settings,t=new Uint8Array(e.length+i.length);t.set(e,0),t.set(i,e.length),i=t}return i}processTagValue(e,t){var i;if(!this.currentSegment?.metadataTags)return;const r=this.currentSegment.metadataTags;if(r.raw??(r.raw={}),(i=r.raw)[e]??(i[e]=t),"string"===typeof t)switch(e.toLowerCase()){case"title":r.title??(r.title=t);break;case"description":r.description??(r.description=t);break;case"artist":r.artist??(r.artist=t);break;case"album":r.album??(r.album=t);break;case"album_artist":r.albumArtist??(r.albumArtist=t);break;case"genre":r.genre??(r.genre=t);break;case"comment":r.comment??(r.comment=t);break;case"lyrics":r.lyrics??(r.lyrics=t);break;case"date":{const e=new Date(t);Number.isNaN(e.getTime())||(r.date??(r.date=e))}break;case"track_number":case"part_number":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.trackNumber??(r.trackNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.tracksTotal??(r.tracksTotal=a))}break;case"disc_number":case"disc":{const e=t.split("/"),i=Number.parseInt(e[0],10),a=e[1]&&Number.parseInt(e[1],10);Number.isInteger(i)&&i>0&&(r.discNumber??(r.discNumber=i)),a&&Number.isInteger(a)&&a>0&&(r.discsTotal??(r.discsTotal=a))}}}async getDurationFromMetadata(e){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){j(r.trackBacking);const e=await r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(t??1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=t??0,i}}class Ba{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)}async getLiveRefreshInterval(){return null}async getFirstPacket(e){return this.performClusterLookup(null,e=>e.trackData.get(this.internalTrack.id)?{blockIndex:0,correctBlockFound:!0}:{blockIndex:-1,correctBlockFound:!1},-1/0,1/0,e)}intoTimescale(e){return Ce(e*this.internalTrack.segment.timestampFactor)}async getPacket(e,t){const i=this.intoTimescale(e);return this.performClusterLookup(null,e=>{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=pe(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=we(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 j(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)}async fetchPacketInCluster(e,t,i){if(-1===t)return null;const r=e.trackData.get(this.internalTrack.id).blocks[t];if(j(r),r.decoded||(r.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,r.data),r.decoded=!0),!r.postProcessed){if("prores"===this.internalTrack.info?.codec){if(!(r.data.length>=8&&105===r.data[4]&&99===r.data[5]&&112===r.data[6]&&102===r.data[7])){const e=new Uint8Array(r.data.length+8);J(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(r.data,8),r.data=e}}r.postProcessed=!0}const a=i.metadataOnly?rr:r.data,s=r.timestamp/this.internalTrack.segment.timestampFactor,n=r.duration/this.internalTrack.segment.timestampFactor,o={};r.mainAdditional&&"video"===this.internalTrack.info?.type&&this.internalTrack.info.alphaMode&&(o.alpha=i.metadataOnly?rr:r.mainAdditional,o.alphaByteLength=r.mainAdditional.byteLength);const c=new ar(a,r.isKeyFrame?"key":"delta",s,n,e.dataStartPos+t,r.data.byteLength,o);return this.packetToClusterLocation.set(c,{cluster:e,blockIndex:t}),c}async performClusterLookup(e,t,i,r,a){const{demuxer:s,segment:n}=this.internalTrack;let o=null,c=null,l=-1;if(e){const{blockIndex:i,correctBlockFound:r}=t(e);if(r)return this.fetchPacketInCluster(e,i,a);-1!==i&&(c=e,l=i)}const u=pe(this.internalTrack.cuePoints,i,e=>e.time),h=-1!==u?this.internalTrack.cuePoints[u]:null,d=pe(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),f=-1!==d?this.internalTrack.clusterPositionCache[d]:null,m=Math.max(h?.clusterPosition??0,f?.elementStartPos??0)||null;let p;for(e?null===m||e.elementStartPos>=m?(p=e.elementEndPos,o=e):p=m:p=m??n.clusterSeekStartPos;null===n.elementEndPos||p<=n.elementEndPos-2;){if(o){const e=o.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=s.reader.requestSliceRange(p,2,Kr);if(Xe(e)&&(e=await e),!e)break;const i=p,u=Jr(e);if(!u||!Vr.includes(u.id)&&u.id!==qr.Void){const e=await ra(s.reader,i,Vr,Math.min(n.elementEndPos??1/0,i+xa));if(e){p=e;continue}break}const h=u.id;let d=u.size;const f=e.filePos;if(h===qr.Cluster){o=await s.readCluster(i,n),d=o.elementEndPos-f;const{blockIndex:e,correctBlockFound:r}=t(o);if(r)return this.fetchPacketInCluster(o,e,a);-1!==e&&(c=o,l=e)}if(void 0===d){j(h!==qr.Cluster);d=(await ia(s.reader,f,jr,n.elementEndPos)).pos-f}const m=f+d;if(null===n.elementEndPos){let e=s.reader.requestSliceRange(m,2,Kr);if(Xe(e)&&(e=await e),!e)break;if(Qr(e)===qr.Segment){n.elementEndPos=m;break}}p=m}if(h&&(!c||c.elementStartPos{var e,t,i,r;let a=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(a=await this.getFirstPacket({}));const s={width:this.internalTrack.info.width,height:this.internalTrack.info.height,codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,colorSpace:this.internalTrack.info.colorSpace,avcType:1,avcCodecInfo:"avc"===this.internalTrack.info.codec&&a?Ft(a.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&a?Wt(a.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&a?ei(a.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&a?ii(a.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&a?ri(a.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!oe(this.internalTrack.info.colorSpace)){const a=Ui(s);(e=this.internalTrack.info.colorSpace).primaries??(e.primaries=a.primaries),(t=this.internalTrack.info.colorSpace).transfer??(t.transfer=a.transfer),(i=this.internalTrack.info.colorSpace).matrix??(i.matrix=a.matrix),(r=this.internalTrack.info.colorSpace).fullRange??(r.fullRange=a.fullRange)}const n={codec:zi(s),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:this.internalTrack.info.codecDescription??void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(n.displayAspectWidth=this.internalTrack.info.squarePixelWidth,n.displayAspectHeight=this.internalTrack.info.squarePixelHeight),n})()):null}}class _a extends Ba{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}async getDecoderConfig(){return this.internalTrack.info.codec?this.decoderConfigPromise??(this.decoderConfigPromise=(async()=>{if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=await this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&xi(e.data)}return{codec:qi({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:this.internalTrack.info.codecDescription??void 0}})()):null}}const Ra=async(e,t,i,r=null)=>{let a=t;for(;null===i||a=4;){const t=s.filePos,i=uc(s),n=null!==e.fileSize?e.fileSize-a:null,o=Yi(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&tr(o.header.channel)===tr(r.channel)))return{header:o.header,startPos:a};s.filePos=t+o.bytesAdvanced,a=s.filePos}}return null};class Fa extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Aa(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=await Ra(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=Qi(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(Xe(r)&&(r=await r),r){const a=uc(r);if(a===$i||a===Gi){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(Xe(t)&&(t=await t),t){const e=rc(t,12),i=J(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&Zi.FrameCount?i.getUint32(4,!1):null,fileSize:r&Zi.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);const a=t.audioSamplesInFrame/this.firstFrameHeader.sampleRate,s={timestamp:this.nextTimestampInSamples/this.firstFrameHeader.sampleRate,duration:a,dataStart:e.startPos,dataSize:t.totalSize};this.loadedSamples.push(s),this.nextTimestampInSamples+=t.audioSamplesInFrame}async getMimeType(){return"audio/mpeg"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0,t=!1;for(;;){let i=this.reader.requestSlice(e,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=!0;let a=this.reader.requestSlice(i.filePos,r.size);if(Xe(a)&&(a=await a),!a)break;Rc(a,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Ic){let e=this.reader.requestSlice(this.reader.fileSize-Ic,Ic);Xe(e)&&(e=await e),j(e);"TAG"===bc(e,3)&&Bc(e,this.metadataTags)}return this.metadataTags}finally{e()}}}class Aa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){const e=this.demuxer;if(j(null!==e.firstFrameHeader),j(null!==e.firstFrameHeaderPos),e.xingData){if(null!==e.xingData.frameCount)return e.xingData.frameCount*e.firstFrameHeader.audioSamplesInFrame/e.firstFrameHeader.sampleRate}else if(null!==e.reader.fileSize){const s=(t=e.firstFrameHeader.lowSamplingFrequency,i=e.firstFrameHeader.layer,r=e.firstFrameHeader.bitrate,a=e.firstFrameHeader.sampleRate,0===i?0:1===i?144*r/(a<e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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>>0&4294967295}const Na=e=>{const t=J(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let a=0;a>>24^t])>>>0}return t.setUint32(22,i,!0),r},Oa=(e,t,i)=>{let r=0,a=null;if(e.length>0)if("vorbis"===t.codec){j(t.vorbisInfo);const s=(1<<(e=>{let t=0;for(;e;)t++,e>>=1;return t})(t.vorbisInfo.modeBlockflags.length-1))-1<<1,n=(e[0]&s)>>1;if(n>=t.vorbisInfo.modeBlockflags.length)throw new Error("Invalid mode number.");let o=i;const c=t.vorbisInfo.modeBlockflags[n];if(a=t.vorbisInfo.blocksizes[c],1===c){const i=1+(1|s),r=e[0]&i?1:0;o=t.vorbisInfo.blocksizes[r]}r=null!==o?o+a>>2:0}else if("opus"===t.codec){r=(e=>{const t=e[0]>>3,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:ai[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:a}},La=27,za=282,Ua=e=>{const t=e.filePos;if(hc(e)!==Ma)return null;e.skip(1);const i=ac(e),r=gc(e),a=hc(e),s=hc(e),n=hc(e),o=ac(e),c=new Uint8Array(o);for(let h=0;he+t,0);return{headerStartPos:t,totalSize:l+u,dataStartPos:t+l,dataSize:u,headerType:i,granulePosition:r,serialNumber:a,sequenceNumber:s,checksum:n,lacingValues:c}},qa=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Ma)return!0;e.skip(1)}}return!1};class Wa extends ir{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=0;for(;;){let t=this.reader.requestSliceRange(e,La,za);if(Xe(t)&&(t=await t),!t)break;const i=Ua(t);if(!i)break;if(!!!(2&i.headerType))break;this.bitstreams.push({serialNumber:i.serialNumber,bosPage:i,description:null,numberOfChannels:-1,sampleRate:-1,codecInfo:{codec:null,vorbisInfo:null,opusInfo:null},lastMetadataPacket:null}),e=i.headerStartPos+i.totalSize}for(const t of this.bitstreams){const e=await this.readPacket(t.bosPage,0);e&&(e.data.byteLength>=7&&1===e.data[0]&&118===e.data[1]&&111===e.data[2]&&114===e.data[3]&&98===e.data[4]&&105===e.data[5]&&115===e.data[6]?await this.readVorbisMetadata(e,t):e.data.byteLength>=8&&79===e.data[0]&&112===e.data[1]&&117===e.data[2]&&115===e.data[3]&&72===e.data[4]&&101===e.data[5]&&97===e.data[6]&&100===e.data[7]&&await this.readOpusMetadata(e,t),null!==t.codecInfo.codec&&this.trackBackings.push(new Ha(t,this)))}})())}async readVorbisMetadata(e,t){let i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;if(i=await this.findNextPacketStart(r),!i)return;const a=await this.readPacket(i.startPage,i.startSegmentIndex);if(!a)return;if(3!==r.data[0]||5!==a.data[0])return;const s=[],n=e=>{for(;s.push(Math.min(255,e)),!(e<255);)e-=255};n(e.data.length),n(r.data.length);const o=new Uint8Array(1+s.length+e.data.length+r.data.length+a.data.length);o[0]=2,o.set(s,1),o.set(e.data,1+s.length),o.set(r.data,1+s.length+e.data.length),o.set(a.data,1+s.length+e.data.length+r.data.length),t.codecInfo.codec="vorbis",t.description=o,t.lastMetadataPacket=a;const c=J(e.data);t.numberOfChannels=c.getUint8(11),t.sampleRate=c.getUint32(12,!0);const l=c.getUint8(28);t.codecInfo.vorbisInfo={blocksizes:[1<<(15&l),1<<(l>>4)],modeBlockflags:si(a.data).modeBlockflags},li(r.data.subarray(7),this.metadataTags)}async readOpusMetadata(e,t){const i=await this.findNextPacketStart(e);if(!i)return;const r=await this.readPacket(i.startPage,i.startSegmentIndex);if(!r)return;t.codecInfo.codec="opus",t.description=e.data,t.lastMetadataPacket=r;const a=(e=>{const t=J(e),i=t.getUint8(9),r=t.getUint16(10,!0),a=t.getUint32(12,!0),s=t.getInt16(16,!0),n=t.getUint8(18);let o=null;return n&&(o=e.subarray(19,21+i)),{outputChannelCount:i,preSkip:r,inputSampleRate:a,outputGain:s,channelMappingFamily:n,channelMappingTable:o}})(e.data);t.numberOfChannels=a.outputChannelCount,t.sampleRate=Wi,t.codecInfo.opusInfo={preSkip:a.preSkip},li(r.data.subarray(8),this.metadataTags)}async readPacket(e,t){j(te+t.length,0);if(0===o)return null;const c=new Uint8Array(o);let l=0;for(let u=0;u{let t="audio/ogg";e.codecStrings&&(t+=`; codecs="${[...new Set(e.codecStrings)].join(", ")}"`);return t})({codecStrings:(await Promise.all(this.trackBackings.map(e=>e.getDecoderConfig().then(e=>e?.codec??null)))).filter(Boolean)})}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}class Ha{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new ue,this.internalSampleRate="opus"===e.codecInfo.codec?Wi:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return j(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}async getDecoderConfig(){return j(this.bitstream.codecInfo.codec),{codec:this.bitstream.codecInfo.codec,numberOfChannels:this.bitstream.numberOfChannels,sampleRate:this.bitstream.sampleRate,description:this.bitstream.description??void 0}}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht,primary:!1}}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(j(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:a}=Oa(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new ar(i.metadataOnly?rr:e.data,"key",Math.max(0,t.timestampInSamples)/this.internalSampleRate,r/this.internalSampleRate,e.endPage.headerStartPos+e.endSegmentIndex,e.data.byteLength);return this.encodedPacketToMetadata.set(s,{packet:e,timestampInSamples:t.timestampInSamples,durationInSamples:r,vorbisLastBlockSize:t.vorbisLastBlocksize,vorbisBlockSize:a}),s}async getFirstPacket(e){j(this.bitstream.lastMetadataPacket);const t=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(j(this.bitstream.codecInfo.opusInfo),i-=this.bitstream.codecInfo.opusInfo.preSkip);const r=await this.demuxer.readPacket(t.startPage,t.startSegmentIndex);return this.createEncodedPacketFromOggPacket(r,{timestampInSamples:i,vorbisLastBlocksize:null},e)}async getNextPacket(e,t){const i=this.encodedPacketToMetadata.get(e);if(!i)throw new Error("Packet was not created from this track.");const r=await this.demuxer.findNextPacketStart(i.packet);if(!r)return null;const a=i.timestampInSamples+i.durationInSamples,s=await this.demuxer.readPacket(r.startPage,r.startSegmentIndex);return this.createEncodedPacketFromOggPacket(s,{timestampInSamples:a,vorbisLastBlocksize:i.vorbisBlockSize},t)}async getPacket(e,t){if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const i=Ce(e*this.internalSampleRate);if(0===i)return this.getFirstPacket(t);if(i<0)return null;j(this.bitstream.lastMetadataPacket);const r=await this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!r)return null;let a=r.startPage,s=this.demuxer.reader.fileSize;const n=[a];e:for(;a.headerStartPos+a.totalSizei?s=l.headerStartPos:(a=l,n.push(l));continue e}r=l.headerStartPos+l.totalSize}}let o=r.startPage;for(const k of n){if(k.granulePosition===a.granulePosition)break;(!o||k.headerStartPos>o.headerStartPos)&&(o=k)}let c=o;const l=[c];for(;c.serialNumber!==this.bitstream.serialNumber||c.granulePosition!==a.granulePosition;){const e=c.headerStartPos+c.totalSize;let t=this.demuxer.reader.requestSliceRange(e,La,za);Xe(t)&&(t=await t),j(t);const i=Ua(t);j(i),c=i,c.serialNumber===this.bitstream.serialNumber&&l.push(c)}j(-1!==c.granulePosition);let u,h,d=null,f=c,m=0;if(c.headerStartPos===r.startPage.headerStartPos)u=this.granulePositionToTimestampInSamples(0),h=!0,d=0;else{u=0,h=!1;for(let t=c.lacingValues.length-1;t>=0;t--){if(c.lacingValues[t]<255){d=t+1;break}}if(null===d)throw new Error("Invalid page with granule position: no packets end on this page.");m=d-1;const e={data:rr,endPage:f,endSegmentIndex:m};if(await this.demuxer.findNextPacketStart(e)){const e=ja(l,c,d);j(e);const t=Va(l,e.page,e.segmentIndex);t&&(c=t.page,d=t.segmentIndex)}else for(;;){const e=ja(l,c,d);if(!e)break;const t=Va(l,e.page,e.segmentIndex);if(!t)break;if(c=t.page,d=t.segmentIndex,e.page.headerStartPos!==f.headerStartPos){f=e.page,m=e.segmentIndex;break}}}let p=null,g=null;for(;null!==c;){j(null!==d);const e=await this.demuxer.readPacket(c,d);if(!e)break;if(!(c.headerStartPos===r.startPage.headerStartPos&&di||Math.max(a.timestampInSamples,0)===i))break}const a=await this.demuxer.findNextPacketStart(e);if(!a)break;c=a.startPage,d=a.startSegmentIndex}return p}async getPacketSequential(e,t){const i=await this.sequentialScanMutex.acquire();try{const i=Ce(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=pe(this.sequentialScanCache,i,e=>e.timestampInSamples);let a;if(-1!==r){const e=this.sequentialScanCache[r];a=this.createEncodedPacketFromOggPacket(e.packet,{timestampInSamples:e.timestampInSamples,vorbisLastBlocksize:e.vorbisLastBlockSize},t)}else a=await this.getFirstPacket(t);let s=0;for(;a&&a.timestampe)break;if(a=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(a);j(e),this.sequentialScanCache.length>0&&j(X(this.sequentialScanCache).timestampInSamples<=e.timestampInSamples),this.sequentialScanCache.push(e)}}return a}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Va=(e,t,i)=>{let r=t,a=i;e:for(;;){for(a--;a>=0;a--){if(r.lacingValues[a]<255){a++;break e}}j(-1===a);if(!(1&r.headerType)){a=0;break}const t=be(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=be(e,e=>e.headerStartPos{let e=this.reader.requestSlice(0,12);Xe(e)&&(e=await e),j(e);const t=bc(e,4),i="RIFX"!==t,r="RF64"===t,a=lc(e,i);let s=r?this.reader.fileSize:Math.min(a+8,this.reader.fileSize??1/0);if("WAVE"!==bc(e,4))throw new Error("Invalid WAVE file - wrong format");let n=0,o=null,c=e.filePos;for(;null===s||c=18&&357!==a){const e=sc(r,i),s=t-18;if(Math.min(s,e)>=22&&a===Ka.EXTENSIBLE){r.skip(6);const e=rc(r,16);a=e[0]|e[1]<<8}}if(a!==Ka.MULAW&&a!==Ka.ALAW||(c=8),a!==Ka.PCM&&a!==Ka.IEEE_FLOAT&&a!==Ka.ALAW&&a!==Ka.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${a}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(a===Ka.PCM&&![8,16,24,32].includes(c))throw new Error(`Unsupported WAVE PCM bit depth (${c}). Only 8, 16, 24, and 32 bits are supported.`);if(a===Ka.IEEE_FLOAT&&![32,64].includes(c))throw new Error(`Unsupported WAVE float bit depth (${c}). Only 32 and 64 bits are supported.`);this.audioInfo={format:a,numberOfChannels:s,sampleRate:n,sampleSizeInBytes:Math.ceil(c/8),blockSizeInBytes:o}}async parseListChunk(e,t,i){var r,a,s,n,o,c,l,u,h,d,f;let m=this.reader.requestSlice(e,t);if(Xe(m)&&(m=await m),!m)return;const p=bc(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=bc(m,4),t=lc(m,i),p=rc(m,t);let k=0;for(let i=0;i0&&((c=this.metadataTags).trackNumber??(c.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&((l=this.metadataTags).tracksTotal??(l.tracksTotal=i))}break;case"ICRD":case"IDIT":{const e=new Date(y);Number.isNaN(e.getTime())||((u=this.metadataTags).date??(u.date=e))}break;case"YEAR":{const e=Number.parseInt(y,10);Number.isInteger(e)&&e>0&&((h=this.metadataTags).date??(h.date=new Date(e,0,1)))}break;case"IGNR":case"GENR":(d=this.metadataTags).genre??(d.genre=y);break;case"ICMT":case"CMNT":case"COMM":(f=this.metadataTags).comment??(f.comment=y)}g+=8+t+(1&t)}}async parseId3Chunk(e,t){let i=this.reader.requestSlice(e,t);if(Xe(i)&&(i=await i),!i)return;const r=_c(i);if(r){const a=t-xc;if(r.size=Math.min(r.size,a),r.size>0){const t=i.slice(e+xc,r.size);Rc(t,r,this.metadataTags)}}}getCodec(){if(j(this.audioInfo),this.audioInfo.format===Ka.MULAW)return"ulaw";if(this.audioInfo.format===Ka.ALAW)return"alaw";if(this.audioInfo.format===Ka.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===Ka.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}j(!1)}async getMimeType(){return"audio/wav"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){return await this.readMetadata(),this.metadataTags}}const Ga=2048;class Qa{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.format}async getDecoderConfig(){const e=this.demuxer.getCodec();return e?(j(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getDisposition(){return{...ht}}async getPacketAtIndex(e,t){j(e>=0),j(this.demuxer.audioInfo);const i=e*Ga*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(Ga*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(Xe(e)&&(e=await e),!e)return null}let a;if(t.metadataOnly)a=rr;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);Xe(e)&&(e=await e),j(e),a=rc(e,r)}const s=e*Ga/this.demuxer.audioInfo.sampleRate,n=r/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate;return this.demuxer.lastKnownPacketIndex=Math.max(e,this.demuxer.lastKnownPacketIndex),new ar(a,"key",s,n,e,r)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getPacket(e,t){j(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/Ga,(this.demuxer.dataSize-1)/(Ga*this.demuxer.audioInfo.blockSizeInBytes)));if(i<0)return null;const r=await this.getPacketAtIndex(i,t);if(r)return r;if(0===i)return null;j(null===this.demuxer.reader.fileSize);let a=await this.getPacketAtIndex(this.demuxer.lastKnownPacketIndex,t);for(;a;){const e=await this.getNextPacket(a,t);if(!e)break;a=e}return a}getNextPacket(e,t){j(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/Ga);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const Ya=e=>{const t=e.filePos,i=rc(e,9),r=new dt(i);if(4095!==r.readBits(12))return null;r.skipBits(1);if(0!==r.readBits(2))return null;const a=r.readBits(1),s=r.readBits(2)+1,n=r.readBits(4);if(15===n)return null;r.skipBits(1);const o=r.readBits(3);if(0===o)throw new Error("ADTS frames with channel configuration 0 are not supported.");r.skipBits(1),r.skipBits(1),r.skipBits(1),r.skipBits(1);const c=r.readBits(13);r.skipBits(11);const l=r.readBits(2)+1;if(1!==l)throw new Error("ADTS frames with more than one AAC frame are not supported.");let u=null;return 1===a?e.filePos-=2:u=r.readBits(16),{objectType:s,samplingFrequencyIndex:n,channelConfiguration:o,frameLength:c,numberOfAacFrames:l,crcCheck:u,startPos:t}},Ja=1024;class Za extends ir{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new ue,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)await this.advanceReader();j(this.firstFrameHeader),this.trackBackings=[new es(this)]})())}async advanceReader(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=_c(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const t=Ya(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=ft[t.samplingFrequencyIndex];j(void 0!==i);const r=Ja/i,a={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(a),this.nextTimestampInSamples+=Ja,this.lastLoadedPos=t.startPos+t.frameLength}async getMimeType(){return"audio/aac"}async getTrackBackings(){return await this.readMetadata(),this.trackBackings}async getMetadataTags(){const e=await this.readingMutex.acquire();try{if(await this.readMetadata(),this.metadataTags)return this.metadataTags;this.metadataTags={};let e=0;for(;;){let t=this.reader.requestSlice(e,xc);if(Xe(t)&&(t=await t),!t)break;const i=_c(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(Xe(r)&&(r=await r),!r)break;Rc(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}}}class es{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/Ja}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}getName(){return null}getLanguageCode(){return xe}getCodec(){return"aac"}getInternalCodecId(){return j(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){j(this.demuxer.firstFrameHeader);const e=mt[this.demuxer.firstFrameHeader.channelConfiguration];return j(void 0!==e),e}getSampleRate(){j(this.demuxer.firstFrameHeader);const e=ft[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return j(void 0!==e),e}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}}async getPacketAtIndex(e,t){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.dataSize)}return new ar(r,"key",i.timestamp,i.duration,e,i.dataSize)}getFirstPacket(e){return this.getPacketAtIndex(0,e)}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=me(this.demuxer.loadedSamples,e.timestamp,e=>e.timestamp);if(-1===i)throw new Error("Packet was not created from this track.");const r=i+1;for(;r>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(r,t)}finally{i()}}async getPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(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{var e;let t=0;for(;;){let e=this.reader.requestSlice(t,xc);if(Xe(e)&&(e=await e),!e)return void(this.lastSampleLoaded=!0);const i=_c(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);Xe(r)&&(r=await r),j(r),Rc(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:s.end-e,isLastFrame:!0};if(255===ac(s)){const t=s.filePos;if(ac(s)!==(1===this.blockingBit?249:248)){s.filePos=t;continue}s.skip(-2);const i=s.filePos-e,r=this.readFlacFrameHeader({slice:s,isFirstPacket:!1});if(!r){s.filePos=t;continue}if(0===this.blockingBit){if(r.num-n.num!==1){s.filePos=t;continue}}else if(r.num-n.num!==n.blockSize){s.filePos=t;continue}return{num:n.num,blockSize:n.blockSize,sampleRate:n.sampleRate,size:i,isLastFrame:!1}}}}readFlacFrameHeader({slice:e,isFirstPacket:t}){const i=e.filePos,r=rc(e,4),a=new dt(r);if(32764!==a.readBits(15))return null;if(null===this.blockingBit){j(t);const e=a.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){j(!t);if(1!==a.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");j(!t);if(0!==a.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*2**e:6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?2**e:null)(a.readBits(4));if(!s)return null;j(this.audioInfo);const n=((e,t)=>{switch(e){case 0:return t;case 1:return 88200;case 2:return 176400;case 3:return 192e3;case 4:return 8e3;case 5:return 16e3;case 6:return 22050;case 7:return 24e3;case 8:return 32e3;case 9:return 44100;case 10:return 48e3;case 11:return 96e3;case 12:return"uncommon-u8";case 13:return"uncommon-u16";case 14:return"uncommon-u16-10";default:return null}})(a.readBits(4),this.audioInfo.sampleRate);if(!n)return null;a.readBits(4),a.readBits(3);if(0!==a.readBits(1))return null;const o=(e=>{let t=0;const i=new dt(rc(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],a=t-1,s=new dt(rc(e,a)),n=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?nc(e)+1:"uncommon-u8"===t?ac(e)+1:"number"===typeof t?t:(Te(t),void j(!1)))(e,s),l=((e,t)=>"uncommon-u16"===t?nc(e):"uncommon-u16-10"===t?10*nc(e):"uncommon-u8"===t?ac(e):"number"===typeof t?t:null)(e,n);if(null===l)return null;if(l!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,h=ac(e);e.skip(-u),e.skip(-1);const d=(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})(rc(e,u));return h!==d?null:{num:o,blockSize:c,sampleRate:l}}async advanceReader(){await this.readMetadata(),j(null!==this.lastLoadedPos),j(this.audioInfo);const e=this.lastLoadedPos,t=await this.readNextFlacFrame({startPos:e,isFirstPacket:0===this.loadedSamples.length});if(!t)return void(this.lastSampleLoaded=!0);const i=this.loadedSamples[this.loadedSamples.length-1],r={blockOffset:i?i.blockOffset+i.blockSize:0,blockSize:t.blockSize,byteOffset:e,byteSize:t.size};this.lastLoadedPos=this.lastLoadedPos+t.size,this.loadedSamples.push(r),t.isLastFrame&&(this.lastSampleLoaded=!0)}}class is{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return xe}getTimeResolution(){return j(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return j(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate}async getLiveRefreshInterval(){return null}getDisposition(){return{...ht}}async getDecoderConfig(){return j(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}}async getPacket(e,t){if(j(this.demuxer.audioInfo),e<0)return null;const i=await this.demuxer.readingMutex.acquire();try{for(;;){const i=pe(this.demuxer.loadedSamples,e,e=>e.blockOffset/this.demuxer.audioInfo.sampleRate);if(-1===i){await this.demuxer.advanceReader();continue}const r=this.demuxer.loadedSamples[i],a=r.blockOffset/this.demuxer.audioInfo.sampleRate;if(!(a+r.blockSize/this.demuxer.audioInfo.sampleRate<=e))return this.getPacketAtIndex(i,t);if(this.demuxer.lastSampleLoaded)return this.getPacketAtIndex(this.demuxer.loadedSamples.length-1,t);await this.demuxer.advanceReader()}}finally{i()}}async getNextPacket(e,t){const i=await this.demuxer.readingMutex.acquire();try{const i=e.sequenceNumber+1;if(this.demuxer.lastSampleLoaded&&i>=this.demuxer.loadedSamples.length)return null;for(;i>=this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(i,t)}finally{i()}}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}async getPacketAtIndex(e,t){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=rr;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(Xe(e)&&(e=await e),!e)return null;r=rc(e,i.byteSize)}j(this.demuxer.audioInfo);const a=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new ar(r,"key",a,s,e,i.byteSize)}async getFirstPacket(e){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)await this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)}}const rs=9e4,as=2**33,ss=188,ns="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.",os=new Set([133,134,162]),cs=new Set;class ls extends ir{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}async readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{let e=this.reader.requestSlice(0,205);Xe(e)&&(e=await e),j(e);const t=rc(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ss;else if(71===t[0]&&71===t[204])this.packetOffset=0,this.packetStride=204;else{if(71!==t[4]||71!==t[196])throw new Error("Unreachable.");this.packetOffset=4,this.packetStride=192}this.minReferencePointByteDistance=256*this.packetStride;let i=this.packetOffset,r=null,a=!1,s=!1;for(;;){const e=await this.readPacketHeader(i);if(!e)break;if(0===e.payloadUnitStartIndicator){i+=this.packetStride;continue}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){i+=this.packetStride;continue}const t=await this.readSection(i,!0,!s);if(!t)break;const n=3,o=32;let c=!1;if(!s&&0!==t.pid){if(!(0===t.payload[0]&&0===t.payload[1]&&1===t.payload[2])){const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i);c=2===e.readBits(8)}}if(0!==t.pid||a)if(t.pid!==r&&!c||s){const e=this.elementaryStreams.find(e=>e.pid===t.pid);e:if(e&&!e.initialized){const i=hs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(await this.input._initInput._getDemuxer()).elementaryStreams.find(i=>i.pid===t.pid&&i.info.codec===e.info.codec);if(i){e.info=i.info,e.initialized=!0;break e}}const r=new gs(e,i);if("video"===e.info.type){for(;;){if(r.suppliedPacket=null,await r.markNextPacket(),"avc"===e.info.codec){if(!r.suppliedPacket)throw new Error("Invalid AVC video stream; could not extract AVCDecoderConfigurationRecord from any packet.");if(e.info.avcCodecInfo=Ft(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];j(t);const i=Nt(t);e.info.width=i.displayWidth,e.info.height=i.displayHeight;const a=i.pixelAspectRatio.num,s=i.pixelAspectRatio.den;a>0&&s>0&&(a>s?(e.info.squarePixelWidth=Math.round(e.info.width*a/s),e.info.squarePixelHeight=e.info.height):(e.info.squarePixelWidth=e.info.width,e.info.squarePixelHeight=Math.round(e.info.height*s/a))),e.info.colorSpace={primaries:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[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=Wt(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===St.SPS_NUT).nalUnits[0];j(t);const i=qt(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:ie[i.colourPrimaries],transfer:ae[i.transferCharacteristics],matrix:ne[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:zi({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(await r.markNextPacket(),!r.suppliedPacket)throw new Error(`Couldn't parse first media packet for Elementary Stream with PID ${e.pid}`);if("aac"===e.info.codec){const t=tc.tempFromBytes(r.suppliedPacket.data),i=Ya(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=mt[i.channelConfiguration],e.info.sampleRate=ft[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=uc(tc.tempFromBytes(r.suppliedPacket.data)),i=Yi(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=tr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=hi(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=ui[t.acmod]+t.lfeon,e.info.sampleRate=yt[t.fscod]}else if("eac3"===e.info.codec){const t=mi(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=pi(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=gi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=Ii(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:qi({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(12);const r=e.readBits(12);e.skipBits(43),e.readBits(13),e.skipBits(6);const a=e.readBits(10),c=e.pos+8*a;let l=!1;for(;e.pos=4){const t=e.readBits(32);l||(l=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=c;8*(r+n)-e.pos>o;){const t=e.readBits(8);e.skipBits(3);const i=e.readBits(13);e.skipBits(6);const r=e.readBits(10),a=e.pos+8*r;let s=!1,n=!1,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let c=null;const u=l&&os.has(t)?130:t;switch(u){case 27:case 36:c={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",c={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:n?c={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?c={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(c={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:cs.has(t)||(ct._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),cs.add(t))}c&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:c,referencePesPackets:[]})}s=!0}else{const e=new dt(t.payload),i=e.readAlignedByte();e.skipBits(8*i),e.skipBits(14);const s=e.readBits(10);for(e.skipBits(40);8*(s+n)-e.pos>o;){const t=e.readBits(16);e.skipBits(3);const i=e.readBits(13);if(0!==t){if(null!==r)throw new Error("Only files with a single program are supported.");r=i}}if(null===r)throw new Error("Program Association Table must link to a Program Map Table.");a=!0}if(s&&this.elementaryStreams.every(e=>e.initialized))break;i+=this.packetStride}if(!s){if(!a)throw new Error("No Program Association Table found in the file.");throw new Error("No Program Map Table found in the file.")}for(const n of this.elementaryStreams)n.initialized&&("video"===n.info.type?this.trackBackingEntries.push(new fs(n)):this.trackBackingEntries.push(new ms(n)))})())}async getTrackBackings(){return await this.readMetadata(),this.trackBackingEntries}async getMetadataTags(){return{}}async getMimeType(){await this.readMetadata();return(e=>{let t="video/MP2T";const i=[...new Set(e.filter(Boolean))];return i.length>0&&(t+=`; codecs="${i.join(", ")}"`),t})(await Promise.all(this.trackBackingEntries.map(e=>e.getDecoderConfig().then(e=>e?.codec??null))))}async readSection(e,t,i=!1){let r=e,a=e;const s=[];let n,o=0,c=null,l=!0,u=0;for(;;){const e=await this.readPacket(a);if(a+=this.packetStride,!e)break;if(c){if(e.pid!==c.pid){if(i)break;continue}if(1===e.payloadUnitStartIndicator)break}else{if(0===e.payloadUnitStartIndicator)break;c=e}const n=!!(2&e.adaptationFieldControl),h=!!(1&e.adaptationFieldControl);let d=0;if(n&&(d=1+e.body[0],e===c&&d>1&&(u=e.body[1]>>6&1)),h&&(0===d?(s.push(e.body),o+=e.body.byteLength):(s.push(e.body.subarray(d)),o+=e.body.byteLength-d)),r=a,!t&&o>=64){l=!1;break}if(-1!==me(this.sectionEndPositions,r,e=>e)){l=!1;break}}if(l){const e=pe(this.sectionEndPositions,r,e=>e);this.sectionEndPositions.splice(e+1,0,r)}if(!c)return null;if(1===s.length)n=s[0];else{const e=s.reduce((e,t)=>e+t.length,0);n=new Uint8Array(e);let t=0;for(const i of s)n.set(i,t),t+=i.length}return{startPos:e,endPos:t?r:null,pid:c.pid,payload:n,randomAccessIndicator:u}}async readPacketHeader(e){let t=this.reader.requestSlice(e,4);if(Xe(t)&&(t=await t),!t)return null;if(71!==ac(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=nc(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:ac(t)>>4&3}}async readPacket(e){let t=this.reader.requestSlice(e,ss);if(Xe(t)&&(t=await t),!t)return null;const i=rc(t,ss);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=as-t?-8589934592:as}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new dt(t.payload);if(1!==r.readBits(24))return null;const a=r.readBits(8);if(r.skipBits(16),188===a||190===a||191===a||240===a||241===a||255===a||242===a||248===a)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let n=null;if(2===s||3===s)n=0,r.skipBits(4),n+=r.readBits(3)*(1<<30),r.skipBits(1),n+=32768*r.readBits(15),r.skipBits(1),n+=r.readBits(15),n=e.normalizeTimestamp(n);else if(i)throw new Error(ns);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:n,randomAccessIndicator:t.randomAccessIndicator}},hs=(e,t,i)=>{j(null!==t.endPos);const r=us(e,t,i);if(!r)return null;const a=new dt(t.payload);a.skipBits(32);const s=a.readBits(16);a.skipBits(16);const n=a.readBits(8),o=a.pos+8*n;a.pos=o;const c=o/8;j(Number.isInteger(c));const l=t.payload.subarray(c,s>0?6+s:t.payload.byteLength);return{...r,data:l}};class ds{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++,j(r instanceof ds),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 xe}getDisposition(){return{...ht,primary:!1}}getTimeResolution(){return rs}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return 1n}getBitrate(){return null}getAverageBitrate(){return null}async getDurationFromMetadata(){return null}async getLiveRefreshInterval(){return null}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new ar(i.metadataOnly?rr:e.data,r,e.pts/rs,Math.max(t/rs,0),e.sequenceNumber,e.data.byteLength)}async getFirstPacket(e){const t=this.elementaryStream.firstSection;j(t);const i=hs(this.elementaryStream.demuxer,t,!0);j(i);const r=new gs(this.elementaryStream,i),a=new ks(this,r),s=await a.readNext();if(!s)return null;const n=this.createEncodedPacket(s.packet,s.duration,e);return this.packetBuffers.set(n,a),this.packetSectionStarts.set(n,s.packet.sectionStartPos),n}async getNextPacket(e,t){let i=this.packetBuffers.get(e);if(i){const r=await i.readNext();if(!r)return null;this.packetBuffers.delete(e);const a=this.createEncodedPacket(r.packet,r.duration,t);return this.packetBuffers.set(a,i),this.packetSectionStarts.set(a,r.packet.sectionStartPos),a}const r=this.packetSectionStarts.get(e);if(void 0===r)throw new Error("Packet was not created from this track.");const a=this.elementaryStream.demuxer,s=await a.readSection(r,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n);i=new ks(this,o);const c=e.sequenceNumber;for(;;){const e=await i.readNext();if(!e)return null;if(e.packet.sequenceNumber>c){const r=this.createEncodedPacket(e.packet,e.duration,t);return this.packetBuffers.set(r,i),this.packetSectionStarts.set(r,e.packet.sectionStartPos),r}}}async getNextKeyPacket(e,t){let i=e;for(;;){if(i=await this.getNextPacket(i,t),!i)return null;if("key"===i.type)return i}}getPacket(e,t){return this.doPacketLookup(e,!1,t)}getKeyPacket(e,t){return this.doPacketLookup(e,!0,t)}async doPacketLookup(e,t,i){const r=Ce(e*rs),a=this.elementaryStream.demuxer,{reader:s,seekChunkSize:n}=a,o=this.elementaryStream.pid,c=async(e,t,i)=>{let r=e;for(;re.pts),m=-1!==f?d[f]:null;if(m&&r-m.pts<45e3)h=m.sectionStartPos;else{let e=0;if(null!==s.fileSize){const t=Math.ceil(s.fileSize/n);if(t>1){let i=0,s=t-1;for(e=i;i<=s;){const t=Math.floor((i+s)/2),o=_e(t*n,a.packetStride)+u.sectionStartPos,l=o+n,h=await c(o,l,!1);h?h.pesPacketHeader.pts<=r?(e=t,i=t+1):s=t-1:s=t-1}}}h=_e(e*n,a.packetStride)+u.sectionStartPos}const p=await c(h,s.fileSize??1/0,!1);let g=p?.pesPacketHeader??null;g||(g=u);const k=this.getReorderSize(),y=async(e,t)=>{const s=await a.readSection(e,!0);j(s);const n=hs(a,s,!0);j(n);const o=new gs(this.elementaryStream,n),c=new ks(this,o);for(;;){if((X(c.presentationOrderPackets)?.pts??-1/0)>=r)break;if(!(await c.readNextPacket()))break}const l=we(c.presentationOrderPackets,t);if(-1===l)return null;const u=c.presentationOrderPackets[l],h=0===l?0:u.pts-c.presentationOrderPackets[l-1].pts;for(;c.decodeOrderPackets[0]!==u;)c.decodeOrderPackets.shift();c.lastDuration=h;const d=await c.readNext();j(d);const f=this.createEncodedPacket(d.packet,d.duration,i);return this.packetBuffers.set(f,c),this.packetSectionStarts.set(f,d.packet.sectionStartPos),f};if(!t||this.allPacketsAreKeyPackets()){e:for(;;){let e=g.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){if(e.pts>r)break e;g=e,ps(this.elementaryStream,g);break}}}e+=a.packetStride}}e:for(let e=0;e=a.packetOffset;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,!1);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){g=e;break}}}e-=a.packetStride}}return y(g.sectionStartPos,e=>e.pts<=r)}{let e=h,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let h=null;const d=e<=u.sectionStartPos;let f,m=null;if(d)f=u,m=l;else{const t=await c(e,s.fileSize??1/0,i);f=t?.pesPacketHeader??null,m=t?.section??null}let p=!1,g=0;e:for(;f&&!(null!==t&&f.sectionStartPos>=t);){if(f.pts<=r){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===f.randomAccessIndicator;else{j(m);const t=hs(a,m,!0);j(t);const i=new gs(this.elementaryStream,t);await i.markNextPacket(),e=1===i.suppliedPacket?.randomAccessIndicator}e&&(h=f)}if(f.pts>r&&(p=!0),p&&(g++,g>k))break;let e=f.sectionStartPos+a.packetStride;for(;;){const t=await a.readPacketHeader(e);if(!t)break e;if(t.pid===o&&1===t.payloadUnitStartIndicator){const t=await a.readSection(e,i);if(t){const e=us(a,t,!1);if(e&&null!==e.pts){f=e,m=t,ps(this.elementaryStream,f);break}}}e+=a.packetStride}}if(h){let e=h;if(0===g)e:for(let r=0;r=a.packetOffset;){const r=await a.readPacketHeader(t);if(!r)break e;if(r.pid===o&&1===r.payloadUnitStartIndicator){const r=await a.readSection(t,i);if(r){const t=us(a,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=a.packetStride}}const t=await y(e.sectionStartPos,e=>e.pts<=r&&1===e.randomAccessIndicator);return j(t),t}if(d)return null;t=e,e=Math.max(_e(e-u.sectionStartPos-n,a.packetStride)+u.sectionStartPos,u.sectionStartPos)}}}}class fs extends ds{getType(){return"video"}getCodec(){return this.elementaryStream.info.codec}getCodedWidth(){return this.elementaryStream.info.width}getCodedHeight(){return this.elementaryStream.info.height}getSquarePixelWidth(){return this.elementaryStream.info.squarePixelWidth}getSquarePixelHeight(){return this.elementaryStream.info.squarePixelHeight}getRotation(){return 0}async getColorSpace(){return this.elementaryStream.info.colorSpace}async canBeTransparent(){return!1}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class ms extends ds{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}async getDecoderConfig(){return j(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const ps=(e,t)=>{const i=e.referencePesPackets,r=pe(i,t.sectionStartPos,e=>e.sectionStartPos);if(r>=0){const a=i[r];if(t.pts<=a.pts)return!1;const s=e.demuxer.minReferencePointByteDistance;if(t.sectionStartPos-a.sectionStartPos=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return j(e),e}async bufferData(e){const t=this.endPos+e;for(;this.endPos=l)break;u=e;const i=o+u;if(u+3>=l){this.seekTo(i);break}const h=c[u+1],d=c[u+2],f=c[u+3];let m=0;if(0===h&&0===d&&1===f?m=4:0===h&&1===d&&(m=3),0===m){u++;continue}const p=i;a??(a=p);const g=u+m,k=g+r,y=6;if(k+("avc"===t?y:1)>l){this.seekTo(i);break}const b=c[g];let w,T,S;if("avc"===t)w=Ct(b),T=w===wt.NON_IDR_SLICE||w===wt.SLICE_DPA||w===wt.IDR,S=w===wt.SEI||w===wt.SPS||w===wt.PPS||w===wt.AUD;else{w=Ut(b);if(((1&b)<<5|c[g+1]>>3)>0){u+=m;continue}T=w<=St.RASL_R||w>=St.BLA_W_LP&&w<=21,S=w>=St.VPS_NUT&&w<=37||w===St.PREFIX_SEI_NUT||w>=41&&w<=44||w>=48&&w<=55}let v=!1;if(T){let e;if("avc"===t){const t=c.subarray(k,k+y),i=$(new dt(t));e=!s||i<=n,n=i}else e=c[k]>>7===1;e&&(s?v=!0:s=!0)}else S&&s&&(v=!0);if(v){const e=p-a;return this.seekTo(a),this.supplyPacket(e,0)}u+=m}if(ea){const e=this.endPos-a;return this.seekTo(a),this.supplyPacket(e,0)}}else{const t=e.info.codec,i=128;for(;;){let r=this.ensureBuffered(i);Xe(r)&&(r=await r);const a=this.currentPos;for(;this.currentPos-a>6,n=63&a[4];if(3===s||n>37){this.seekTo(t+1);continue}const o=di[3*n+s];j(void 0!==o),this.seekTo(t),r=this.ensureBuffered(o),Xe(r)&&(r=await r);const c=Math.round(13824e4/e.info.sampleRate);return this.supplyPacket(r,c)}if("eac3"===t){if(11!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(5);if(Xe(r)&&(r=await r),r<5)return;const a=this.readBytes(5);if(11!==a[0]||119!==a[1]){this.seekTo(t+1);continue}const s=2*(((7&a[2])<<8|a[3])+1),n=3===a[4]>>6?3:a[4]>>4&3,o=fi[n];this.seekTo(t),r=this.ensureBuffered(s),Xe(r)&&(r=await r);const c=256*o,l=Math.round(c*rs/e.info.sampleRate);return this.supplyPacket(r,l)}if("dts"===t){if(127!==i&&100!==i)continue;this.skip(-1);const t=this.currentPos;let r=this.ensureBuffered(18);if(Xe(r)&&(r=await r),r<18)return;const a=this.readBytes(18),s=Ci(a);let n=s?null:Bi(a);if(!s&&!n){this.seekTo(t+1);continue}if(n&&!n.asset){this.seekTo(t);const e=Math.min(n.frameSize,4096);let i=this.ensureBuffered(e);Xe(i)&&(i=await i),n=Bi(this.readBytes(i))??n}let o=s?s.frameSize:n.frameSize;if(s){let e=4*Math.ceil(s.frameSize/4);for(;;){this.seekTo(t);const i=e+10;let r=this.ensureBuffered(i);if(Xe(r)&&(r=await r),r=0)}async readNext(){if(0===this.decodeOrderPackets.length){if(!(await this.readNextPacket()))return null}await this.ensureCurrentPacketHasNext();const e=this.decodeOrderPackets[0],t=this.presentationOrderPackets.indexOf(e);let i;if(j(-1!==t),t===this.presentationOrderPackets.length-1)i=this.lastDuration;else{i=this.presentationOrderPackets[t+1].pts-e.pts,this.lastDuration=i}for(this.decodeOrderPackets.shift();this.presentationOrderPackets.length>0;){const e=this.presentationOrderPackets[0];if(this.decodeOrderPackets.includes(e))break;this.presentationOrderPackets.shift()}return{packet:e,duration:i}}async readNextPacket(){if(this.reachedEnd)return!1;let e;return this.context.suppliedPacket||await this.context.markNextPacket(),e=this.context.suppliedPacket,this.context.suppliedPacket=null,e?(this.decodeOrderPackets.push(e),this.processPacketThroughReorderBuffer(e),!0):(this.reachedEnd=!0,this.flushReorderBuffer(),!1)}async ensureCurrentPacketHasNext(){const e=this.decodeOrderPackets[0];for(j(e);;){const t=this.presentationOrderPackets.indexOf(e);if(-1!==t&&t<=this.presentationOrderPackets.length-2)break;if(!(await this.readNextPacket()))break}}processPacketThroughReorderBuffer(e){if(this.reorderBuffer.push(e),this.reorderBuffer.length>this.reorderSize){let e=0;for(let i=1;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const ys="application/vnd.apple.mpegurl",bs="#EXT-X-STREAM-INF:",ws="#EXT-X-I-FRAME-STREAM-INF:",Ts="#EXT-X-MEDIA:",Ss="#EXTINF:",vs="#EXT-X-MAP:",Ps="#EXT-X-KEY:",Is="#EXT-X-MEDIA-SEQUENCE:",xs="#EXT-X-BYTERANGE:",Cs="#EXT-X-PROGRAM-DATE-TIME:",Bs="#EXT-X-TARGETDURATION:",Es="#EXT-X-PLAYLIST-TYPE:",_s=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class Rs{constructor(e){this._attributes={};let t="",i="",r=!1,a=!1;for(let s=0;s{const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,t,i))}else if("audio"===t.type){const i=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,t,i))}}else{if(this.firstSegment=await this.getFirstSegment({}),!this.firstSegment)return[];const t=this.getInputForSegment(this.firstSegment),i=await t.getTracks();for(const r of i)if("video"===r.type){const t=et(e,e=>"video"===e.getType())+1;e.push(new Ms(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=et(e,e=>"audio"===e.getType())+1;e.push(new Ds(this,{id:e.length+1,type:"audio"},t))}}return e})())}async getFirstTimestampForInput(e){const t=this.firstTimestampCache.get(e);if(void 0!==t)return t;const i=await e.getFirstTimestamp();return this.firstTimestampCache.set(e,i),i}async getMediaOffset(e,t){const i=e.firstSegment??e;let r;if(this.firstSegmentFirstTimestamps.has(i))r=this.firstSegmentFirstTimestamps.get(i);else{const e=this.getInputForSegment(i);r=await this.getFirstTimestampForInput(e),this.firstSegmentFirstTimestamps.set(i,r)}if(i===e)return i.timestamp-r;const a=await this.getFirstTimestampForInput(t),s=e.timestamp-i.timestamp,n=a-r-s;return Math.abs(n)<=Math.min(.25,s)?i.timestamp-r:e.timestamp-a}dispose(){for(const e of this.inputCache)e.input.dispose();this.inputCache.length=0}}class As{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{var e;if((e=this.segmentedInput).firstSegment??(e.firstSegment=await this.segmentedInput.getFirstSegment({})),!this.segmentedInput.firstSegment)throw new Error("Missing first segment, can't retrieve track.");let t=this.segmentedInput.firstSegment,i=null;for(;t;){const e=this.segmentedInput.getInputForSegment(t);if(i=(await e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number)??null,i)break;t=await this.segmentedInput.getNextSegment(t,{})}if(!i)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=i,this.firstSegment=t})())}getId(){return this.decl.id}getType(){return this.decl.type}getNumber(){return this.number}delegate(e){return this.firstInputTrack?e():this.hydrate().then(e)}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}getHasOnlyKeyPackets(){return this.delegate(()=>this.firstInputTrack._backing.getHasOnlyKeyPackets?.()??null)}getPairingMask(){return 1n}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getInternalCodecId(){return this.delegate(()=>this.firstInputTrack._backing.getInternalCodecId())}getDisposition(){return this.delegate(()=>this.firstInputTrack._backing.getDisposition())}getLanguageCode(){return this.delegate(()=>this.firstInputTrack._backing.getLanguageCode())}getName(){return this.delegate(()=>this.firstInputTrack._backing.getName())}getTimeResolution(){return this.delegate(()=>this.firstInputTrack._backing.getTimeResolution())}async isRelativeToUnixEpoch(){return await this.hydrate(),j(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}async createAdjustedPacket(e,t,i){j(e.sequenceNumber>=0),j(this.segmentedInput.firstSegment);const r=await this.segmentedInput.getMediaOffset(t,i.input),a=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:Ee(e.timestamp+r,await i.getTimeResolution()),sequenceNumber:Math.floor(1e8*a)+e.sequenceNumber});return this.packetInfos.set(s,{segment:t,track:i,sourcePacket:e}),s}async getFirstPacket(e){await this.hydrate(),j(this.firstInputTrack),j(this.firstSegment);let t=this.firstInputTrack,i=this.firstSegment;for(;;){if(t){const r=await t._backing.getFirstPacket(e);if(r)return this.createAdjustedPacket(r,i,t)}if(i=await this.segmentedInput.getNextSegment(i,{skipLiveWait:e.skipLiveWait}),!i)break;const r=this.segmentedInput.getInputForSegment(i);t=(await r.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number)??null}return null}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}async _getNextInternal(e,t,i){const r=this.packetInfos.get(e);if(!r)throw new Error("Packet was not created from this track.");const a=i?await r.track._backing.getNextKeyPacket(r.sourcePacket,t):await r.track._backing.getNextPacket(r.sourcePacket,t);if(a)return this.createAdjustedPacket(a,r.segment,r.track);let s=r.segment;for(;;){const e=await this.segmentedInput.getNextSegment(s,{skipLiveWait:t.skipLiveWait});if(!e)return null;const i=this.segmentedInput.getInputForSegment(e),a=(await i.getTracks()).find(e=>e.type===r.track.type&&e.number===r.track.number);if(!a){s=e;continue}const n=await a._backing.getFirstPacket(t);return n?this.createAdjustedPacket(n,e,a):null}}getPacket(e,t){return this._getPacketInternal(e,t,!1)}getKeyPacket(e,t){return this._getPacketInternal(e,t,!0)}async _getPacketInternal(e,t,i){let r=await this.segmentedInput.getSegmentAt(e,{skipLiveWait:t.skipLiveWait});if(!r)return null;for(await this.hydrate();r;){const a=this.segmentedInput.getInputForSegment(r),s=(await a.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number);if(!s){r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait});continue}const n=e-await this.segmentedInput.getMediaOffset(r,a),o=i?await s._backing.getKeyPacket(n,t):await s._backing.getPacket(n,t);if(o)return this.createAdjustedPacket(o,r,s);r=await this.segmentedInput.getPreviousSegment(r,{skipLiveWait:t.skipLiveWait})}return null}}class Ms extends As{getType(){return"video"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getCodedWidth(){return this.delegate(()=>this.firstInputTrack._backing.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.firstInputTrack._backing.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.firstInputTrack._backing.getSquarePixelHeight())}getRotation(){return this.delegate(()=>this.firstInputTrack._backing.getRotation())}async getColorSpace(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())}async canBeTransparent(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}class Ds extends As{getType(){return"audio"}getCodec(){return this.delegate(()=>this.firstInputTrack._backing.getCodec())}getNumberOfChannels(){return this.delegate(()=>this.firstInputTrack._backing.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.firstInputTrack._backing.getSampleRate())}async getDecoderConfig(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())}}Ye();const Ns=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class Os extends st{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}async getSizeOrNull(){if(this._disposed)throw new Zo;return this._sizePromise??(this._sizePromise=(async()=>{let e=this._getFileSize();return void 0!==e||(await this._read(0,1,0,Ns),e=this._getFileSize(),j(void 0!==e)),e})())}async getSize(){if(this._disposed)throw new Zo;const e=await this.getSizeOrNull();if(null===e)throw new Error("Cannot determine the size of an unsized source.");return e}slice(e,t){if(!Number.isInteger(e)||e<0)throw new TypeError("offset must be a non-negative integer.");if(void 0!==t&&(!Number.isInteger(t)||t<0))throw new TypeError("length, when provided, must be a non-negative integer.");return new Js(this,e,t)}_dispatchRead(e,t){this.onread?.(e,t),this._emit("read",{start:e,end:t})}ref(){return new Ls(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class Ls{constructor(e){if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),e._refFinalizationRegistry?.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const e=this.source;j(e._refCount>0),e._decrementRefCount(),e._refFinalizationRegistry?.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class zs extends Os{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 Os||e instanceof Ls))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof Os?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return Xe(t)?t.then(i):i(t)}}const Us=(e,t)=>e.path===t.path;class qs extends zs{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 Os?e.ref():e;return this._root=t,this._rootRequest=null,t};Xe(e)?this._rootRequest=e.then(t):(t(e),j(this._root))}if(this._rootRequest)return this._rootRequest.then(a=>a.source._read(e,t,i,r))}return this._root.source._read(e,t,i,r)}_getFileSize(){if(this._root)return this._root.source._getFileSize()}_dispose(){this._root?this._root.free():this._rootRequest&&this._rootRequest.then(e=>e.free())}}const Ws="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class Hs extends Os{constructor(e,t={}){if(!(e instanceof Blob))throw new TypeError("blob must be a Blob.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??8388608,maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),Ws?.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:Qs.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}async _runWorker(e){j(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!Ue()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),Ws?.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch{}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return ct._warn("Request will not be retried because a CORS error was suspected due to different origins. You can modify this behavior by providing your own function for the 'getRetryDelay' option."),null}return Math.min(2**(e-2),16)},js=new Set;class Ks extends zs{constructor(e,t={}){if("string"!==typeof e&&!(e instanceof URL)&&!("undefined"!==typeof Request&&e instanceof Request))throw new TypeError("url must be a string, URL or Request.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(void 0!==t.requestInit&&(!t.requestInit||"object"!==typeof t.requestInit))throw new TypeError("options.requestInit, when provided, must be an object.");if(void 0!==t.getRetryDelay&&"function"!==typeof t.getRetryDelay)throw new TypeError("options.getRetryDelay, when provided, must be a function.");if(void 0!==t.maxCacheSize&&(!Je(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new Ks(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=t.getRetryDelay??Vs,this._requestInit={...t.requestInit};let i=null;if(t.requestInit?.headers){const e={...Ne(t.requestInit.headers)},r=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==r&&(i=e[r],delete e[r],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){i??(i=t);const r=new Request(e);r.headers.delete("Range"),this._url=r}}if(null!==i){const e=$s(i);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new Ys({maxCacheSize:t.maxCacheSize??67108864,maxWorkerCount:t.parallelism??2,runWorker:this._runWorker.bind(this),prefetchProfile:Qs.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const e=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===e?null!==this._length?this._length:null:Ie(e-this._offset,0,this._length??1/0)}_read(e,t,i,r){if(null!==this._length&&t>this._length)return null;const a=this._offset,s=this._sequentialBacking?this._sequentialBacking._read(a+e,a+t):this._orchestrator.read(a+e,a+t,Math.max(a+i,a),a+Math.min(r,this._length??1/0)),n=e=>e?(e.offset-=this._offset,e):null;return Xe(s)?s.then(n):n(s)}async _runWorker(e){for(;;){const i=new AbortController,r=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:i.signal}),this._getRetryDelay,()=>this._disposed);if(!r.ok)throw new Error(`Error fetching ${String(this._url)}: ${r.status} ${r.statusText}`);r.redirected&&(this.rootPath=r.url);e:if(null===this._orchestrator.fileSize&&(206===r.status||"basic"===r.type&&!r.headers.has("Content-Encoding"))){const t=r.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=r.headers.get("Content-Length");if(i){const t=206===r.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!r.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==r.status){if(this._sequentialBacking)return void r.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||js.has(e.origin)||(ct._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),js.add(e.origin))}return void this._transitionToSequentialMode(r.body)}const a=r.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return i.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let r;try{r=await a.read()}catch(t){if(this._disposed)throw t;const e=this._getRetryDelay(1,t,this._url);if(null!==e){ct._error("Error while reading response stream. Attempting to resume.",t),await at(1e3*e);break}throw t}if(e.aborted)continue;const{done:s,value:n}=r;if(s){if(e.currentPos>=e.targetPos)return void this._orchestrator.onWorkerFinished(e);if(e.strictTarget)break;return void this._orchestrator.onWorkerFinished(e)}this._dispatchRead(e.currentPos,e.currentPos+n.length),this._orchestrator.supplyWorkerData(e,n)}}}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const a=new ReadableStream({pull:async e=>{for(;;){let s;try{s=await t.read()}catch(a){if(this._disposed)throw a;const e=this._getRetryDelay(1,a,this._url);if(null===e)throw a;ct._error("Error while reading response stream. Attempting to resume.",a),await at(1e3*e);const s=await Oe(this._options.fetchFn??fetch,this._url,De(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!s.ok)throw new Error(`Error fetching ${String(this._url)}: ${s.status} ${s.statusText}`);if(!s.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=s.body.getReader(),r=206===s.status?0:i;continue}if(s.done)return void e.close();let n=s.value;if(r>0){const e=Math.min(r,n.length);r-=e,n=n.subarray(e)}if(0!==n.length)return i+=n.length,void e.enqueue(n)}},cancel:()=>t.cancel()}),s=new Gs(a,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const n=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)n.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)n.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of n){const e=s._read(o.start,o.start+o.bytes.length);Xe(e)?e.then(e=>{e?(j(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(j(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const Xs=/^bytes=(\d+)-(\d*)$/,$s=e=>{const t=Xs.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=pe(this._cache,e,e=>e.start),r=-1!==i?this._cache[i]:null;if(r&&r.start<=e&&t<=r.end)return{bytes:r.bytes,view:r.view,offset:r.start};let a=e;const s=new Uint8Array(t-e);if(-1!==i)for(let l=i;l=t)break;const r=Math.max(e,i.start);r>a&&this._throwDueToCacheMiss();const n=Math.min(t,i.end);ra&&this._throwDueToCacheMiss();const{promise:n,resolve:o,reject:c}=ke();return this._pendingSlices.push({start:e,end:t,bytes:s,resolve:o,reject:c}),this._targetIndex=Math.max(this._targetIndex,t),this._pulling||(this._pulling=!0,this._pull().catch(e=>{if(this._pulling=!1,this._pendingSlices.length>0)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),n}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}async _pull(){for(this._reader??(this._reader=this._stream.getReader());this._currentIndex0;){const e=this._cache[0];if(this._maxRequestedIndex-e.end<=this._maxCacheSize)break;this._cache.shift()}this._currentIndex+=t.byteLength}this._pulling=!1}_dispose(){for(const e of this._pendingSlices)e.reject(new Zo);this._pendingSlices.length=0,this._cache.length=0,this._reader?.cancel()}}const Qs={fileSystem:(e,t)=>{const i=65536;return{start:e=Math.floor((e-i)/i)*i,end:t=Math.ceil((t+i)/i)*i}},network:(e,t,i)=>{const r=65536;e=Math.max(0,Math.floor((e-r)/r)*r);for(const a of i){const i=8388608,r=Math.max((a.startPos+a.targetPos)/2,a.targetPos-i);if(Ge(e,t,r,a.targetPos)){const e=a.targetPos-a.startPos,r=Math.ceil((e+1)/i)*i,s=2**Math.ceil(Math.log2(e+1)),n=Math.min(s,r);t=Math.max(t,a.startPos+n)}}return{start:e,end:t=Math.max(t,e+524288)}}};class Ys{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){j(!this.disposed);const a=this.options.prefetchProfile(e,t,this.workers),s=Math.max(a.start,i),n=Math.min(a.end,this.fileSize??1/0,r);j(s<=e&&t<=n);let o=null;const c=pe(this.cache,e,e=>e.start),l=-1!==c?this.cache[c]:null;l&&l.start<=e&&t<=l.end&&(l.age=this.nextAge++,o={bytes:l.bytes,view:l.view,offset:l.start});const u=pe(this.cache,s,e=>e.start),h=o?null:new Uint8Array(t-e);let d=0,f=s;const m=[];if(-1!==u){for(let i=u;i=n)break;if(r.end<=s)continue;const a=Math.max(s,r.start),o=Math.min(n,r.end);if(j(a<=o),f=h.length&&(o={bytes:h,view:J(h),offset:e}),0===m.length)return j(o),o;const{promise:p,resolve:g,reject:k}=ke(),y=[];for(const w of m){const i=Math.max(e,w.start),r=Math.min(t,w.end);i===w.start&&r===w.end?y.push(w):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&w.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,w.end),i.strictTarget&&(i.strictTarget=e),b&&i.pendingSlices.push(b)):(t++,i={hole:{start:w.start,end:w.end},strictTarget:e,pendingSlices:b?[b]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.hole.end)break;i.hole.end=Math.max(i.hole.end,e.hole.end),i.pendingSlices.push(...e.pendingSlices),i.strictTarget&&(i.strictTarget=e.strictTarget),i.age=Math.min(i.age,e.age),this.queuedReads.splice(t+1,1)}}}return o?p.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(j(h),o=p.then(t=>t&&{bytes:t,view:J(t),offset:e})),o}checkHoleAgainstWorker(e,t,i){if(Ge(t.start-2**17,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=r),t.end<=t.start&&(s.holes.splice(e,1),e--)}0===s.holes.length&&(s.resolve(s.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){const t=this.workers.indexOf(e);j(-1!==t),e.running=!1,this.workers.splice(t,1),this.options.onIdleWorkerRemoved?.(e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const i of e.pendingSlices)i.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=pe(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=J(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=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=J(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;ithis._length)return null;const a=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return Xe(a)?a.then(s):s(a)}_dispose(){this._ref?.free()}ref(){return this._ref??(this._ref=this._baseSource.ref()),super.ref()}}var Zs=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t},en=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});const tn=/^0[xX][0-9a-fA-F]+$/,rn=/^data:.*;base64,/i;class an extends Fs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){return this.currentUpdateSegmentsPromise??(this.currentUpdateSegmentsPromise=(async()=>{try{const e=this.getRemainingWaitTimeMs();e>0&&await at(e),this.lastSegmentUpdateTime=performance.now(),await this.updateSegments()}finally{this.currentUpdateSegmentsPromise=null}})())}getRemainingWaitTimeMs(){const e=performance.now()-this.lastSegmentUpdateTime,t=Math.max(0,1e3*this.refreshInterval-e);return t<=50?0:t}async updateSegments(){let e=this.nextLines;if(this.nextLines=null,!e){const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),r=new ec(i.source),a=await r.requestEntireFile();j(a),e=wc(a,a.length,{ignore:_s}),i.source instanceof zs&&(this.rootPath=i.source.rootPath)}catch(y){t.error=y,t.hasError=!0}finally{en(t)}}const t=!1!==this.input._formatOptions.hls?.offsetTimestampsByDateTime;let i=!1,r=0,a=null,s=null,n=null,o=0,c=null,l=null,u=null,h=null,d=null,f=null,m=!1,p=X(this.segments)??null;const g=e=>{const t=e.indexOf("@"),i=Number(-1===t?e:e.slice(0,t));if(!Number.isInteger(i)||i<0)throw new Error(`Invalid #EXT-X-BYTERANGE length '${e}'.`);let r=null;if(-1!==t&&(r=Number(e.slice(t+1)),!Number.isInteger(r)||r<0))throw new Error(`Invalid #EXT-X-BYTERANGE offset '${e}'.`);return{length:i,offset:r}},k=e=>{o=e,p&&(j(null!==p.sequenceNumber),p.sequenceNumber0&&null!==f&&(r=o*f),m=!0);const e=y.slice(8),t=e.indexOf(","),i=-1===t?e:e.slice(0,t),a=Number(i);if(!Number.isFinite(a)||a<0)throw new Error(`Invalid #EXTINF tag duration '${i}'.`);s=a}else if(y.startsWith(vs)){const e=new Rs(y.slice(11)),t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const i=e.get("byterange");let o=null;if(null!==i&&(o=g(i)),o&&null===o.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!p){const e={path:Ze(this.rootPath,t),offset:o?.offset??0,length:o?.length??null};if("AES-128"===n?.method&&!n.iv)throw new Error("IV attribute must be set on #EXT-X-KEY tag preceding the #EXT-X-MAP tag.");l={timestamp:r,unixEpochTimestamp:a,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:n,initSegment:null,lastProgramDateTimeSeconds:d}}s=null,null===h?u=null:h=null}else if(y.startsWith(Ps)){const e=new Rs(y.slice(11)),t=e.get("method");if("NONE"===t)n=null;else if("AES-128"===t){const t=e.get("uri");if(!t)throw new Error("Invalid #EXT-X-KEY: AES-128 requires a URI attribute.");let i=null;const r=e.get("iv");if(r){if(!tn.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(fr);for(let t=0;t=8&&112===t[4]&&115===t[5]&&115===t[6]&&104===t[7]){const e=J(t).getUint32(0);r=sr(t.subarray(8,Math.min(e,t.length)))}}n={method:t,psshBox:r}}}}else if(y.startsWith(Is)){const e=y.slice(22),t=Number(e);if(!Number.isInteger(t)||t<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${e}'.`);k(t)}else if(y.startsWith(xs)){const e=g(y.slice(17));if(null===e.offset){if(null===u)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");e.offset=u}h=e,u=e.offset+e.length}else if(y.startsWith(Cs)){if(p)continue;const e=y.slice(25),i=Date.parse(e);if(!Number.isFinite(i))continue;const s=i/1e3;if(d===s)continue;if(null===d&&this.segments.length>0){const e=X(this.segments),i=s-(e.timestamp+e.duration);for(const r of this.segments)r.unixEpochTimestamp=r.timestamp+i,t&&(r.timestamp=r.unixEpochTimestamp)}d=s,a=s,t&&(r=s)}else if("#EXT-X-DISCONTINUITY"===y)c=null;else if(y.startsWith(Bs)){const e=y.slice(22),t=Number(e);if(!Number.isFinite(t)||t<0)throw new Error(`Invalid EXT-X-TARGETDURATION value '${e}'.`);this.refreshInterval=t,f=t}else{if("#EXT-X-ENDLIST"===y){this.streamHasEnded=!0;break}if(y.startsWith(Es)){"vod"===y.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==y)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");i=!0}}if(!i)throw new Error("Invalid M3U8 file; no #EXTM3U header.")}async getFirstSegment(){return 0===this.segments.length&&await this.runUpdateSegments(),this.segments[0]??null}async getSegmentAt(e,t){0===this.segments.length&&await this.runUpdateSegments();let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=pe(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.segment===t);if(i)return i.age=this.nextInputCacheAge++,i.input;let r=null;(t.initSegment||t.firstSegment)&&(r=this.getInputForSegment(t.initSegment??t.firstSegment));const a={...this.input._formatOptions,isobmff:{...this.input._formatOptions.isobmff,resolveKeyId:this.input._formatOptions.isobmff?.resolveKeyId&&(e=>{if(!t.encryption||"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method||!t.encryption.psshBox)return this.input._formatOptions.isobmff.resolveKeyId(e);let i=e.psshBoxes;const{psshBox:r}=t.encryption;return null!==r.keyIds&&!r.keyIds.includes(e.keyId)||i.some(e=>nr(e,r))||(i=[...i,r]),this.input._formatOptions.isobmff.resolveKeyId({...e,psshBoxes:i})})}},s=new Yo({source:new qs(t.location.path,async e=>{j(e.isRoot);const i={...e,isRoot:!1};let r;const a=t.location.offset>0||null!==t.location.length;if(t.encryption&&"SAMPLE-AES"!==t.encryption.method&&"SAMPLE-AES-CTR"!==t.encryption.method)if("AES-128"===t.encryption.method){const e=t.encryption;j(e.iv);let s=await this.input._getSourceCached(i);if(a){const e=s.source.slice(t.location.offset,t.location.length??void 0).ref();s.free(),s=e}const n=((e,t,i)=>{let r=!1,a=0;const s=new Sr;return new ReadableStream({pull:async n=>{r||(s.init(await t()),r=!0);let o=e.requestSliceRange(a,0,65552);if(Xe(o)&&(o=await o),!o||0===o.length)throw new Error("Invalid ciphertext.");const c=o.length;if(c%16!==0)throw new Error("Invalid ciphertext.");const l=65552===c?c-16:c,u=rc(o,l),h=new Uint8Array(l);for(let e=0;e16)throw new Error("Invalid PKCS#7 padding. Incorrect key or corrupted data.");const t=h.subarray(0,l-e);n.enqueue(t),n.close(),i()}},cancel:()=>{i()}})})(new ec(s.source),async()=>{const t={stack:[],error:void 0,hasError:!1};try{const i=Zs(t,await this.input._getSourceCached({path:e.keyUri,isRoot:!1},Qo),!1),r=new ec(i.source),a=await r.requestSlice(0,fr);if(!a)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:rc(a,fr),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{en(t)}},()=>{s.free()});r=new Gs(n).ref()}else j(!1);else if(r=await this.input._getSourceCached(i),a){const e=r.source.slice(t.location.offset,t.location.length??void 0).ref();r.free(),r=e}return r}),formats:this.input._formats.filter(e=>!(e instanceof Pn)),initInput:r??void 0,formatOptions:a});s._onFormatDetermined=e=>{if(("SAMPLE-AES"===t.encryption?.method||"SAMPLE-AES-CTR"===t.encryption?.method)&&!e._isIsobmff)throw new Error("The SAMPLE-AES and SAMPLE-AES-CTR encryption methods are currently only supported for ISOBMFF files.")},this.inputCache.push({segment:t,input:s,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=tt(this.inputCache,e=>e.age);j(-1!==e),this.inputCache.splice(e,1)}return s}async getLiveRefreshInterval(){return 0===this.getRemainingWaitTimeMs()&&await this.runUpdateSegments(),this.streamHasEnded?null:this.refreshInterval}}class sn extends ir{constructor(e){super(e),this.metadataPromise=null,this.trackBackings=null,this.internalTracks=null,this.segmentedInputs=[],this.hasMasterPlaylist=!0}readMetadata(){return this.metadataPromise??(this.metadataPromise=(async()=>{j(this.input._rootSource instanceof zs);const e=await this.input._reader.requestEntireFile();j(e);const t=wc(e,e.length,{ignore:_s}),{rootPath:i}=this.input._rootSource,r=[],a=[];for(let u=1;u"video"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],n=[...new Set(a.filter(e=>"audio"===e.attributes.get("type").toLowerCase()).map(e=>e.attributes.get("group-id")))],o=await Promise.all(r.map(async(e,t)=>{const r=[],o=e.attributes.get("codecs");let c;if(o)c=o.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=await t.getTrackBackings(),r=await Promise.all(i.map(async e=>({track:e,codec:await e.getCodec()})));c=await Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const l=e.attributes.get("video"),u=e.attributes.get("audio"),h=c.some(e=>_i.includes(ji(e))),d=c.some(e=>Fi.includes(ji(e)));if(null!==l&&!h){if(!s.includes(l))throw new Error(`Invalid M3U8 file; variant stream references video group "${l}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===l&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"video"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}if(null!==u&&!d){if(!n.includes(u))throw new Error(`Invalid M3U8 file; variant stream references audio group "${u}" which is not defined in any #EXT-X-MEDIA tags.`);const e=a.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===u&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=Ze(i,t),a=this.getSegmentedInputForPath(r),s=(await a.getTrackBackings()).find(e=>"audio"===e.getType());if(!s||null===await s.getCodec())break e;const n=await s.getDecoderConfig().then(e=>e?.codec??null);j(null!==n),c.push(n)}}c=[...new Set(c)];let f=null,m=null;const p=e.attributes.getAsNumber("bandwidth");j(null!==p);const g=e.attributes.getAsNumber("average-bandwidth"),k=e.attributes.get("name");for(const i of c){const o=ji(i);if(null!==o)if(_i.includes(o)){if(null!==f)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");f=i;const n=e.attributes.get("video");if(null===n){const i=e.attributes.get("resolution");let a=null,s=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(a=Number(e[1]),s=Number(e[2]))}r.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:xe,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:f,pairingMask:1n<0?a:null}})}else{if(!n.includes(s))throw new Error(`Invalid M3U8 file; variant stream references audio group "${s}" which is not defined in any #EXT-X-MEDIA tags.`);for(const i of a){const a=i.attributes.get("group-id"),n=i.attributes.get("type");if(a!==s||"audio"!==n.toLowerCase())continue;const o=i.attributes.get("channels")??e.attributes.get("channels"),c=null!==o?Number(o.split("/")[0]):null;r.push({id:-1,demuxer:this,backingTrack:null,default:ln(i.attributes),autoselect:ln(i.attributes)||un(i.attributes),languageCode:hn(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:i.fullPath??e.fullPath,fullCodecString:m,pairingMask:1n<0?c:null}})}}}}return r})),c=[],l=e=>{const t=c.find(t=>t.fullPath===e.fullPath&&t.info.type===e.info.type);t?(t.pairingMask|=e.pairingMask,t.default||(t.default=e.default),t.autoselect||(t.autoselect=e.autoselect),t.lineNumber=Math.min(t.lineNumber,e.lineNumber),null!==e.peakBitrate&&(t.peakBitrate=Math.max(t.peakBitrate??-1/0,e.peakBitrate)),null!==e.averageBitrate&&(t.averageBitrate=Math.max(t.averageBitrate??-1/0,e.averageBitrate)),t.languageCode===xe&&(t.languageCode=e.languageCode)):(e.id=c.length+1,c.push(e))};for(const u of o)for(const e of u)l(e);c.sort((e,t)=>e.lineNumber-t.lineNumber),this.trackBackings=[];for(const u of c)"video"===u.info.type?this.trackBackings.push(new on(u)):this.trackBackings.push(new cn(u));this.internalTracks=c})())}async getTrackBackings(){return await this.readMetadata(),j(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 an(this,e,i,null),this.segmentedInputs.push(t),t}async getMetadataTags(){return{}}async getMimeType(){return ys}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class nn{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){return this.hydrationPromise??(this.hydrationPromise=(async()=>{const e=this.internalTrack.demuxer.getSegmentedInputForPath(this.internalTrack.fullPath);let t=null;const i=(await e.getTrackBackings()).filter(e=>e.getType()===this.getType());if(1===i.length)t=i[0];else if(this instanceof on){for(const r of i)if(await r.getCodec()===this.getCodec()){t=r;break}}else{j(this instanceof cn);for(const e of i)if(await e.getCodec()===this.getCodec()){t=e;break}}if(!t)throw new Error("Could not find matching track in underlying media data.");this.internalTrack.backingTrack=t})())}delegate(e){return this.internalTrack.backingTrack?e():this.hydrate().then(e)}getCodec(){throw new Error("Not implemented on base class.")}getDisposition(){return{...ht,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(){j(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}async getDurationFromMetadata(e){return await this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)}async getLiveRefreshInterval(){return await this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}async getFirstPacket(e){return await this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)}async getPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)}async getKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)}async getNextPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)}async getNextKeyPacket(e,t){return await this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)}}class on extends nn{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return ji(this.internalTrack.fullCodecString)}getCodedWidth(){return this.delegate(()=>this.backingVideoTrack.getCodedWidth())}getCodedHeight(){return this.delegate(()=>this.backingVideoTrack.getCodedHeight())}getSquarePixelWidth(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelWidth())}getSquarePixelHeight(){return this.delegate(()=>this.backingVideoTrack.getSquarePixelHeight())}getMetadataDisplayWidth(){return this.backingVideoTrack?null:this.internalTrack.info.width}getMetadataDisplayHeight(){return this.backingVideoTrack?null:this.internalTrack.info.height}getRotation(){return this.delegate(()=>this.backingVideoTrack.getRotation())}async getColorSpace(){return await this.hydrate(),this.backingVideoTrack.getColorSpace()}async canBeTransparent(){return await this.hydrate(),this.backingVideoTrack.canBeTransparent()}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingVideoTrack.getDecoderConfig()}}class cn extends nn{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return ji(this.internalTrack.fullCodecString)}getNumberOfChannels(){return null!==this.internalTrack.info.numberOfChannels?this.internalTrack.info.numberOfChannels:this.delegate(()=>this.backingAudioTrack.getNumberOfChannels())}getSampleRate(){return this.delegate(()=>this.backingAudioTrack.getSampleRate())}getMetadataCodecParameterString(){return this.backingAudioTrack?null:this.internalTrack.fullCodecString}async getDecoderConfig(){return await this.hydrate(),this.backingAudioTrack.getDecoderConfig()}}const ln=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}".`)},un=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}".`)},hn=e=>{if(null===e)return xe;const t=e.split("-")[0];return t||xe};class dn{constructor(){this._isIsobmff=!1}}class fn extends dn{constructor(){super(...arguments),this._isIsobmff=!0}async _getMajorBrand(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return null;t.skip(4);const i=bc(t,4);return"ftyp"!==i&&"styp"!==i?null:bc(t,4)}_createDemuxer(e){return new vr(e)}}class mn extends fn{async _canReadInput(e){const t=await this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(Xe(t)&&(t=await t),!t)return!1;let r=uc(t),a=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(Xe(t)&&(t=await t),!t)return!1;r=mc(t),a=16}if(r8)return!1;if(Gr(i,r)!==qr.EBML)return!1;const a=Yr(i);if("number"!==typeof a)return!1;let s=e._reader.requestSlice(i.filePos,a);if(Xe(s)&&(s=await s),!s)return!1;const n=i.filePos;for(;s.filePos<=n+a-2;){const e=Jr(s);if(!e)break;const{id:i,size:r}=e,a=s.filePos;if(void 0===r)return!1;switch(i){case qr.EBMLVersion:if(1!==Gr(s,r))return!1;break;case qr.EBMLReadVersion:if(1!==Gr(s,r))return!1;break;case qr.DocType:if(Zr(s,r)!==t)return!1;break;case qr.DocTypeVersion:if(Gr(s,r)>4)return!1}s.filePos=a+r}return!0}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Ca(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class kn extends gn{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class yn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}const i=await Ra(e._reader,t,t+4096);if(!i)return!1;const r=i.header,a=Qi(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+a,4);if(Xe(s)&&(s=await s),!s)return!1;const n=uc(s);if(n===$i||n===Gi)return!0;t=i.startPos+i.header.totalSize;const o=await Ra(e._reader,t,t+4);if(!o)return!1;const c=o.header;return r.channel===c.channel&&r.sampleRate===c.sampleRate}_createDemuxer(e){return new Fa(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class bn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,12);if(Xe(t)&&(t=await t),!t)return!1;const i=bc(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===bc(t,4)}_createDemuxer(e){return new $a(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class wn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,4);return Xe(t)&&(t=await t),!!t&&"OggS"===bc(t,4)}_createDemuxer(e){return new Wa(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class Tn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return Xe(i)&&(i=await i),!!i&&"fLaC"===bc(i,4)}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ts(e)}}class Sn extends dn{async _canReadInput(e){let t=0;for(;;){let i=e._reader.requestSlice(t,xc);if(Xe(i)&&(i=await i),!i)break;const r=_c(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(Xe(i)&&(i=await i),!i)return!1;const r=Ya(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),Xe(i)&&(i=await i),!i)return!1;const a=Ya(i);return!!a&&(r.objectType===a.objectType&&r.samplingFrequencyIndex===a.samplingFrequencyIndex&&r.channelConfiguration===a.channelConfiguration)}_createDemuxer(e){return new Za(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class vn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,205);if(Xe(t)&&(t=await t),!t)return!1;const i=rc(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 ls(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class Pn extends dn{async _canReadInput(e){let t=e._reader.requestSlice(0,7);if(Xe(t)&&(t=await t),!t)return!1;if(!("#EXTM3U"===bc(t,7)))return!1;if(!(e._rootSource instanceof zs))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 sn(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return ys}}const In=new mn,xn=new pn,Cn=new gn,Bn=new kn,En=new yn,_n=new bn,Rn=new wn,Fn=new Sn,An=new Tn,Mn=new vn,Dn=new Pn,Nn=[Dn,In,xn,Cn,Bn,_n,Rn,An,En,Fn,Mn],On=[Dn,In,xn,En,Fn,Mn];var Ln=function(e){return function(t){function i(i){t.error=t.hasError?new e(i,t.error,"An error was suppressed during disposal."):i,t.hasError=!0}var r,a=0;return function e(){for(;r=t.stack.pop();)try{if(!r.async&&1===a)return a=0,t.stack.push(r),Promise.resolve().then(e);if(r.dispose){var s=r.dispose.call(r.value);if(r.async)return a|=2,Promise.resolve(s).then(e,function(t){return i(t),e()})}else a|=1}catch(n){i(n)}if(1===a)return t.hasError?Promise.reject(t.error):Promise.resolve();if(t.hasError)throw t.error}()}}("function"===typeof SuppressedError?SuppressedError:function(e,t,i){var r=new Error(i);return r.name="SuppressedError",r.error=e,r.suppressed=t,r});Ye();let zn=-1/0,Un=-1/0,qn=null;"undefined"!==typeof FinalizationRegistry&&(qn=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-zn>=1e3&&(ct._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."),zn=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-Un>=1e3&&(ct._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."),Un=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class Wn{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const Hn=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],Vn=new Set(Hn);class jn{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(Me*this.timestamp)}get microsecondDuration(){return Math.trunc(Me*this.duration)}get hasAlpha(){return this.format&&this.format.includes("A")}constructor(e,t){if(this._closed=!1,e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e)){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0===t.format||!Vn.has(t.format))throw new TypeError("init.format must be one of: "+Hn.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&&rt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0;const i=t.layout??to(t.format,t.codedWidth,t.codedHeight);let r=t.colorSpace??null;null===r&&(r="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:t.visibleRect?.left??0,top:t.visibleRect?.top??0,width:t.visibleRect?.width??t.codedWidth,height:t.visibleRect?.height??t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?Y(e):Y(e).slice(),this._layout=i,this.colorSpace=new Qn(r)}else if("undefined"!==typeof VideoFrame&&e instanceof VideoFrame){if(void 0!==t?.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(void 0!==t?.timestamp&&!Number.isFinite(t?.timestamp))throw new TypeError("init.timestamp, when provided, must be a number.");if(void 0!==t?.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");void 0!==t?.visibleRect&&rt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:e.visibleRect?.x??0,top:e.visibleRect?.y??0,width:e.visibleRect?.width??e.codedWidth,height:e.visibleRect?.height??e.codedHeight},this.rotation=t?.rotation??0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=t?.timestamp??e.timestamp/1e6,this.duration=t?.duration??(e.duration??0)/1e6,this.colorSpace=new Qn(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&rt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new jn(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Me),duration:Math.trunc((t.duration??0)*Me)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const a=t.visibleRect??{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(a.width,a.height),n=s.getContext("2d",{alpha:We(),willReadFrequently:!0});if(!n)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");n.drawImage(e,-a.left,-a.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:a.width,height:a.height},this.squarePixelWidth=a.width,this.squarePixelHeight=a.height,this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=new Qn({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof Wn))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!Hn.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=t.rotation??0,this.timestamp=t.timestamp,this.duration=t.duration??0,this.colorSpace=e.getColorSpace()}this.encodeOptions=t?.encodeOptions??{},this.pixelAspectRatio=it({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),qn?.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return j(null!==this._data),this._data instanceof Wn?new jn(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):Yn(this._data)?new jn(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(j(this._layout),new jn(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new jn(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(qn?.unregister(this),this._data instanceof Wn?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Yn(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){if(eo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(e.format??this.format))throw new Error("Cannot get allocation size when format is null.");if(Yn(this._data))return this._data.allocationSize(e);return ro(this,e).allocationSize}async copyTo(e,t={}){if(!le(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(eo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(t.format??this.format))throw new Error("Cannot copy video sample data when format is null.");if(j(null!==this._data),Yn(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof Wn)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=await i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const r=function(e,t,i){if(null!==t&&void 0!==t){if("object"!==typeof t&&"function"!==typeof t)throw new TypeError("Object expected.");var r,a;if(i){if(!Symbol.asyncDispose)throw new TypeError("Symbol.asyncDispose is not defined.");r=t[Symbol.asyncDispose]}if(void 0===r){if(!Symbol.dispose)throw new TypeError("Symbol.dispose is not defined.");r=t[Symbol.dispose],i&&(a=r)}if("function"!==typeof r)throw new TypeError("Object not disposable.");a&&(r=function(){try{a.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:i})}else i&&e.stack.push({async:!0});return t}(i,await this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},t.colorSpace??"srgb"),!1);if(!(r instanceof jn))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(r.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${r.format}' instead.`);return await r.copyTo(e,t)}catch(c){i.error=c,i.hasError=!0}finally{Ln(i)}}}const i=ro(this,t);j(this.format);const r=Y(e);if(r.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');s=e}else if(this._data instanceof Uint8Array)j(this._layout),j(this._layout.length===a.length),s=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");j(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);s=[{data:Y(t.data),stride:4*this.codedWidth}]}const n=[],o=a.length;for(let l=0;la.byteLength)throw new Error("Source buffer OOB read.");if(c+u>r.byteLength)throw new Error("Destination buffer OOB write.");const i=a.subarray(o,o+u);r.set(i,c),o+=t,c+=e.destinationStride}n.push(h)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),a=this.format.includes("X")&&t.format.includes("A");if(e||a)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const a=[];for(const s of e)i.set(s.data,r),a.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:a[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return Yn(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(j(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,a,s,n,o,c){let l=0,u=0,h=this.displayWidth,d=this.displayHeight,f=0,m=0,p=this.displayWidth,g=this.displayHeight;if(void 0!==s?(l=t,u=i,h=r,d=a,f=s,m=n,void 0!==o?(p=o,g=c):(p=h,g=d)):(f=t,m=i,void 0!==r&&(p=r,g=a)),!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!Number.isFinite(l))throw new TypeError("sx must be a number.");if(!Number.isFinite(u))throw new TypeError("sy must be a number.");if(!Number.isFinite(h)||h<0)throw new TypeError("sWidth must be a non-negative number.");if(!Number.isFinite(d)||d<0)throw new TypeError("sHeight must be a non-negative number.");if(!Number.isFinite(f))throw new TypeError("dx must be a number.");if(!Number.isFinite(m))throw new TypeError("dy must be a number.");if(!Number.isFinite(p)||p<0)throw new TypeError("dWidth must be a non-negative number.");if(!Number.isFinite(g)||g<0)throw new TypeError("dHeight must be a non-negative number.");if(this._closed)throw new Error("VideoSample is closed.");({sx:l,sy:u,sWidth:h,sHeight:d}=this._rotateSourceRegion(l,u,h,d,this.rotation));const k=this.toCanvasImageSource();e.save();const y=f+p/2,b=m+g/2;e.translate(y,b),e.rotate(this.rotation*Math.PI/180);const w=this.rotation%180===0?1:p/g;e.scale(1/w,w),e.drawImage(k,l,u,h,d,-p/2,-g/2,p,g),e.restore()}drawWithFit(e,t){if(!("undefined"!==typeof CanvasRenderingContext2D&&e instanceof CanvasRenderingContext2D||"undefined"!==typeof OffscreenCanvasRenderingContext2D&&e instanceof OffscreenCanvasRenderingContext2D))throw new TypeError("context must be a CanvasRenderingContext2D or OffscreenCanvasRenderingContext2D.");if(!t||"object"!==typeof t)throw new TypeError("options must be an object.");if(!["fill","contain","cover"].includes(t.fit))throw new TypeError("options.fit must be 'fill', 'contain', or 'cover'.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("options.rotation, when provided, must be 0, 90, 180, or 270.");void 0!==t.crop&&Zn(t.crop,"options.");const i=e.canvas.width,r=e.canvas.height,a=t.rotation??this.rotation,[s,n]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let o,c,l,u,h=t.crop;h&&(h=Jn(h,s,n));const{sx:d,sy:f,sWidth:m,sHeight:p}=this._rotateSourceRegion(t.crop?.left??0,t.crop?.top??0,t.crop?.width??s,t.crop?.height??n,a);if("fill"===t.fit)o=0,c=0,l=i,u=r;else{const[e,a]=t.crop?[t.crop.width,t.crop.height]:[s,n],h="contain"===t.fit?Math.min(i/e,r/a):Math.max(i/e,r/a);l=e*h,u=a*h,o=(i-l)/2,c=(r-u)/2}e.save();const g=a%180===0?1:l/u;e.translate(i/2,r/2),e.rotate(a*Math.PI/180),e.scale(1/g,g),e.translate(-i/2,-r/2),e.drawImage(this.toCanvasImageSource(),d,f,m,p,o,c,l,u),e.restore()}_rotateSourceRegion(e,t,i,r,a){return 90===a?[e,t,i,r]=[t,this.squarePixelHeight-e-i,r,i]:180===a?[e,t]=[this.squarePixelWidth-e-i,this.squarePixelHeight-t-r]:270===a&&([e,t,i,r]=[this.squarePixelWidth-t-r,e,r,i]),{sx:e,sy:t,sWidth:i,sHeight:r}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,a=e.height,[s,n]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,c=i.crop?i.crop.height:n;let l=0;2*r0?Gn(u,h):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,h)):m||f.clearRect(0,0,u,h),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=l;p>1;p--){const e=r*2**p,t=a*2**p;f.drawImage(d,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",l>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(d,0,0,2*r,2*a,0,0,r,a),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(j(null!==this._data),this._data instanceof Wn||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}async transform(e){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&Zn(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const t=K(this.rotation+(e.rotate??0)),[i,r]=t%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let a=e.crop;a&&(a=Jn(a,i,r));const s=a?a.width:i,n=a?a.height:r,o=s/n;let c,l;void 0!==e.width&&void 0===e.height?(c=e.width,l=c/o):void 0===e.width&&void 0!==e.height?(l=e.height,c=l*o):void 0!==e.width&&void 0!==e.height?(c=e.width,l=e.height):(c=s,l=n),c=Be(c,e.roundDimensionsTo??1),l=Be(l,e.roundDimensionsTo??1);const u={width:c,height:l,fit:e.fit??"fill",rotation:t,crop:a??{left:0,top:0,width:i,height:r},alpha:e.alpha??"keep"};for(const m of Kn){let e=m(this,u);if(Xe(e)&&(e=await e),null!==e)return e}const{canvas:h,context:d,isNew:f}=Gn(u.width,u.height);return this._drawWithFitAndMipmapping(h,d,{fit:u.fit,rotation:u.rotation,crop:u.crop,targetIsFresh:f,fillBlack:"discard"===u.alpha}),new jn(h,{timestamp:this.timestamp,duration:this.duration,rotation:0})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const Kn=[],Xn=[];let $n=0;const Gn=(e,t)=>{for(const a of Xn)if(a.canvas.width===e&&a.canvas.height===t)return a.age=$n++,{canvas:a.canvas,context:a.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return Xn.length>=3&&Xn.splice(tt(Xn,e=>e.age),1),Xn.push({canvas:i,context:r,age:$n++}),{canvas:i,context:r,isNew:!0}};class Qn{constructor(e){if(void 0!==e){if(!e||"object"!==typeof e)throw new TypeError("init.colorSpace, when provided, must be an object.");const t=Object.keys(te);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(re);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(se);if(null!=e.matrix&&!r.includes(e.matrix))throw new TypeError(`init.colorSpace.matrix, when provided, must be one of ${r.join(", ")}.`);if(null!=e.fullRange&&"boolean"!==typeof e.fullRange)throw new TypeError("init.colorSpace.fullRange, when provided, must be a boolean.")}this.primaries=e?.primaries??null,this.transfer=e?.transfer??null,this.matrix=e?.matrix??null,this.fullRange=e?.fullRange??null}toJSON(){return{primaries:this.primaries,transfer:this.transfer,matrix:this.matrix,fullRange:this.fullRange}}}const Yn=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,Jn=(e,t,i)=>{const r=Math.min(e.left,t),a=Math.min(e.top,i),s=Math.min(e.width,t-r),n=Math.min(e.height,i-a);return j(s>=0),j(n>=0),{left:r,top:a,width:s,height:n}},Zn=(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.")},eo=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.")}},to=(e,t,i)=>{const r=io(e),a=[];let s=0;for(const n of r){const e=Math.ceil(t/n.widthDivisor),r=Math.ceil(i/n.heightDivisor),o=e*n.sampleBytes,c=o*r;a.push({offset:s,stride:o}),s+=c}return a},io=e=>{const t=(e,t,i,r,a)=>{const s=[{sampleBytes:e,widthDivisor:1,heightDivisor:1},{sampleBytes:t,widthDivisor:i,heightDivisor:r},{sampleBytes:t,widthDivisor:i,heightDivisor:r}];return a&&s.push({sampleBytes:e,widthDivisor:1,heightDivisor:1}),s};switch(e){case"I420":return t(1,1,2,2,!1);case"I420P10":case"I420P12":return t(2,2,2,2,!1);case"I420A":return t(1,1,2,2,!0);case"I420AP10":case"I420AP12":return t(2,2,2,2,!0);case"I422":return t(1,1,2,1,!1);case"I422P10":case"I422P12":return t(2,2,2,1,!1);case"I422A":return t(1,1,2,1,!0);case"I422AP10":case"I422AP12":return t(2,2,2,1,!0);case"I444":return t(1,1,1,1,!1);case"I444P10":case"I444P12":return t(2,2,1,1,!1);case"I444A":return t(1,1,1,1,!0);case"I444AP10":case"I444AP12":return t(2,2,1,1,!0);case"NV12":return[{sampleBytes:1,widthDivisor:1,heightDivisor:1},{sampleBytes:2,widthDivisor:2,heightDivisor:2}];case"RGBA":case"RGBX":case"BGRA":case"BGRX":return[{sampleBytes:4,widthDivisor:1,heightDivisor:1}];default:Te(e),j(!1)}},ro=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,a=ao(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let n;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");n=t.format}else n=e.format;return no(a,n,s)},ao=(e,t,i,r,a)=>{const s={...e};if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!so(a,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},so=(e,t)=>{if(null===e)return!0;const i=io(e);for(let r=0;r{const r=io(t),a=r.length;if(void 0!==i&&i.length!==a)throw new TypeError(`Layout must have ${a} planes.`);let s=0;const n=[],o=[];for(let c=0;c4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(d),s=Math.max(s,d);for(let e=0;e 0.");if(!Number.isInteger(e.numberOfChannels)||0===e.numberOfChannels)throw new TypeError("Invalid AudioDataInit: numberOfChannels must be an integer > 0.");if(!Number.isFinite(e?.timestamp))throw new TypeError("init.timestamp must be a number.");const t=e.data.byteLength/(uo(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*uo(this.format);if(i.byteLength=this.numberOfFrames)throw new RangeError("frameOffset out of range");const r=void 0!==e.frameCount?e.frameCount:this.numberOfFrames-i;if(r>this.numberOfFrames-i)throw new RangeError("frameCount out of range");const a=uo(t),s=ho(t);if(s&&e.planeIndex>=this.numberOfChannels)throw new RangeError("planeIndex out of range");if(!s&&0!==e.planeIndex)throw new RangeError("planeIndex out of range");return(s?r:r*this.numberOfChannels)*a}copyTo(e,t){if(!le(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&&!oo.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:a}=t;let{planeIndex:s}=t,n=this.format;const o=i??this.format;if(!o)throw new Error("Destination format not determined");const c=this.numberOfFrames,l=this.numberOfChannels,u=a??0;if(u>=c)throw new RangeError("frameOffset out of range");const h=void 0!==r?r:c-u;if(h>c-u)throw new RangeError("frameCount out of range");const d=uo(o),f=ho(o);if(f&&s>=l)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?h:h*l)*d;if(e.byteLength2&&o!==n)return void go(this._data,p,n,o,l,s,u,h);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:h,format:o})}catch(S){if("f32-planar"===o)throw S;n="f32-planar"}}const k=fo(n),y=uo(n),b=ho(n);let w;if(this._data instanceof co){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=c*y*(b?1:l);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)w=e(s),s=0;else{w=new Uint8Array(c*y*l);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(a,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new lo({data:a,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(qn?.unregister(this),this._data instanceof co?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof co?this._createAudioDataFromData():po(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(ho(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const a=Math.min(s,o),c=new Float32Array(i*a);for(let t=0;t0;){const a=Math.min(s,o),l=new Float32Array(i*a);for(let t=0;t{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")}},ho=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},fo=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)}},mo=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,Ie(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,Ie(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,Ie(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},po=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,go=(e,t,i,r,a,s,n,o)=>{const c=fo(i),l=mo(r),u=uo(i),h=uo(r),d=ho(i);if(ho(r))if(d){const r=new ArrayBuffer(o*u),a=J(r);e.copyTo(r,{planeIndex:s,frameOffset:n,frameCount:o,format:i});for(let e=0;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.")},wo=e=>{if(!Je(e))throw new TypeError("timestamp must be a number.")},To=(e,t,i)=>i.verifyKeyPackets?t.then(async t=>{if(!t||"delta"===t.type)return t;const i=await e.determinePacketType(t);return i&&(t.type=i),t}):t;class So{constructor(e){if(!(e instanceof Oo))throw new TypeError("track must be an InputTrack.");this._track=e}async getFirstPacket(e={}){if(bo(e),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getFirstPacket(e),e)}async getFirstKeyPacket(e={}){bo(e);const t=await this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null}async getPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getPacket(e,t),t)}async getNextPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;return To(this._track,this._track._backing.getNextPacket(e,t),t)}async getKeyPacket(e,t={}){if(wo(e),bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=await this._track._backing.getKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getKeyPacket(i.timestamp-1/await this._track.getTimeResolution(),t):i}async getNextKeyPacket(e,t={}){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(bo(t),this._track.input._disposed)throw new Zo;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=await this._track._backing.getNextKeyPacket(e,t);if(!i)return i;j("key"===i.type);return"delta"===await this._track.determinePacketType(i)?this.getNextKeyPacket(i,t):i}packets(e,t,i={}){if(void 0!==e&&!(e instanceof ar))throw new TypeError("startPacket must be an EncodedPacket.");if(void 0!==e&&e.isMetadataOnly&&!i?.metadataOnly)throw new TypeError("startPacket can only be metadata-only if options.metadataOnly is enabled.");if(void 0!==t&&!(t instanceof ar))throw new TypeError("endPacket must be an EncodedPacket.");if(bo(i),this._track.input._disposed)throw new Zo;const r=[];let{promise:a,resolve:s}=ke(),{promise:n,resolve:o}=ke(),c=!1,l=!1,u=null,h=!1;const d=[],f=()=>Math.max(2,d.length);(async()=>{let u=e??await this.getFirstPacket(i);for(;u&&!l&&!this._track.input._disposed&&!(t&&u.sequenceNumber>=t?.sequenceNumber);)r.length>f()?(({promise:n,resolve:o}=ke()),await n):(r.push(u),s(),({promise:a,resolve:s}=ke()),u=await this.getNextPacket(u,i));c=!0,s()})().catch(e=>{h||(u=e,h=!0,s())});const m=this._track;return{async next(){for(;;){if(m.input._disposed)throw new Zo;if(l)return{value:void 0,done:!0};if(h)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(d.push(t);d.length>0&&t-d[0]>=1e3;)d.shift();return o(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};await a}},return:async()=>(l=!0,o(),s(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}class vo{constructor(e,t){this.onSample=e,this.onError=t}}class Po{mediaSamplesInRange(e=-1/0,t=1/0,i){wo(e),wo(t);const r=[];let a=!1,s=null,{promise:n,resolve:o}=ke(),{promise:c,resolve:l}=ke(),u=!1,h=!1,d=!1,f=null,m=null,p=!1;const g={...i,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{f=await this._createDecoder(i=>{l(),i.timestamp>=t&&(h=!0),h?i.close():(s&&(i.timestamp>e?(r.push(s),a=!0):s.close()),i.timestamp>=e&&(r.push(i),a=!0),s=a?null:i,r.length>0&&(o(),({promise:n,resolve:o}=ke())))},e=>{p||(m=e,p=!0,o())});const i=this._createPacketSink(),k=await i.getKeyPacket(e,g)??await i.getFirstKeyPacket(g);let y=k;const b=i.packets(k??void 0,void 0,g);for(await b.next();y&&!h&&!this._track.input._disposed;){const e=Io(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:c,resolve:l}=ke()),await c;continue}f.decode(y);const t=await b.next();if(t.done)break;y=t.value}await b.return(),d||this._track.input._disposed||await f.flush(),!a&&s&&r.push(s),u=!0,o()})().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{f?.close()});const k=this._track,y=()=>{s?.close();for(const e of r)e.close()};return{async next(){for(;;){if(k.input._disposed)throw d=!0,h=!0,y(),new Zo;if(d)return{value:void 0,done:!0};if(p)throw d=!0,h=!0,y(),m;if(r.length>0){const e=r.shift();return l(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};await n}},return:async()=>(d=!0,h=!0,l(),o(),y(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}mediaSamplesAtTimestamps(e,t){(e=>{if(!(Symbol.iterator in e)&&!(Symbol.asyncIterator in e))throw new TypeError("Argument must be an iterable or async iterable.")})(e);const i=async function*(e){Symbol.iterator in e?yield*e[Symbol.iterator]():yield*e[Symbol.asyncIterator]()}(e),r=[],a=[];let{promise:s,resolve:n}=ke(),{promise:o,resolve:c}=ke(),l=!1,u=!1,h=null,d=null,f=!1;const m=e=>{a.push(e),n(),({promise:s,resolve:n}=ke())},p={...t,verifyKeyPackets:!0,metadataOnly:!1};(async()=>{h=await this._createDecoder(e=>{if(c(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(d=e,f=!0,n())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=async()=>{j(s),j(h);let t=s;for(h.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:c}=ke()),await o;if(u)break;const r=await e.getNextPacket(t,p);j(r),h.decode(r),t=r}g=-1},y=async()=>{j(h),await h.flush();for(let e=0;e{f||(d=e,f=!0,n())}).finally(()=>{h?.close()});const g=this._track,k=()=>{for(const e of a)e?.close()};return{async next(){for(;;){if(g.input._disposed)throw u=!0,k(),new Zo;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),d;if(a.length>0){const e=a.shift();return j(void 0!==e),c(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};await s}},return:async()=>(u=!0,c(),n(),k(),{value:void 0,done:!0}),async throw(e){throw e},[Symbol.asyncIterator](){return this}}}}const Io=e=>0===e?40:8;class xo extends vo{constructor(e,t,i,r,a,s){super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=a,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const n=ko.find(e=>e.supports(i,r));if(n)this.customDecoder=new n,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof jn))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();j(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(Ve()){if("avc"===i&&this.decoderConfig.description){const e=Mt(Y(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Nt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig={...this.decoderConfig,hardwareAcceleration:"prefer-software"}),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=Lt(t),this.decoderConfig={...this.decoderConfig,description:At(e)}))}}oe(this.decoderConfig.colorSpace)||(this.decoderConfig={...this.decoderConfig,colorSpace:{primaries:this.decoderConfig.colorSpace?.primaries??"bt709",matrix:this.decoderConfig.colorSpace?.matrix??"bt709",transfer:this.decoderConfig.colorSpace?.transfer??"bt709",fullRange:this.decoderConfig.colorSpace?.fullRange??!1}})}const t=new Error("Decoding error").stack;this.decoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.decoder.configure(this.decoderConfig)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),Math.max(this.decoder.decodeQueueSize,this.alphaDecoder?.decodeQueueSize??0))}decode(e){if("hevc"===this.codec&&this.currentPacketIndex>0&&!this.raslSkipped){if(this.hasHevcRaslPicture(e.data))return;this.raslSkipped=!0}if(this.customDecoder)this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(j(this.decoder),Ue()||ge(this.inputTimestamps,e.timestamp,e=>e),Ve()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const a of xt(e.data,this.decoderConfig)){const r=Ct(e.data[a.offset]);if(i||(i=r>=1&&r<=5),r===wt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(a.offset,a.offset+a.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&Y(t.description)[4];return Rt(e,i+1)}return _t(e)})(t,this.decoderConfig);e=new ar(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=Jt(e.data,this.decoderConfig);t&&(e=new ar(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new Bo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();j(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();j(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=ni(this.codec,this.decoderConfig,e.sideData.alpha);if(this.alphaHadKeyframe||(this.alphaHadKeyframe="key"===t),this.alphaHadKeyframe){if("hevc"===this.codec&&this.currentAlphaPacketIndex>0&&!this.alphaRaslSkipped){if(this.hasHevcRaslPicture(e.sideData.alpha))return void this.pushNullAlphaFrame();this.alphaRaslSkipped=!0}this.currentAlphaPacketIndex++,this.alphaDecoder.decode(e.alphaToEncodedVideoChunk(t??e.type)),this.alphaDecoderQueueSize++}else this.pushNullAlphaFrame()}pushNullAlphaFrame(){0===this.alphaDecoderQueueSize?this.alphaQueue.push(null):this.nullAlphaFrameQueue.push(this.decodedAlphaChunkCount+this.alphaDecoderQueueSize)}hasHevcRaslPicture(e){for(const t of zt(e,this.decoderConfig)){const i=Ut(e[t.offset]);if(i===St.RASL_N||i===St.RASL_R)return!0}return!1}sampleHandler(e){if(Ue()){if(this.sampleQueue.length>0&&e.timestamp>=X(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}ge(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();j(void 0!==t),e.setTimestamp(t),this.finalizeAndEmitSample(e)}}finalizeAndEmitSample(e){e.setTimestamp(Math.round(e.timestamp*this.timeResolution)/this.timeResolution),e.setDuration(Math.round(e.duration*this.timeResolution)/this.timeResolution),e.setRotation(this.rotation),this.onSample(e)}async mergeAlpha(e,t){const i=ke();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){j(this.merger);const i=await this.merger.merge(e,t);r.sample=new jn(i)}else r.sample=new jn(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(a){ye(this.finalSamples,r),this.onError(a)}finally{ye(this.mergeAlphaPromises,i.promise),i.resolve()}}async flush(){if(this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await Promise.all([this.decoder.flush(),this.alphaDecoder?.flush()]),await Promise.all(this.mergeAlphaPromises),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.alphaHadKeyframe=!1,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue.length=0,this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1),Ue()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>e?.close()),this.alphaQueue.length=0,this.merger?.close());for(const e of this.sampleQueue)e.close();this.sampleQueue.length=0}}let Co=null;class Bo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Co){const e=new Blob([`(${Eo.toString()})()`],{type:"application/javascript"});Co=URL.createObjectURL(e)}const e=Ie(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=ke();this.pendingRequests.set(i,r);const a=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,a.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Eo=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:a,alpha:s}=e.data;i=i.then(async()=>{try{const e=await r(a,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{a.close(),s.close()}})});const r=async(e,t)=>{const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),c=i.includes("P12"),l=r.includes("P10"),u=r.includes("P12");if(l!==o||u!==c)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return await a(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return await s(e,t,i);if("NV12"===i)return await n(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)},a=async(e,t,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=new Uint8Array(4*s);await e.copyTo(n);const c=await o(t,r,a,1);for(let o=0,u=3;o{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=i.includes("P10"),n=i.includes("P12"),c=s||n?2:1;let l,u;i.startsWith("I420")?(l=Math.ceil(r/2),u=Math.ceil(a/2)):i.startsWith("I422")?(l=Math.ceil(r/2),u=a):(l=r,u=a);const h=r*a,d=h*c,f=l*u*c,m=new Uint8Array(d+2*f+h*c);await e.copyTo(m);const p=await o(t,r,a,c),g=d+2*f;m.set(p,g);const k={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:r,codedHeight:a,timestamp:e.timestamp,duration:e.duration??void 0,transfer:[m.buffer]};return new VideoFrame(m,k)},n=async(e,i)=>{const r=e.visibleRect?.width??e.codedWidth,a=e.visibleRect?.height??e.codedHeight,s=r*a,n=Math.ceil(r/2)*Math.ceil(a/2),c=e.allocationSize();t&&t.byteLength===c||(t=new Uint8Array(c)),await e.copyTo(t);const l=new Uint8Array(s+2*n+s);l.set(t.subarray(0,s),0);const u=s,h=s+n,d=s;for(let o=0;o{const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),await t.copyTo(e);const n=t.format;if("RGBA"===n||"BGRA"===n||"RGBX"===n||"BGRX"===n){const t="RGBA"===n||"RGBX"===n?0:2,a=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class Ro extends Po{constructor(e,t={}){if(!(e instanceof Uo))throw new TypeError("videoTrack must be an InputVideoTrack.");_o(t),super(),this._track=e,this._decoderOptions=t}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(je("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getRotation();let a=await this._track.getDecoderConfig();const s=await this._track.getTimeResolution();return j(i&&a),a={...a,hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency},new xo(e,t,i,a,r,s)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Fo{constructor(e,t={}){if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof Uo))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&&Zn(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&_o(t.decoderOptions),this._videoTrack=e,this._alpha=t.alpha??!1,this._options=t,this._fit=t.fit??"fill",this._videoSampleSink=new Ro(e,t.decoderOptions),this._canvasPool=Array.from({length:t.poolSize??0},()=>null)}_ensureInit(){return this._initPromise??(this._initPromise=(async()=>{const e=this._options,t=this._videoTrack,i=e.rotation??await t.getRotation(),r=await t.getSquarePixelWidth(),a=await t.getSquarePixelHeight(),[s,n]=i%180===0?[r,a]:[a,r];let o=e.crop;o&&(o=Jn(o,s,n));let[c,l]=o?[o.width,o.height]:[s,n];const u=c/l;void 0!==e.width&&void 0===e.height?(c=e.width,l=Math.round(c/u)):void 0===e.width&&void 0!==e.height?(l=e.height,c=Math.round(l*u)):void 0!==e.width&&void 0!==e.height&&(c=e.width,l=e.height),this._width=c,this._height=l,this._rotation=i,this._crop=o})())}_videoSampleToWrappedCanvas(e){const t=this._width,i=this._height;let r=this._canvasPool[this._nextCanvasIndex],a=!1;r||("undefined"!==typeof document?(r=document.createElement("canvas"),r.width=t,r.height=i):r=new OffscreenCanvas(t,i),this._canvasPool.length>0&&(this._canvasPool[this._nextCanvasIndex]=r),a=!0),this._canvasPool.length>0&&(this._nextCanvasIndex=(this._nextCanvasIndex+1)%this._canvasPool.length);const s=r.getContext("2d",{alpha:this._alpha||We()});j(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:a,fillBlack:!this._alpha&&We()});const n={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),n}async getCanvas(e,t){wo(e),await this._ensureInit();const i=await this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)}async*canvases(e,t,i){await this._ensureInit(),yield*Pe(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e))}async*canvasesAtTimestamps(e,t){await this._ensureInit(),yield*Pe(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e))}}class Ao extends vo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new Le,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const a=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const a=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(a*s)/s),e(t)},s=yo.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 lo))throw new TypeError("The argument passed to onSample must be an AudioSample.");a(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{a(new lo(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(j(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(j(this.decoder),this.expectedFirstTimestamp??(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}async flush(){this.customDecoder?await this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(j(this.decoder),await this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(j(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Mo extends vo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,j(Ri.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:a,littleEndian:s}=Vi(this.codec);switch(this.inputSampleSize=a,a){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-128:"signed"===r?this.readInputValue=(e,t)=>e.getInt8(t):"ulaw"===r?this.readInputValue=(e,t)=>(e=>{let t=0,i=0,r=~e;128&r&&(r&=-129,t=-1),i=5+((240&r)>>4);const a=(1<(e=>{let t=0,i=0,r=85^e;128&r&&(r&=-129,t=-1),i=4+((240&r)>>4);let a=0;return a=4!==i?1<e.getUint16(t,s)-32768:"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):j(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Se(e,t,s)-2**23:"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Se(e,t,i)<<8>>8)(e,t,s):j(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-2**31:"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):j(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):j(!1);break;default:Te(a),j(!1)}switch(a){case 1:"ulaw"===r||"alaw"===r?(this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0)):(this.outputSampleSize=1,this.outputFormat="u8",this.writeOutputValue=(e,t,i)=>e.setUint8(t,i+128));break;case 2:this.outputSampleSize=2,this.outputFormat="s16",this.writeOutputValue=(e,t,i)=>e.setInt16(t,i,!0);break;case 3:this.outputSampleSize=4,this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i<<8,!0);break;case 4:this.outputSampleSize=4,"float"===r?(this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0)):(this.outputFormat="s32",this.writeOutputValue=(e,t,i)=>e.setInt32(t,i,!0));break;case 8:this.outputSampleSize=4,this.outputFormat="f32",this.writeOutputValue=(e,t,i)=>e.setFloat32(t,i,!0);break;default:Te(a),j(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=J(e.data),i=e.byteLength/this.decoderConfig.numberOfChannels/this.inputSampleSize,r=i*this.decoderConfig.numberOfChannels*this.outputSampleSize,a=new ArrayBuffer(r),s=new DataView(a);for(let l=0;l=n)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=n;const c=new lo({format:this.outputFormat,data:a,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(c)}async flush(){}close(){}}class Do extends Po{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}async _createDecoder(e,t){if(!(await this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(je("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=await this._track.getCodec(),r=await this._track.getDecoderConfig();return j(i&&r),Ri.includes(r.codec)?new Mo(e,t,r):new Ao(e,t,i,r)}_createPacketSink(){return new So(this._track)}async getSample(e,t={}){wo(e);for await(const i of this.mediaSamplesAtTimestamps([e],t))return i;throw new Error("Internal error: Iterator returned nothing.")}samples(e,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class No{constructor(e){if(!(e instanceof qo))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Do(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}async getBuffer(e,t){wo(e);const i=await this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)}buffers(e,t,i){return Pe(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Pe(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class Oo{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof Uo}isAudioTrack(){return this instanceof qo}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}async getInternalCodecId(){return this._backing.getInternalCodecId()}get internalCodecId(){return Lo(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}async getLanguageCode(){return this._backing.getLanguageCode()}get languageCode(){return Lo(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}async getName(){return this._backing.getName()}get name(){return Lo(this._backing.getName(),"name","getName")}async getTimeResolution(){return this._backing.getTimeResolution()}get timeResolution(){return Lo(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}async isRelativeToUnixEpoch(){return this._backing.isRelativeToUnixEpoch()}async getUnixTimeForTimestamp(e){return this._backing.getUnixTimeForTimestamp(e)}async hasUnixTimeMapping(){return null!==await this._backing.getUnixTimeForTimestamp(await this.getFirstTimestamp())}async getDisposition(){return this._backing.getDisposition()}get disposition(){return Lo(this._backing.getDisposition(),"disposition","getDisposition")}async getBitrate(){return this._backing.getBitrate()}async getAverageBitrate(){return this._backing.getAverageBitrate()}async getFirstTimestamp(){const e=await this._backing.getFirstPacket({metadataOnly:!0});return e?.timestamp??0}async computeDuration(e){const t=await this._backing.getPacket(1/0,{metadataOnly:!0,...e});return Ee((t?.timestamp??0)+(t?.duration??0),await this.getTimeResolution())}async getDurationFromMetadata(e={}){return this._backing.getDurationFromMetadata(e)}async computePacketStats(e=1/0,t){const i=new So(this);let r=1/0,a=-1/0,s=0,n=0;for await(const o of i.packets(void 0,void 0,{metadataOnly:!0,...t})){if(s>=e&&o.timestamp>=a)break;r=Math.min(r,o.timestamp),a=Math.max(a,o.timestamp+o.duration),s++,n+=o.byteLength}return{packetCount:s,averagePacketRate:s?Number((s/(a-r)).toPrecision(16)):0,averageBitrate:s?Number((8*n/(a-r)).toPrecision(16)):0}}async isLive(){return null!==await this._backing.getLiveRefreshInterval()}async getLiveRefreshInterval(){return this._backing.getLiveRefreshInterval()}canBePairedWith(e){if(!(e instanceof Oo))throw new TypeError("other must be an InputTrack.");return this.input===e.input&&this!==e&&0n!==(this._backing.getPairingMask()&e._backing.getPairingMask())}async getPairableTracks(e){return this.input.getTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableVideoTracks(e){return this.input.getVideoTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPairableAudioTracks(e){return this.input.getAudioTracks(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableVideoTrack(e){return this.input.getPrimaryVideoTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async getPrimaryPairableAudioTrack(e){return this.input.getPrimaryAudioTrack(jo({filter:e=>e.canBePairedWith(this)},e))}async hasPairableTrack(e){e&&(e=zo(e));const t=await this.input.getTracks();for(const i of t)if(this.canBePairedWith(i)&&(!e||await e(i)))return!0;return!1}hasPairableVideoTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isVideoTrack()&&(!e||await e(t)))}hasPairableAudioTrack(e){return e&&(e=zo(e)),this.hasPairableTrack(async t=>t.isAudioTrack()&&(!e||await e(t)))}}const Lo=(e,t,i)=>{if(Xe(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},zo=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 Xe(r)?r.then(i):i(r)}:void 0};class Uo extends Oo{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??"prores"===await this._backing.getCodec()}async getCodedWidth(){return this._backing.getCodedWidth()}get codedWidth(){return Lo(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}async getCodedHeight(){return this._backing.getCodedHeight()}get codedHeight(){return Lo(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}async getRotation(){return this._backing.getRotation()}get rotation(){return Lo(this._backing.getRotation(),"rotation","getRotation")}async getSquarePixelWidth(){return this._backing.getSquarePixelWidth()}get squarePixelWidth(){return Lo(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}async getSquarePixelHeight(){return this._backing.getSquarePixelHeight()}get squarePixelHeight(){return Lo(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}async getPixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:await this.getSquarePixelWidth()*await this.getCodedHeight(),den:await this.getSquarePixelHeight()*await this.getCodedWidth()}))}get pixelAspectRatio(){return this._pixelAspectRatioCache??(this._pixelAspectRatioCache=it({num:Lo(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:Lo(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*Lo(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")}))}async getDisplayWidth(){const e=await(this._backing.getMetadataDisplayWidth?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelWidth():this.getSquarePixelHeight()}get displayWidth(){const e=this._backing.getMetadataDisplayWidth?.();if(void 0!==e){const t=Lo(e,"displayWidth","getDisplayWidth");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return Lo(t,"displayWidth","getDisplayWidth")}async getDisplayHeight(){const e=await(this._backing.getMetadataDisplayHeight?.());if(null!=e)return e;return await this.getRotation()%180===0?this.getSquarePixelHeight():this.getSquarePixelWidth()}get displayHeight(){const e=this._backing.getMetadataDisplayHeight?.();if(void 0!==e){const t=Lo(e,"displayHeight","getDisplayHeight");if(null!==t)return t}const t=Lo(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return Lo(t,"displayHeight","getDisplayHeight")}async getColorSpace(){return this._backing.getColorSpace()}async hasHighDynamicRange(){const e=await this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix}async canBeTransparent(){return this._backing.canBeTransparent()}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),ko.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(await VideoDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");if(e.isMetadataOnly)throw new TypeError("packet must not be metadata-only to determine its type.");const t=await this.getCodec();if(null===t)return null;const i=await this.getDecoderConfig();return j(i),ni(t,i,e.data)}async computeFrameRateMetrics(e={}){if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!Je(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const t=await this.getTimeResolution(),i=e.targetPacketCount??256,r=new So(this),a=[];let s=-1/0,n=0;for await(const I of r.packets(void 0,void 0,{metadataOnly:!0})){if(a.length>=i&&I.timestamp>=s)break;a.push(I.timestamp),s=Math.max(s,I.timestamp),n++}const o=new Float64Array(a.length);for(let I=0;Ie-t),b=k-1>>1,w=k>>1;let T=0,S=0,v=0;for(const I of y)if(v+=f.get(I),0===T&&v>b&&(T=I),v>w){S=I;break}const P=(h/T+h/S)/2;return{underlyingFrameRate:u,bestGuessFrameRate:null!==u?u:Go(P),minFrameRate:h/p,maxFrameRate:h/m,averageFrameRate:h*k/g,medianFrameRate:P,frameRateIsConstant:null!==u&&1===m&&1===p,probedPacketCount:n}}}class qo extends Oo{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}async getCodec(){return this._backing.getCodec()}get codec(){return Lo(this._backing.getCodec(),"codec","getCodec")}async hasOnlyKeyPackets(){return await(this._backing.getHasOnlyKeyPackets?.())??!0}async getNumberOfChannels(){return this._backing.getNumberOfChannels()}get numberOfChannels(){return Lo(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}async getSampleRate(){return this._backing.getSampleRate()}get sampleRate(){return Lo(this._backing.getSampleRate(),"sampleRate","getSampleRate")}async getDecoderConfig(){return this._backing.getDecoderConfig()}async getCodecParameterString(){const e=await(this._backing.getMetadataCodecParameterString?.());if(null!=e)return e;const t=await this._backing.getDecoderConfig();return t?.codec??null}async canDecode(){try{const e=await this._backing.getDecoderConfig();if(!e)return!1;const t=await this._backing.getCodec();if(j(null!==t),yo.some(i=>i.supports(t,e)))return!0;if(e.codec.startsWith("pcm-"))return!0;if("undefined"===typeof AudioDecoder)return!1;return!0===(await AudioDecoder.isConfigSupported(e)).supported}catch(e){return ct._error("Error during decodability check:",e),!1}}async determinePacketType(e){if(!(e instanceof ar))throw new TypeError("packet must be an EncodedPacket.");return null===await this.getCodec()?null:"key"}}const Wo=e=>-(e??-1/0),Ho=e=>-e,Vo=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 Xe(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return Xe(r)?r.then(i):i(r)}:void 0}},jo=(e,t)=>({filter:e?.filter||t?.filter?i=>{const r=e?.filter?.(i)??!0,a=e=>!1!==e&&(t?.filter?.(i)??!0);return Xe(r)?r.then(a):a(r)}:void 0,sortBy:e?.sortBy||t?.sortBy?i=>{const r=e?.sortBy?.(i)??[],a=t?.sortBy?.(i)??[],s=(e,t)=>[...Array.isArray(e)?e:[e],...Array.isArray(t)?t:[t]];return Xe(r)||Xe(a)?Promise.all([r,a]).then(([e,t])=>s(e,t)):s(r,a)}:void 0}),Ko=async(e,t)=>{let i=e;if(t?.filter){const r=e.map(e=>t.filter(e));if(r.some(e=>Xe(e))){const t=await Promise.all(r);i=e.filter((e,i)=>t[i])}else i=e.filter((e,t)=>r[t])}if(!t?.sortBy)return i;const r=i.map(e=>t.sortBy(e)),a=r.some(e=>Xe(e))?await Promise.all(r):r;return i.map((e,t)=>({track:e,sortValue:a[t]})).sort((e,t)=>{const i=Array.isArray(e.sortValue)?e.sortValue:[e.sortValue],r=Array.isArray(t.sortValue)?t.sortValue:[t.sortValue],a=Math.max(i.length,r.length);for(let s=0;se.track)},Xo=(e,t)=>{const i=1e6,r=1+1e-9,a=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let T=1;T0))return null;s[T-1]=t}const n=s.slice();n.sort();let o=n[Math.floor(.05*n.length)];for(let T=0;T<6;T++){let e=0,t=0;for(const a of s){const i=Math.max(1,Math.round(a/o));Math.abs(a-i*o)>=r||(e+=a,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let c=0,l=0,u=0;for(const T of s){const e=Math.max(1,Math.round(T/o));Math.abs(T-e*o)>=r||(c++,l+=T,u+=e)}if(c/s.length<.98)return null;o=l/u;const h=1/Math.min(u,1e3),d=Math.max(Number.EPSILON,o-h),f=o+h,m=t/f,p=t/d,g=t/o;let k=null,y=1/0;for(const T of a){if(Tp)continue;const e=Math.abs(T/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,a=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof dn)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof Os||e.source instanceof Ls))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof Os&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof Yo))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=e.initInput??null,this._formatOptions=e.formatOptions??{},e.source instanceof Os?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}async _getSourceUncached(e){j(this._rootSource instanceof zs);const t=await this._rootSource._resolveRequest(e);return this._emit("source",{source:t.source,request:e,isRoot:e.isRoot}),t}_getSourceCached(e,t=1){const i=this._sourceCache.find(i=>i.cacheGroup===t&&Us(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&Us(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const a=(async()=>{const i=await this._getSourceUncached(e);if(et(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=tt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);j(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),ye(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);j(-1!==r),this._sourceCachePromises.splice(r,1);return{request:e,sourceRef:i,age:this._nextSourceCacheAge++,cacheGroup:t}})();return this._sourceCachePromises.push({request:e,cacheGroup:t,promise:a}),a.then(e=>{const t=e.sourceRef.source.ref();return this._sourceCache.push(e),t})}_getDemuxer(){return this._demuxerPromise??(this._demuxerPromise=(async()=>{this._reader=new ec(this._rootSource),this._emit("source",{source:this._rootSource,request:null,isRoot:!0});for(const e of this._formats){if(await e._canReadInput(this))return this._format=e,this._onFormatDetermined?.(e),e._createDemuxer(this)}throw new Jo})())}get source(){return this._rootSource}async getFormat(){return await this._getDemuxer(),j(this._format),this._format}async canRead(){try{return await this._getDemuxer(),!0}catch(e){if(e instanceof Jo)return!1;throw e}}async getFirstTimestamp(e){e??(e=await this.getTracks());const t=e.filter(e=>null!==e);if(0===t.length)return 0;const i=await Promise.all(t.map(e=>e._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>e?.timestamp??1/0));return r===1/0?0:r}async computeDuration(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e);if(0===i.length)return 0;const r=await Promise.all(i.map(e=>e.computeDuration(t)));return Math.max(...r)}async getDurationFromMetadata(e,t){e??(e=await this.getTracks());const i=e.filter(e=>null!==e),r=(await Promise.all(i.map(e=>e.getDurationFromMetadata(t)))).filter(e=>null!==e);return 0===r.length?null:Math.max(...r)}async getTracks(e){e&&(e=Vo(e));const t=(await this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return Ko(t,e)}async getVideoTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isVideoTrack());return Ko(t,e)}async getAudioTracks(e){e&&(e=Vo(e));const t=(await this.getTracks()).filter(e=>e.isAudioTrack());return Ko(t,e)}async getPrimaryVideoTrack(e){e&&(e=Vo(e));const t=jo(e,{sortBy:async e=>[Ho((await e.getDisposition()).default),Ho(await e.hasPairableAudioTrack()),Ho(!(await e.hasOnlyKeyPackets())),Wo(await e.getBitrate())]});return(await this.getVideoTracks(t))[0]??null}async getPrimaryAudioTrack(e){e&&(e=Vo(e));const t=await this.getPrimaryVideoTrack(),i=jo(e,{sortBy:async e=>[Ho(!t||e.canBePairedWith(t)),Ho((await e.getDisposition()).default),Wo(await e.getBitrate())]});return(await this.getAudioTracks(i))[0]??null}async _getTrackBackings(){const e=await this._getDemuxer();return this._trackBackingsCache??(this._trackBackingsCache=await e.getTrackBackings())}_wrapBackingAsTrack(e){const t=this._backingToTrack.get(e);if(t)return t;const i="video"===e.getType()?new Uo(this,e):new qo(this,e);return this._backingToTrack.set(e,i),i}async getMimeType(){return(await this._getDemuxer()).getMimeType()}async getMetadataTags(){return(await this._getDemuxer()).getMetadataTags()}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class Jo extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class Zo extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class ec{constructor(e){this.source=e}get fileSize(){const e=this.source._getFileSize();if(void 0===e)throw new Error("Reading file size too early; read required first.");return e}get fileSizeNonStrict(){return this.source._getFileSize()??null}requestSlice(e,t){if(this.source._disposed)throw new Zo;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 tc(t,J(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Ns);return Xe(r)?r.then(t=>t?new tc(t.bytes,t.view,t.offset,e,i):null):r?new tc(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new Zo;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),a=r=>r||(j(null!==this.fileSizeNonStrict),this.requestSlice(e,Ie(this.fileSizeNonStrict-e,t,i)));return Xe(r)?r.then(a):a(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(async()=>{const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(Xe(i)&&(i=await i),!i||0===i.length)break;const r=rc(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const a of e)i.set(a,r),r+=a.length;return new tc(i,J(i),0,0,t)})()}}class tc{constructor(e,t,i,r,a){this.bytes=e,this.view=t,this.offset=i,this.start=r,this.end=a,this.bufferPos=r-i}static tempFromBytes(e){return new tc(e,J(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new tc(this.bytes,this.view,this.offset,e,e+t)}}const ic=(e,t)=>{if(e.filePose.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.`)},rc=(e,t)=>{ic(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},ac=e=>(ic(e,1),e.view.getUint8(e.bufferPos++)),sc=(e,t)=>{ic(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},nc=e=>{ic(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},oc=e=>{ic(e,3);const t=Se(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},cc=e=>{ic(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},lc=(e,t)=>{ic(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},uc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},hc=e=>{ic(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},dc=e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},fc=(e,t)=>{let i,r;return t?(i=lc(e,!0),r=lc(e,!0)):(r=lc(e,!1),i=lc(e,!1)),4294967296*r+i},mc=e=>4294967296*uc(e)+uc(e),pc=e=>4294967296*dc(e)+uc(e),gc=e=>{const t=hc(e),i=(e=>{ic(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},kc=e=>{ic(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},yc=e=>{ic(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},bc=(e,t)=>{ic(e,t);let i="";for(let r=0;rZ.decode(rc(e,t)).split("\n").map(e=>e.trim()).filter(e=>e.length>0&&!i?.ignore?.(e));var Tc,Sc,vc,Pc;(Sc=Tc||(Tc={}))[Sc.Unsynchronisation=128]="Unsynchronisation",Sc[Sc.ExtendedHeader=64]="ExtendedHeader",Sc[Sc.ExperimentalIndicator=32]="ExperimentalIndicator",Sc[Sc.Footer=16]="Footer",(Pc=vc||(vc={}))[Pc.ISO_8859_1=0]="ISO_8859_1",Pc[Pc.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",Pc[Pc.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",Pc[Pc.UTF_8=3]="UTF_8";const Ic=128,xc=10,Cc=["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"],Bc=(e,t)=>{var i;const r=e.filePos;t.raw??(t.raw={}),(i=t.raw).TAG??(i.TAG=rc(e,Ic-3)),e.filePos=r;const a=Ec(e,30);a&&(t.title??(t.title=a));const s=Ec(e,30);s&&(t.artist??(t.artist=s));const n=Ec(e,30);n&&(t.album??(t.album=n));const o=Ec(e,4),c=Number.parseInt(o,10);Number.isInteger(c)&&c>0&&(t.date??(t.date=new Date(String(c))));const l=rc(e,30);let u;if(0===l[28]&&0!==l[29]){const i=l[29];i>0&&(t.trackNumber??(t.trackNumber=i)),e.skip(-30),u=Ec(e,28),e.skip(2)}else e.skip(-30),u=Ec(e,30);u&&(t.comment??(t.comment=u));const h=ac(e);h{const i=rc(e,t),r=$e(i.indexOf(0),i.length),a=i.subarray(0,r);let s="";for(let n=0;n{const t=e.filePos,i=bc(e,3),r=ac(e),a=ac(e),s=ac(e),n=uc(e);if("ID3"!==i||255===r||255===a||0!==(2155905152&n))return e.filePos=t,null;let o=Ji(n);return s&Tc.Footer&&(o+=xc),{majorVersion:r,revision:a,flags:s,size:o}},Rc=(e,t,i)=>{var r,a,s,n,o;if(![2,3,4].includes(t.majorVersion))return void ct._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Tc.Footer?t.size-xc:t.size,l=rc(e,c),u=new Fc(t,l);if(t.flags&Tc.Unsynchronisation&&3===t.majorVersion&&u.ununsynchronizeAll(),t.flags&Tc.ExtendedHeader){const e=u.readU32();3===t.majorVersion?u.pos+=e:u.pos+=e-4}for(;u.pos<=u.bytes.length-u.frameHeaderSize();){const e=u.readId3V2Frame();if(!e)break;const c=u.pos,l=u.pos+e.size;let h=!1,d=!1,f=!1;if(3===t.majorVersion?(h=!!(64&e.flags),d=!!(128&e.flags)):4===t.majorVersion&&(h=!!(4&e.flags),d=!!(8&e.flags),f=!!(2&e.flags)||!!(t.flags&Tc.Unsynchronisation)),h)ct._warn(`Skipping encrypted ID3v2 frame ${e.id}`),u.pos=l;else if(d)ct._warn(`Skipping compressed ID3v2 frame ${e.id}`),u.pos=l;else{if(f&&u.ununsynchronizeRegion(u.pos,l),i.raw??(i.raw={}),"TXXX"===e.id){const e=(r=i.raw).TXXX??(r.TXXX={}),t=u.readId3V2TextEncoding(),a=u.readId3V2Text(t,l),s=u.readId3V2Text(t,l);e[a]??(e[a]=s)}else"T"===e.id[0]?(a=i.raw)[s=e.id]??(a[s]=u.readId3V2EncodingAndText(l)):(n=i.raw)[o=e.id]??(n[o]=u.readBytes(e.size));switch(u.pos=c,e.id){case"TIT2":case"TT2":i.title??(i.title=u.readId3V2EncodingAndText(l));break;case"TIT3":case"TT3":i.description??(i.description=u.readId3V2EncodingAndText(l));break;case"TPE1":case"TP1":i.artist??(i.artist=u.readId3V2EncodingAndText(l));break;case"TALB":case"TAL":i.album??(i.album=u.readId3V2EncodingAndText(l));break;case"TPE2":case"TP2":i.albumArtist??(i.albumArtist=u.readId3V2EncodingAndText(l));break;case"TRCK":case"TRK":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.trackNumber??(i.trackNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.tracksTotal??(i.tracksTotal=r))}break;case"TPOS":case"TPA":{const e=u.readId3V2EncodingAndText(l).split("/"),t=Number.parseInt(e[0],10),r=e[1]&&Number.parseInt(e[1],10);Number.isInteger(t)&&t>0&&(i.discNumber??(i.discNumber=t)),r&&Number.isInteger(r)&&r>0&&(i.discsTotal??(i.discsTotal=r))}break;case"TCON":case"TCO":{const e=u.readId3V2EncodingAndText(l);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Cc[e]){i.genre??(i.genre=Cc[e]);break}}i.genre??(i.genre=e)}break;case"TDRC":case"TDAT":{const e=u.readId3V2EncodingAndText(l),t=new Date(e);Number.isNaN(t.getTime())||(i.date??(i.date=t))}break;case"TYER":case"TYE":{const e=u.readId3V2EncodingAndText(l),t=Number.parseInt(e,10);Number.isInteger(t)&&(i.date??(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.lyrics??(i.lyrics=u.readId3V2Text(e,l))}break;case"COMM":case"COM":{const e=u.readU8();u.pos+=3,u.readId3V2Text(e,l),i.comment??(i.comment=u.readId3V2Text(e,l))}break;case"APIC":case"PIC":{const e=u.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=u.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=u.readId3V2Text(e,l);const a=u.readU8(),s=u.readId3V2Text(e,l).trimEnd(),n=l-u.pos;if(n>=0){const e=u.readBytes(n);i.images||(i.images=[]),i.images.push({data:e,mimeType:r,kind:3===a?"coverFront":4===a?"coverBack":"unknown",description:s})}}break;default:u.pos+=e.size}u.pos=l}}};class Fc{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{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:Ji(t);s(e)&&(i=e)}return this.pos=a,{id:e,size:i,flags:r}}}readId3V2TextEncoding(){const e=this.readU8();if(e>3)throw new Error(`Unsupported text encoding: ${e}`);return e}readId3V2Text(e,t){const i=this.pos,r=this.readBytes(t-this.pos);switch(e){case vc.ISO_8859_1:{let e="";for(let t=0;t0===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=$e(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=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}case vc.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=$e(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 vc.UTF_8:{const e=$e(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),Z.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ac{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch{i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(a){try{r?.disconnect()}catch(s){console.warn("MediaBunny gain setup cleanup:",s)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),a}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{t?.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Mc{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(a){r=!0,i=a}try{e.disconnect()}catch(a){r||(r=!0,i=a)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const a=function(e,t,i,r){const a=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(a+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(a,r),offset:a=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===a.offset?s.start(a.startAt):s.start(a.startAt,a.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,a.endMediaTime)}catch(n){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw n}}}const Dc=Symbol("cancelled");class Nc{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Dc);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function Oc(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class Lc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}async stopIterator(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),await t}cancel(){this.task?.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}async run(e){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Nc;this.task=r;let a=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!a||this.host.audioIterator===a);try{for(a=t.buffers(this.host.currentTime),this.host.audioIterator=a;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=await r.wait(a.next());if(i===Dc||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if(await r.wait(this.contexts.resume(i))===Dc||!s())return;Oc(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(await r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(await r.delay(50))||!s())return}}catch(n){if(s())throw n}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}}}class zc{constructor(e,h){N(this,u),N(this,t,!1),N(this,i,0),N(this,r),N(this,a),N(this,s),N(this,n,null),N(this,o,null),N(this,c,null),N(this,l),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,O(this,r,new Ac(this)),O(this,a,new Mc(this)),O(this,s,new Lc(this,D(this,r),D(this,a))),O(this,l,h)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){D(this,r).ensure(e)}updateGain(){D(this,r).updateGain()}stopQueuedNodes(){D(this,a).stop()}async stopIterator(){await D(this,s).stopIterator()}handleNoAudioTrack(){D(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){z(this,i)._++;try{this.pause()}finally{O(this,c,null),this.input=null,this.audioSink=null}}async load(e,r){if(D(this,t))return;this.cancelPending();const a=D(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>L(this,u,h).call(this,e,a,r));O(this,c,s);try{await s}finally{D(this,c)===s&&O(this,c,null)}}async runIterator(e){D(this,t)||await D(this,s).run(e)}async play(){if(D(this,t))return;if(D(this,o))return D(this,o);if(!this.paused)return;const e=new Nc;O(this,n,e);const r=D(this,i),a=L(this,u,f).call(this,e,r);O(this,o,a);try{await a}finally{D(this,n)===e&&(O(this,n,null),O(this,o,null))}}pause(){this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,D(this,n)?.cancel(),O(this,n,null),O(this,o,null),D(this,s).cancel(),this.stopQueuedNodes()}async seek(e){if(D(this,t))return;const i=!this.paused;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=this.audioContext?.currentTime??0,this.latestScheduledEndTime=this.playbackTimeAtStart;const r=++this.asyncId;i&&L(this,u,d).call(this,r)}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){if(D(this,t)||e===this.playbackRate)return;const i=this.currentTime;D(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=i,this.audioContextStartTime=this.audioContext?.currentTime??0,this.playbackRate=e,this.latestScheduledEndTime=i;const r=++this.asyncId;this.paused||L(this,u,d).call(this,r)}destroy(){if(D(this,t))return;O(this,t,!0),z(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>D(this,r).destroy()])try{t()}catch(a){e.push(a)}if(this.input=null,this.audioSink=null,O(this,c,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,a=new WeakMap,s=new WeakMap,n=new WeakMap,o=new WeakMap,c=new WeakMap,l=new WeakMap,u=new WeakSet,h=async function({input:e,audioTrack:r,duration:a},s,n){const o=()=>!D(this,t)&&D(this,i)===s;if(o()){this.input=e,this.duration=a;try{const e=r&&null!==r.codec&&await r.canDecode();if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new No(r)}else this.handleNoAudioTrack();o()&&n?.()}catch(c){if(o())throw c}}},d=function(e){this.runIterator(e).catch(i=>{if(!D(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{D(this,l)?D(this,l).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=async function(e,a){const s=()=>!D(this,t)&&!e.cancelled&&D(this,i)===a;try{const t=D(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if(await e.wait(D(this,r).resume(t))===Dc||!s())return}if(D(this,c)){if(await e.wait(D(this,c))===Dc||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,L(this,u,d).call(this,++this.asyncId)}catch(n){if(s())throw n}};const Uc=new WeakMap;async function qc(e,t,i){const{input:r,loadSeq:a}=e;if(!e.media?.isHls||!r||e.destroyed)return;const s={};Uc.set(e,s);const n=()=>!e.destroyed&&e.loadSeq===a&&e.input===r&&Uc.get(e)===s;for(;n();){const a=e.media;if(!a?.isHls)return;let s;try{s=await i(r,a,t,n)}catch(o){if(!n())return;if(e.media===a)throw o;continue}if(!n())return;if(e.media===a){if(s)try{await e.replaceTracks(s)}catch(o){if(n())throw o}return}}}async function Wc(e,t,i,r){const a=await e.getVideoTracks();if(!r())return null;const s="auto"===i?await e.getPrimaryVideoTrack():a.find(e=>e.id===i)??t.videoTrack;if(!r()||!s)return null;let n=t.audioTrack,o=t.audioMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableAudioTrack(),o="auto"),{videoTrack:s,audioTrack:n,videoMode:"auto"===i?"auto":"manual",audioMode:o}}async function Hc(e,t,i,r){const a=await e.getAudioTracks();if(!r())return null;const s="auto"===i?t.videoTrack?await t.videoTrack.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack():a.find(e=>e.id===i)??t.audioTrack;if(!r()||!s)return null;let n=t.videoTrack,o=t.videoMode;return n&&s.canBePairedWith(n)||(n=await s.getPrimaryPairableVideoTrack(),o="auto"),{videoTrack:n,audioTrack:s,videoMode:o,audioMode:"auto"===i?"auto":"manual"}}async function Vc(e){return await e.getAverageBitrate()??await e.getBitrate()??0}const jc=/\.m3u8(?:$|[?#])/i;function Kc(e){return"string"===typeof e&&jc.test(e)}function Xc(e){const t=function(e){return"string"===typeof e?new Ks(e):e instanceof Blob?new Hs(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new Gs(e):e??null}(e);return t?new Yo({source:t,formats:Kc(e)?On:Nn}):null}class $c{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){return this.controller?.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}async wait(e,t){try{await Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,e?.dispose()}cancel(){if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),this.controller?.abort(),this.disposeInput()}}}async function Gc({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),a=t||i,s=Boolean(a&&await a.isLive());let n=Number.NaN;return r.length>0&&(n=await e.getDurationFromMetadata(r,{skipLiveWait:!0}),null!==n||s||(n=await e.computeDuration(r,{skipLiveWait:!0}))),s?Number.POSITIVE_INFINITY:n??Number.NaN}function Qc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class Yc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return{...Qc(),source:this.host.loadSeq,complete:Qc()}}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,e?.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,e?.complete.resolve(),e?.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}async runPlay(e){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(await this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,await this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),Oc(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}}seek(e,t){return this.position(async t=>{const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();await Promise.all([i,r])},["seeked"],!1,t)}replace(e,t){return this.position(async i=>{e.duration=await Gc(e),i()&&(this.host.media=e,await Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(await Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))},["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=r??(this.seeking?this.wanted:!this.host.paused),this.cancelPlay();const a=this.seeking,s=this.operation();return this.seeking=s,a?.complete.resolve(),a?.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}async runPosition(e,t,i,r){const a=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!a())return;if(this.host.ended=!1,this.host.seeking=!0,Oc(this.host.events,a,["seeking","waiting"]),!a())return;if(r||this.stop(),!a())return;if(await t(a),!a())return;if(this.host.seeking=!1,e.complete.resolve(),Oc(this.host.events,a,i),!a())return;this.seeking=null,s=this.wanted}catch(n){if(!a())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(n),n}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&await this.play()}}const Jc=new WeakMap,Zc=new WeakMap;function el(e){const t=Zc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>e.value??null);Zc.set(e,i);const r=()=>{Zc.get(e)===i&&Zc.delete(e)};return i.then(r,r),i}function tl(e,t,i,r,a){const s=i?Math.max(.06,r/Math.max(1,a)):0;return i&&e{if(this.image===a&&t()){this.cancel();try{i(a)}catch(e){r(e)}}},a.onerror=()=>{this.image===a&&this.cancel()},a.src=e}}class rl{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}async update(e){const t=this.host.videoIterator;if(!t||!this.ready()||!this.current(e)||this.host.isFetching)return;const i={};this.fetching=i,this.host.isFetching=!0;const r=()=>this.current(e)&&this.host.videoIterator===t;try{for(;r();){const e=await el(t);if(!r()||!e)return;const i=this.host.audioClock?.currentTime;if(void 0===i)return;const a=tl(e.timestamp,i,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==a){if("draw"!==a)return void(this.host.nextFrame=e);this.draw(e)}}}catch(a){if(r())throw a}finally{this.fetching===i&&(this.fetching=null,this.host.isFetching=!1)}}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void Oc(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(Oc(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!D(this,w),e=>L(this,P,E).call(this,e,!0),e=>L(this,P,C).call(this,e)))}async preflight(e,t,i){return async function(e,t,i,r,a=()=>!0){if(r?.aborted||!a())return!1;if(!t||"string"!==typeof e||Kc(e))return!0;try{const t=await fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if(r?.aborted||!a())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!(r?.aborted||!a())&&(console.warn("Preflight check failed:",s),!0)}}(e,this.preflightRange,this.events,t,i)}drawPoster(){if(D(this,b)||!this.poster||this.posterDrawn)return;const e=D(this,m);D(this,T).draw(this.poster,()=>L(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,L(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>L(this,P,C).call(this,e))}async stopIterator(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,await function(e){if(!e)return Promise.resolve();const t=Jc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return Jc.set(e,i),i}(e)}clear(){L(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){z(this,m)._++,z(this,p)._++,this.stop(),L(this,P,B).call(this),D(this,T).cancel(),O(this,w,!1),O(this,g,null),O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null}async load(e,t){if(D(this,b))return;this.cancelPending();const i=D(this,m),r=D(this,p);O(this,w,!0);const a=Promise.resolve().then(()=>L(this,P,_).call(this,e,i,r,t));O(this,g,a);try{await a}finally{D(this,g)===a&&O(this,g,null)}}handleNoVideoTrack(){D(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}async resetIterator(e){if(D(this,b))return;const t=D(this,m),i=++z(this,p)._,r=D(this,g);this.stop(),D(this,T).cancel(),O(this,w,!0);try{r&&await r,await L(this,P,R).call(this,e,t,i)}catch(a){if(L(this,P,I).call(this,t)&&D(this,p)===i)throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}}async updateNextFrame(e){await D(this,S).update(e)}render(){D(this,S).render()}start(e){D(this,S).start(e)}stop(){D(this,S).stop()}async seek(e){await this.resetIterator(e)}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){D(this,b)||(O(this,b,!0),z(this,m)._++,D(this,S).destroy(),D(this,T).cancel(),L(this,P,B).call(this),this.posterDrawn=!1,O(this,k,null),O(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,w=new WeakMap,T=new WeakMap,S=new WeakMap,v=new WeakMap,P=new WeakSet,I=function(e){return!D(this,b)&&D(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){D(this,b)||(L(this,P,B).call(this),D(this,v)?D(this,v).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){D(this,T).cancel(),t&&this.clear(),L(this,P,x).call(this).drawImage(e.canvas,0,0)},_=async function(e,t,i,r){if(L(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:a,videoTrack:s,duration:n}=e;if(this.input=a,this.duration=n,!s)return this.handleNoVideoTrack(),void r?.();const o=null!==s.codec&&await s.canDecode();if(!L(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void r?.();const c=await s.canBeTransparent();if(!L(this,P,I).call(this,t))return;O(this,k,()=>new Fo(s,{poolSize:2,fit:"contain",alpha:c})),this.videoSink=D(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,r?.(),L(this,P,I).call(this,t)&&await L(this,P,R).call(this,0,t,i)}catch(a){if(L(this,P,I).call(this,t))throw L(this,P,B).call(this),a}finally{L(this,P,I).call(this,t)&&D(this,p)===i&&O(this,w,!1)}},R=async function(e,t,i){if(!L(this,P,I).call(this,t)||D(this,p)!==i)return;L(this,P,B).call(this),D(this,k)&&this.videoSink===D(this,y)&&(this.videoSink=D(this,k).call(this));const r=this.videoSink;if(!r||!L(this,P,I).call(this,t))return;O(this,y,r);const a=r.canvases(e);this.videoIterator=a;const s=()=>L(this,P,I).call(this,t)&&D(this,p)===i&&this.videoIterator===a,n=await el(a);if(!s())return;const o=await el(a);s()&&(this.nextFrame=o,n?L(this,P,E).call(this,n,!1):this.drawPoster())};class sl{constructor({canvas:e,ctx:t,events:i,option:r={}}){N(this,F),this.events=i,this.option=r,this.audio=new zc(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new al({canvas:e,ctx:t,events:i,timeupdateInterval:r.timeupdateInterval??250,avSyncTolerance:r.avSyncTolerance??.12,dropLateFrames:r.dropLateFrames??!1,poster:r.poster??"",preflightRange:r.preflightRange??!1,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,O(this,F,new Yc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,D(this,F).ended(),this.audio.pause())})}async load(e){if(this.destroyed)return;const t=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),this.loadSession?.cancel(),t!==this.loadSeq||this.destroyed)return;if(this.pause(),t!==this.loadSeq||this.destroyed)return;this.disposeInput();const i=new $c;this.loadSession=i,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,i.defer(()=>this.events.emit("waiting")),i.defer(()=>this.events.emit("loadstart"));const r=Number.isFinite(this.option.loadTimeout)?this.option.loadTimeout??0:0;try{await i.wait(this.performLoad(e,t,i),r)}catch(a){if(t!==this.loadSeq)return;const e=++this.loadSeq;if(D(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),i.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}}async performLoad(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(await this.video.preflight(e,i.signal,r))||!r())return;const a=Xc(e);if(!a)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(a);const s=await async function(e,t){const i=await e.getPrimaryVideoTrack(),r=i?await i.getPrimaryPairableAudioTrack():await e.getPrimaryAudioTrack(),a=await Gc({input:e,videoTrack:i,audioTrack:r}),s=i||r,n=Kc(t);return{input:e,videoTrack:i,audioTrack:r,duration:a,isLive:!Number.isFinite(a)&&Boolean(s&&await s.isLive()),isHls:n,videoMode:n?"auto":"manual",audioMode:n?"auto":"manual"}}(a,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=a,this.media=s;const n=function(e,t){let i=!1,r=!1,a=!1;function s(s){t()&&!a&&("video"===s?i=!0:r=!0,i&&r&&(a=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,Oc(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,n.video),t=r()?this.audio.load(s,n.audio):Promise.resolve();if(await Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,Oc(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){this.loadSession?.disposeInput(),this.input=null,this.media=null}async replaceTracks(e){if(this.media&&!this.destroyed)return D(this,F).replace({...this.media,...e},this.currentTime)}async selectHlsQuality(e){return function(e,t){return qc(e,t,Wc)}(this,e)}async selectHlsAudio(e){return function(e,t){return qc(e,t,Hc)}(this,e)}async getHlsState(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=await async function(e){if(!e?.isHls||!e.input)return null;const[t,i]=await Promise.all([e.input.getVideoTracks(),e.videoTrack?e.videoTrack.getPairableAudioTracks():[]]),[r,a]=await Promise.all([Promise.all(t.map(async(e,t)=>({id:e.id,track:e,index:t,name:await e.getName(),height:await e.getDisplayHeight(),bitrate:await Vc(e)}))),Promise.all(i.map(async(e,t)=>{const i=await e.getName(),r=await e.getLanguageCode();return{id:e.id,track:e,index:t,name:i,lang:r,language:r,bitrate:await Vc(e)}}))]);return{levels:r,audios:a,currentLevel:e.videoTrack?r.find(t=>t.id===e.videoTrack?.id)??null:null,currentAudio:e.audioTrack?a.find(t=>t.id===e.audioTrack?.id)??null:null,videoMode:e.videoMode??"auto",audioMode:e.audioMode??"auto"}}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}}async play(){return D(this,F).play()}pause(){D(this,F).pause()}async seek(e){return D(this,F).seek(e)}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,D(this,F).invalidate();const e=[];for(const i of[()=>this.loadSession?.cancel(),()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){return this.media?.duration??this.audio.duration??this.video.duration}get videoWidth(){return this.video.width}get videoHeight(){return this.video.height}}F=new WeakMap;const nl=new WeakMap;function ol(e){let t=nl.get(e);return t||(t={closed:!1,frames:new Set},nl.set(e,t)),t}class cl{constructor({art:e,canvas:t,ctx:i,option:r}){this.art=e,this.canvas=t,this.option=r,this.events=new V,this.engine=new sl({canvas:t,ctx:i,events:this.events,option:r}),this._src=null,this._volume=r.volume??.7,this._muted=!!r.muted,this._playbackRate=1,this.engine.setVolume(this._volume,this._muted),this.setupEventForwarding(),r.source?this.src=r.source:e.option?.url&&(this.src=e.option.url)}setupEventForwarding(){const{events:e}=this.art.constructor.config;e.forEach(e=>{this.events.addEventListener(e,e=>{this.art.emit(`video:${e.type}`,e)})})}addEventListener(e,t){this.events.addEventListener(e,t)}removeEventListener(e,t){this.events.removeEventListener(e,t)}get src(){return this._src}set src(e){this._src=e,e&&this.engine.load(e)}get currentSrc(){return this._src}get currentTime(){return this.engine.currentTime}set currentTime(e){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=ol(e);if(i.closed)return 0;const r=requestAnimationFrame(a=>{i.frames.delete(r),i.closed||t(a,{presentationTime:e.engine.currentTime,expectedDisplayTime:a+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:a,receiveTime:a,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){ol(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=ol(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}function ll(e={}){return t=>{const i=t,{createElement:r}=i.constructor.utils,a=r("canvas"),s=new cl({art:i,canvas:a,ctx:a.getContext("2d"),option:e}),n=function(e,t,i,r){let a,s=!1;function n(){s||!e.template?.$player||e.option.autoSize||Object.assign(t.style,{width:"100%",height:"100%",objectFit:"contain"})}function o(){s||(s=!0,U([()=>a?.destroy(),()=>{e.mediabunny===i&&delete e.mediabunny},()=>i.destroy(),()=>e.off?.("resize",n),()=>e.off?.("video:loadedmetadata",n),()=>e.off?.("destroy",o)]))}return{install:function(){e.on("resize",n),e.on("video:loadedmetadata",n),a=H({art:e,shim:i,option:r}),e.on("destroy",o)},destroy:o}}(i,a,s,e);try{i.mediabunny=s,function(e,t){const i=new Map,r=e,a=t;for(const n in e)if("function"===typeof r[n]){const t=r[n];i.set(n,t.bind(e))}const s=new Set([...Object.getOwnPropertyNames(t),...Object.getOwnPropertyNames(Object.getPrototypeOf(t))]);for(const n of s)"constructor"===n||n in e||Object.defineProperty(e,n,{get(){const e=a[n];return"function"===typeof e?e.bind(t):e},set(e){a[n]=e},configurable:!0,enumerable:!0});for(const[n,o]of i)r[n]=(...e)=>o(...e)}(a,s),n.install()}catch(o){try{n.destroy()}catch(c){console.warn("MediaBunny entry setup cleanup:",c)}throw o}return a}}return Object.defineProperty(ll,"default",{value:ll,writable:!0,configurable:!0}),ll}); diff --git a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.legacy.js b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.legacy.js index 81d49c745..d8f8db571 100644 --- a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.legacy.js +++ b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.legacy.js @@ -4,4 +4,4 @@ * (c) 2017-2026 Harvey Zhao * Released under the MIT License. */ -!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A=Object.defineProperty,M=Object.defineProperties,D=Object.getOwnPropertyDescriptors,N=Object.getOwnPropertySymbols,O=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable,z=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),U=e=>{throw TypeError(e)},q=Math.pow,W=(e,t,i)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,H=(e,t)=>{for(var i in t||(t={}))O.call(t,i)&&W(e,i,t[i]);if(N)for(var i of N(t))L.call(t,i)&&W(e,i,t[i]);return e},V=(e,t)=>M(e,D(t)),j=(e,t,i)=>t.has(e)||U("Cannot "+i),K=(e,t,i)=>(j(e,t,"read from private field"),i?i.call(e):t.get(e)),X=(e,t,i)=>t.has(e)?U("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),$=(e,t,i,r)=>(j(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),G=(e,t,i)=>(j(e,t,"access private method"),i),Q=(e,t,i,r)=>({set _(r){$(e,t,r,i)},get _(){return K(e,t,r)}}),Y=(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())}),J=function(e,t){this[0]=e,this[1]=t},Z=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof J,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?n("return"===e?e:"next",t[1]?{done:i.done,value:i.value}:i,r,s):r({value:i,done:l})).catch(e=>n("throw",e,r,s))}catch(c){s(c)}},s=(e,t,i,s)=>a[e]=a=>(t=new Promise((t,i,s)=>(s=()=>n(e,a,t,i),r?r.then(s):s())),s=()=>r===i&&(r=0),r=i=t.then(s,s),t),a={};return i=i.apply(e,t),a[z("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},ee=e=>{var t,i=e[z("asyncIterator")],r=!1,n={};return null==i?(i=e[z("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 J(new Promise(r=>{var n=i[e](t);n instanceof Object||U("Object expected"),r(n)}),1)}}),n[z("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},te=(e,t,i)=>(t=e[z("asyncIterator")])?t.call(e):(e=e[z("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 ie(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function re(e,t,i){const r={control:!1,setting:!1};let n=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function a(){n=null,ie([()=>s("control"),()=>s("setting")])}return{update:function(o,l,c,u){if(!o)return void a();n=o;const d=()=>n===o&&c(),h=e=>Y(null,null,function*(){return d()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html});l.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:h})):s("control"),d()&&(l.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:h})):s("setting"))},clear:a}}function ne(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function se({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,n=0,s=0;const a=re(e,"mediabunny-quality",''),o=re(e,"mediabunny-audio",''),l=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;function c(){return Y(this,null,function*(){var e,s;if(r||t.engine.destroyed)return;const c=++n,d=t.engine.loadSeq,h=()=>c===n&&l(d);try{const r=yield t.getM3u8State();if(!h())return;const n=(null==(e=i.m3u8)?void 0:e.quality)||{},c=function(e,t,i){var r;if(!t.control&&!t.setting||!(null==e?void 0:e.levels.length))return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||`${e.height}P`),a=e.currentLevel?s(e.currentLevel):n,o=[];for(const u of e.levels){if(!i())return null;o.push({html:s(u),value:u.id,default:(null==(r=e.currentLevel)?void 0:r.id)===u.id})}const l=new Map(e.levels.map(e=>[e.id,e.height])),c=ne(o).sort((e,t)=>("auto"===t.value?0:l.get(t.value)||0)-("auto"===e.value?0:l.get(e.value)||0));return c.push({html:n,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:a,selector:c}}(r,n,h);if(!h())return;if(a.update(c,n,()=>l(d),(e,t)=>u("quality",e,t)),!h())return;const f=(null==(s=i.m3u8)?void 0:s.audio)||{},m=function(e,t,i){var r;if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||e.lang||e.language),a=e.currentAudio?s(e.currentAudio):n,o=[];for(const c of e.audios){if(!i())return null;o.push({html:s(c),value:c.id,default:(null==(r=e.currentAudio)?void 0:r.id)===c.id})}const l=ne(o);return l.push({html:n,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:a,selector:l}}(r,f,h);h()&&o.update(m,f,()=>l(d),(e,t)=>u("audio",e,t))}catch(f){if(h())throw f}})}function u(i,r,a){return Y(this,null,function*(){const o=++s,u=t.engine.loadSeq;n++;const h=()=>o===s&&l(u);try{"quality"===i?yield t.switchM3u8Quality(r.value):yield t.switchM3u8Audio(r.value),h()&&(yield c(),h()&&(e.notice.show=`${a}: ${r.html}`))}catch(f){if(h()&&(yield d(),h()))throw f}return r.html})}function d(){return c().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function h(){n++,s++;try{ie([a.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}return e.on("video:loadedmetadata",d),e.on("restart",d),e.on("video:loadstart",h),e.on("video:error",h),e.on("destroy",function t(){if(!r){r=!0,h();try{ie([()=>e.off("video:loadedmetadata",d),()=>e.off("restart",d),()=>e.off("video:loadstart",h),()=>e.off("video:error",h),()=>e.off("destroy",t)])}catch(i){console.warn("MediaBunny HLS listener cleanup:",i)}}}),{update:c}}class ae{constructor(){X(this,e,!1),this.listeners=new Map}addEventListener(t,i){var r;K(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),null==(r=this.listeners.get(t))||r.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){var r;if(K(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{K(this,e)||t(n)})}destroy(){$(this,e,!0),this.listeners.clear()}}function oe(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const le=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},ce=e=>e&&e[e.length-1],ue=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-q(2,r))},he=e=>{const t=ue(e);return 0===(1&t)?-(t>>1):t+1>>1},fe=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),me=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),pe=new TextDecoder,ge=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),ke={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ye=ge(ke),be={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Te=ge(be),ve={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},we=ge(ve),Se=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,Pe={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Ie=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class xe{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return Y(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 Ce=/^[0-9a-fA-F]+$/,Be=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),Ee=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,_e=(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{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},Fe=(e,t,i)=>{const r=Re(e,i(t),i);e.splice(r+1,0,t)},Ae=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},Me=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},De=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},Ne=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Oe=e=>{throw new Error(`Unexpected value: ${e}`)},Le=(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},ze=(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)},Ue=(e,t)=>({next(){return Y(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}}),qe=(e,t,i)=>Math.max(t,Math.min(i,e)),We="und",He=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Ve=(e,t)=>Math.round(e/t)*t,je=(e,t)=>Math.round(e*t)/t,Ke=(e,t)=>Math.floor(e/t)*t,Xe=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},$e=/^[a-z]{3}$/,Ge=e=>$e.test(e),Qe=1e6*(1+Number.EPSILON),Ye=(e,t)=>{const i=H(H({},e),t);if(e.headers||t.headers){const r=e.headers?Je(e.headers):{},n=t.headers?Je(t.headers):{},s=H({},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},Je=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},Ze=(e,t,i,r,n)=>Y(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(Pt._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 Tt(1e3*e)),n())throw a}});class et{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let tt=null;const it=()=>{var e;return null!==tt?tt:tt=!("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 rt=null;const nt=()=>{var e;return null!==rt?rt:rt="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let st=null;const at=()=>{var e;return null!==st?st:st=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},ot=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,lt=Y(null,null,function*(){}).constructor,ct=e=>e instanceof lt||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),ut=(e,t)=>-1!==e?e:t,dt=(e,t,i,r)=>e<=r&&i<=t,ht=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},mt=e=>"number"===typeof e&&!Number.isNaN(e),pt=(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("/")},gt=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{oe(Number.isInteger(e.num)),oe(Number.isInteger(e.den)),oe(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}},bt=(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.`)},Tt=e=>new Promise(t=>setTimeout(t,e));class vt{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)}}}var wt,St;(St=wt||(wt={}))[St.Silent=0]="Silent",St[St.Errors=1]="Errors",St[St.Warnings=2]="Warnings",St[St.Info=3]="Info";class Pt{constructor(){}static get level(){return Pt._level}static set level(e){if(e!==wt.Silent&&e!==wt.Errors&&e!==wt.Warnings&&e!==wt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Pt._level=e}static get _emitter(){var e;return null!=(e=Pt._emitterInstance)?e:Pt._emitterInstance=new vt}static on(e,t,i){return Pt._emitter.on(e,t,i)}static _error(...e){Pt._emitter._emit("error",e),Pt._level>=wt.Errors&&console.error(...e)}static _warn(...e){Pt._emitter._emit("warn",e),Pt._level>=wt.Warnings&&console.warn(...e)}static _info(...e){Pt._emitter._emit("info",e),Pt._level>=wt.Info&&console.info(...e)}}Pt._level=wt.Info,Pt._emitterInstance=null;class It{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 xt{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 Ct={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Bt{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;return this.pos++,n}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}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 Bt(this.bytes);return e.pos=this.pos,e}}const Et=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],_t=[-1,1,2,3,4,5,6,8],Rt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Bt(e),i=Ft(t),{frequencyIndex:r,sampleRate:n}=At(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=_t[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=At(t).sampleRate,o=Ft(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Ft(t)&&t.readBits(1)&&(c=At(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(l=!!t.readBits(1)));break}t.pos=e+1}return null!==a&&a>1&&(l=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:c,outputNumberOfChannels:l&&1===a?2:a}},Ft=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},At=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let n=0;t+3i&&(yield{offset:i,length:t-i}),i=t+n,t=i):t++}-1!==i&&i{if(t.description){const i=3&fe(t.description)[4];return qt(e,i+1)}return Ut(e)},Ht=e=>31&e,Vt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+jt.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(jt,r),r+=jt.byteLength,i.set(n,r),r+=n.byteLength;return i},Xt=(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:ze(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},$t=e=>{try{const t=[],i=[],r=[];for(const o of Ut(e)){const n=e.subarray(o.offset,o.offset+o.length),s=Ht(n[0]);s===Nt.SPS?t.push(n):s===Nt.PPS?i.push(n):s===Nt.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=Jt(n);oe(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 Pt._error("Error building AVC Decoder Configuration Record:",t),null}},Gt=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=me(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{var t;try{const i=Vt(e),r=new Bt(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();ue(r);let o=1,l=0,c=0,u=0;if(100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n){o=ue(r),3===o&&(u=r.readBits(1)),l=ue(r),c=ue(r),r.skipBits(1);if(r.readBits(1))for(let e=0;e<(3!==o?8:12);e++){if(r.readBits(1)){const t=e<6?16:64;let i=8,n=8;for(let e=0;ee.level>=a))?t:ce(Gi),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);P=n,I=n}else P=0,I=0}return oe(null!==I),{emulationUnpreventedBytes:i,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:o,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:k,pixelAspectRatio:S,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:w,numReorderFrames:P,maxDecFrameBuffering:I,vuiParametersFlagBitOffset:B,bitstreamRestrictionFlagBitOffset:x,bitstreamRestrictionFlag:C}}catch(i){return Pt._error("Error parsing AVC SPS:",i),null}},Zt=e=>{const t=ue(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)ue(e),ue(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},ei=e=>{oe(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Bt(e.emulationUnpreventedBytes),r=new Bt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(oe(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),de(r,2),de(r,1),de(r,16),de(r,16),de(r,e.numReorderFrames),de(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return oe(Number.isInteger(n)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,n))},ti=(e,t)=>{if(t.description){const i=3&fe(t.description)[21];return qt(e,i+1)}return Ut(e)},ii=e=>e>>1&63,ri=e=>{try{const t=new Bt(Vt(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}=si(t,i);ue(t);const u=ue(t);let d=0;3===u&&(d=t.readBits(1));const h=ue(t),f=ue(t);let m=h,p=f;if(t.readBits(1)){const e=ue(t),i=ue(t),r=ue(t),n=ue(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=ue(t),k=ue(t);ue(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)ue(t),b=ue(t),ue(t);ue(t),ue(t),ue(t),ue(t),ue(t),ue(t),t.readBits(1)&&t.readBits(1)&&ai(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),ue(t),ue(t),t.skipBits(1));const T=ue(t);if(oi(t,T),t.readBits(1)){const e=ue(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of Ut(e)){const s=e.subarray(l.offset,l.offset+l.length),a=ii(s[0]);a===Lt.VPS_NUT?t.push(s):a===Lt.SPS_NUT?i.push(s):a===Lt.PPS_NUT?r.push(s):a!==Lt.PREFIX_SEI_NUT&&a!==Lt.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=ri(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Bt(Vt(e));t.skipBits(16),ue(t),ue(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),ue(t),ue(t),he(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&ue(t),he(t),he(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:Lt.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Lt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Lt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ii(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 Pt._error("Error building HEVC Decoder Configuration Record:",t),null}},si=(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;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&he(e);for(let t=0;t{const i=[];for(let r=0;r{var n;let s=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){if(t===i){o=t-(ue(e)+1)}else o=t-1;e.readBits(1),ue(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=ue(e),i=ue(e);for(let r=0;r{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=Yt[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)&&(ue(e),ue(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(ue(e),ue(e),ue(e),ue(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&ue(e),e.readBits(1)&&ui(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=ue(e),ue(e),ue(e),ue(e),ue(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},ui=(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?ue(e):i=1===e.readBits(1);let a=1;if(!i){a=ue(e)+1}r&&di(e,a,s),n&&di(e,a,s)}},di=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=hi.audAllowed;for(const s of ti(e,t)){if(r===hi.noMoreDataAllowed){i.add(s.offset);continue}const t=ii(e[s.offset]);if(r===hi.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>hi.audAllowed?n=!0:r=hi.beforeFirstVcl:t<=31?r>hi.afterFirstVcl?n=!0:r=hi.afterFirstVcl:36===t?r!==hi.afterFirstVcl?n=!0:r=hi.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>hi.beforeFirstVcl?n=!0:r=hi.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&fe(t.description)[21];return Xt(e,i+1)}return Kt(e)})(n,t)},pi={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},gi=e=>{var t,i,r;const n=new Bt(e);if(2!==n.readBits(2))return null;const s=n.readBits(1),a=(n.readBits(1)<<1)+s;3===a&&n.skipBits(1);if(1===n.readBits(1))return null;if(0!==n.readBits(1))return null;n.skipBits(2);if(4817730!==n.readBits(24))return null;let o=8;if(a>=2){o=n.readBits(1)?12:10}const l=n.readBits(3);let c=0,u=0;if(7!==l){if(u=n.readBits(1),1===a||3===a){const e=n.readBits(1),t=n.readBits(1);c=e||t?e&&!t?2:1:3,n.skipBits(1)}else c=1}else c=3,u=1;const d=(n.readBits(16)+1)*(n.readBits(16)+1);let h=ce(Qi).level;for(const m of Qi)if(d<=m.maxPictureSize){h=m.level;break}const f=pi[l];return{profile:a,level:h,bitDepth:o,chromaSubsampling:c,videoFullRangeFlag:u,colourPrimaries:null!=(t=null==f?void 0:f.colourPrimaries)?t:2,transferCharacteristics:null!=(i=null==f?void 0:f.transferCharacteristics)?i:2,matrixCoefficients:null!=(r=null==f?void 0:f.matrixCoefficients)?r:2}},ki=function*(e){const t=new Bt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*q(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>q(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);oe(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},yi=e=>{for(const{type:t,data:i}of ki(e)){if(1!==t)continue;const e=new Bt(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{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let n=0;n<=r;n++){e.skipBits(12);const r=e.readBits(5);if(0===n&&(s=r),r>7){const t=e.readBits(1);0===n&&(a=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const 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=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,T=1,v=1,w=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,T=0,v=0):(b=e.readBits(1),0===r?(T=1,v=1):1===r?(T=0,v=0):12===m?(T=e.readBits(1),v=T?e.readBits(1):0):(T=1,v=0),T&&v&&(w=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:w,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},bi=e=>{if(e.length<36)return null;const t=me(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},Ti=[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],vi=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;u97;)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}},wi=(e,t,i)=>{switch(e){case"avc":for(const e of Wt(i,t)){const t=i[e.offset],r=Ht(t);if(r>=Nt.NON_IDR_SLICE&&r<=Nt.SLICE_DPC)return"delta";if(r===Nt.IDR)return"key";if(r===Nt.SEI&&!at()){const t=i.subarray(e.offset,e.offset+e.length),r=Vt(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 Bt(r);e.pos=8*n;const t=ue(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=me(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=pe.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;c0&&(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=ht(c),i=me(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=pe.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})}}}},xi=[2,1,2,3,3,4,4,5],Ci=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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)}},Bi=[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],Ei=[1,2,3,6],_i=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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=Ei[s];let d;d=n<3?Mt[n]/1e3:Dt[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}]}},Ri=e=>{const t=e.substreams[0];return oe(t),t.fscod<3?Mt[t.fscod]:null!==t.fscod2&&t.fscod2<3?Dt[t.fscod2]:null},Fi=e=>{const t=e.substreams[0];oe(t);let i=xi[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},Ai=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Mi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Di=[16,16,20,20,0,24,24,0],Ni=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Oi=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Li=[32e3,44100,48e3,0],zi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ui=[512,1024,2048,4096],qi=e=>{const t=Hi(e),i=me(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Vi(e.subarray(r));if(!t)break;null!=n||(n=t),r+=t.frameSize}if(t)return{frameSize:n?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==n};if(!(null==n?void 0:n.asset))return null;const{asset:s}=n;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Wi=e=>{const t=qi(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},Hi=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new Bt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const n=t.readBits(14)+1;if(n<96)return null;const s=t.readBits(6);if(s>=Ni.length)return null;const a=Ai[t.readBits(4)];if(0===a)return null;const o=Mi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const l=t.readBits(2);if(3===l)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const c=Di[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Ni[s]+(u?1:0),sampleCount:32*r,channelLayout:Oi[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},Vi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new Bt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),n=8+4*r,s=16+4*r;t.skipBits(n);const a=t.readBits(s)+1,o={frameSize:a,asset:null};if(!t.readBits(1))return o;const l=Li[t.readBits(2)],c=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===l||t.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(c*m/l),channelLayout:g,pcmResolution:f}}},ji=e=>Xe(e)+Xe(44646&e),Ki=["avc","hevc","vp9","av1","vp8","prores"],Xi=["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"],$i=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Xi],Gi=[{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}],Qi=[{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}],Yi=".01.01.01.01.00",Ji=".0.110.01.01.01.0",Zi=["ap4x","ap4h","apch","apcn","apcs","apco"],er=["dtsc","dtsh","dtsl","dtse"],tr=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(oe(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${Be(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}.${Be(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=Ee(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=me(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=Ee(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=ce(Qi).level;for(const e of Qi)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(Yi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=ce(Qi).level;for(const e of Qi)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)?ke[r.primaries]:1,u=(null==r?void 0:r.transfer)?be[r.transfer]:1,d=(null==r?void 0:r.matrix)?ve[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(Ji)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&Oe(t),new TypeError(`Unhandled codec '${t}'.`)},ir=e=>{var t,i,r,n,s,a;switch(e.codec){case"avc":{let r=null==(t=e.avcCodecInfo)?void 0:t.sequenceParameterSets[0];if(!r&&e.codecDescription&&(r=null==(i=Qt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=Jt(r);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=me(e);let i=0;const r=t.getUint8(i++),n=t.getUint8(i++),s=n>>6&3,a=n>>5&1,o=31&n,l=t.getUint32(i,!1);i+=4;const c=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,T=k>>2&1,v=3&k,w=t.getUint8(i++),S=[];for(let P=0;P>7&1,s=63&r,a=t.getUint16(i,!1);i+=2;const o=[];for(let l=0;le.nalUnitType===Lt.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=ri(t);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ye[e.vp9CodecInfo.colourPrimaries],transfer:Te[e.vp9CodecInfo.transferCharacteristics],matrix:we[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ye[e.av1CodecInfo.colourPrimaries],transfer:Te[e.av1CodecInfo.transferCharacteristics],matrix:we[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ye[e.proresCodecInfo.colourPrimaries],transfer:Te[e.proresCodecInfo.transferCharacteristics],matrix:we[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},rr=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:n}=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=Rt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return null!=n?n:"dtsc";if(t&&Xi.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},nr=48e3,sr=/^pcm-([usf])(\d+)(be)?$/,ar=e=>{if(oe(Xi.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=sr.exec(e);let i;oe(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?q(2,7):0}},or=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":Zi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":er.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":sr.test(e)?e:"webvtt"===e?"webvtt":null,lr=[44100,48e3,32e3],cr=[-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],ur=1483304551,dr=1231971951,hr=(e,t)=>3===e?3===t?21:36:3===t?13:21,fr=(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=cr[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=lr[u]>>a+o,b=((e,t,i,r,n)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var pr,gr;(gr=pr||(pr={}))[gr.FrameCount=1]="FrameCount",gr[gr.FileSize=2]="FileSize",gr[gr.Toc=4]="Toc";const kr=e=>3===e?1:2;class yr{constructor(e){this.input=e}dispose(){}}const br=new Uint8Array(0);class Tr{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===br&&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===br}get microsecondTimestamp(){return Math.trunc(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){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 Tr(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 Tr(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 vr=e=>{const t=me(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=Be(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=Cl(e);const i=Nl(e,4);let r=8;1===t&&(t=Rl(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Pr=e=>El(e)/65536,Ir=e=>El(e)/1073741824,xr=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=vl(e);if(t|=127&i,0===(128&i))break}return t},Cr=e=>{let t=Sl(e);return e.skip(2),t=Math.min(t,e.remainingLength),pe.decode(Tl(e,t))},Br=e=>{const t=Sr(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Cl(e);e.skip(4);const r=Tl(e,t.contentSize-8);switch(i){case 1:return pe.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new It(r,"image/jpeg");case 14:return new It(r,"image/png");case 27:return new It(r,"image/bmp");default:return r}},Er=16,_r=new Uint32Array(256),Rr=new Uint32Array(256),Fr=new Uint32Array(256),Ar=new Uint32Array(256),Mr=new Uint32Array(256),Dr=new Uint32Array(256),Nr=new Uint32Array(10);let Or=!1;class Lr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Er/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Er),this.out=new Uint8Array(Er),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){oe(16===e.byteLength),oe(16===t.byteLength),Or||(()=>{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);_r[s]=t<<24|t<<16|t<<8|t,Dr[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);Rr[s]=n,Fr[s]=n>>>8|n<<24,Ar[s]=n>>>16|n<<16,Mr[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Nr[s]=n<<24,n=n<<1^(128&n?283:0);Or=!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&_r[e>>>16&255]^16711680&_r[e>>>8&255]^65280&_r[e>>>0&255]^255&_r[e>>>24&255]^Nr[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>>24&255]]^Fr[255&_r[t>>>16&255]]^Ar[255&_r[t>>>8&255]]^Mr[255&_r[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=Rr[e>>>24]^Fr[r>>>16&255]^Ar[i>>>8&255]^Mr[255&t]^this.roundkey[n],c=Rr[t>>>24]^Fr[e>>>16&255]^Ar[r>>>8&255]^Mr[255&i]^this.roundkey[n+1],u=Rr[i>>>24]^Fr[t>>>16&255]^Ar[e>>>8&255]^Mr[255&r]^this.roundkey[n+2],d=Rr[r>>>24]^Fr[i>>>16&255]^Ar[t>>>8&255]^Mr[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Dr[e>>>24&255]^16711680&Dr[r>>>16&255]^65280&Dr[i>>>8&255]^255&Dr[t>>>0&255]^this.roundkey[40],f=4278190080&Dr[t>>>24&255]^16711680&Dr[e>>>16&255]^65280&Dr[r>>>8&255]^255&Dr[i>>>0&255]^this.roundkey[41],m=4278190080&Dr[i>>>24&255]^16711680&Dr[t>>>16&255]^65280&Dr[e>>>8&255]^255&Dr[r>>>0&255]^this.roundkey[42],p=4278190080&Dr[r>>>24&255]^16711680&Dr[i>>>16&255]^65280&Dr[t>>>8&255]^255&Dr[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 zr extends yr{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 Y(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return Y(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 Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(ct(r)&&(r=yield r),!r)break;const n=e,s=Sr(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Nl(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(ct(e)&&(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>n+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');yield this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=n+s.totalSize}if(!i&&this.input._initInput&&(yield this.copyMetadataFromInitInput(this.input._initInput)),t){oe(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ct(e)&&(e=yield e),oe(e);const t=Cl(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(ct(e)&&(e=yield e),e){const t=Sr(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ct(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return Y(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==zr)throw new Error("Init input must match the input's format.");yield t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const e of t.tracks){const t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};if(e.trackBacking)if(oe(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new qr(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new Wr(e),this.tracks.push(t)}}})}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;oe(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&&Xi.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){oe("audio"===(null==(i=e.info)?void 0:i.type));const t=ar(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=Re(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=ce(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;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)Xr(e,r.timestamp);else{const t=Re(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];Xr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=Re(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 Yr(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ge(t.languageCode)||(t.languageCode=We)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Nl(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:H({},Pe),avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=re,this.readContiguousBoxes(e.slice(se,ne.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=vl(e);e.skip(3);const r=Cl(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Cl(e),e.skip(8)):2===a&&(e.skip(4),c=Dl(e),o=Cl(e),e.skip(4),l=Cl(e),u=Cl(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=nr;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(er.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Pt._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":(Pt._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":(Pt._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":(Pt._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":(Pt._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(Pt._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<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==vl(e),t.encryptionInfo.defaultPerSampleIvSize=vl(e),t.encryptionInfo.defaultKid=Be(Tl(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=vl(e),r=new Uint8Array(16);r.set(Tl(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;oe("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=vl(e),n=vl(e),s=vl(e),a=s>>4,o=s>>1&7,l=1&s,c=vl(e),u=vl(e),d=vl(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;oe("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=vl(e),l=o>>5,c=31&o,u=vl(e),d=u>>7,h=u>>6&1,f=u>>4&1,m=u>>3&1,p=u>>2&1,g=3&u,k=2===l&&h?u>>5&1?12:10:h?10:8;e.skip(1);const y=Tl(e,ne.contentSize-4),b=yi(y);t.info.av1CodecInfo={profile:l,level:c,tier:d,bitDepth:k,monochrome:f,chromaSubsamplingX:m,chromaSubsamplingY:p,chromaSamplePosition:g,videoFullRangeFlag:null!=(r=null==b?void 0:b.videoFullRangeFlag)?r:0,colourPrimaries:null!=(n=null==b?void 0:b.colourPrimaries)?n:2,transferCharacteristics:null!=(s=null==b?void 0:b.transferCharacteristics)?s:2,matrixCoefficients:null!=(a=null==b?void 0:b.matrixCoefficients)?a:2}}break;case"colr":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(o=t.info)?void 0:o.type));const i=Nl(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Sl(e),n=Sl(e),s=Sl(e);let a;"nclx"===i&&(a=Boolean(128&vl(e))),t.info.colorSpace={primaries:ye[r],transfer:Te[n],matrix:we[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(l=t.info)?void 0:l.type));const i=Cl(e),r=Cl(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==(null==(c=t.info)?void 0:c.type))break;e.skip(4);oe(3===vl(e)),xr(e),e.skip(2);const i=vl(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=vl(e);e.skip(t)}n&&e.skip(2);oe(4===vl(e));const s=xr(e),a=e.filePos,o=vl(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":Pt._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){oe(5===vl(e));const i=xr(e);if(t.info.codecDescription=Tl(e,i),"aac"===t.info.codec){const e=Rt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&Sl(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=vl(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=vl(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(h=t.info)?void 0:h.type)),e.skip(1);const i=vl(e),r=Sl(e),n=Cl(e),s=Il(e),a=vl(e);let o;o=0!==a?Tl(e,2+i):new Uint8Array(0);const l=new Uint8Array(19+o.byteLength),c=new DataView(l.buffer);c.setUint32(0,1332770163,!1),c.setUint32(4,1214603620,!1),c.setUint8(8,1),c.setUint8(9,i),c.setUint16(10,r,!0),c.setUint32(12,n,!0),c.setInt16(16,s,!0),c.setUint8(18,a),l.set(o,19),t.info.codecDescription=l,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=127,r=128,n=e.filePos;for(;e.filePos>>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=Tl(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;oe("audio"===(null==(m=t.info)?void 0:m.type));const i=Tl(e,3),r=new Bt(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Mt[n]),t.info.numberOfChannels=xi[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(p=t.info)?void 0:p.type));const i=(e=>{if(e.length<2)return null;const t=new Bt(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}})(Tl(e,ne.contentSize));if(!i){Pt._warn("Invalid dec3 box contents, ignoring.");break}const r=Ri(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Fi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(g=t.info)?void 0:g.type));const i=(e=>{if(e.length<20)return null;const t=me(e),i=t.getUint32(0);if(0===i)return null;const r=new Bt(e);r.seekToByte(13);const n=r.readBits(2);r.skipBits(5);const s=r.readBits(1),a=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let l=null;return 0!==o?l=ji(o):ae.id===i);if(!r)break;const n=Cl(e),s=(12&n)>>2,a=3&n,o=[vl,Sl,Pl,Cl],l=o[(48&n)>>4],c=o[s],u=o[a],d=Cl(e);for(let h=0;he.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let n=0;ne.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!=(y=null==d?void 0:d.defaultSampleDescriptionIndex)?y:null,defaultSampleDuration:null!=(b=null==d?void 0:d.defaultSampleDuration)?b:null,defaultSampleSize:null!=(T=null==d?void 0:d.defaultSampleSize)?T:null,defaultSampleFlags:null!=(v=null==d?void 0:d.defaultSampleFlags)?v:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Rl(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Cl(e)),n&&(u.currentFragmentState.defaultSampleDuration=Cl(e)),s&&(u.currentFragmentState.defaultSampleSize=Cl(e)),a&&(u.currentFragmentState.defaultSampleFlags=Cl(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;oe(t.currentFragmentState);const i=vl(e);e.skip(3);const r=0===i?Cl(e):Rl(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;oe(this.currentFragment),oe(t.currentFragmentState);const i=vl(e),r=Pl(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=Cl(e);let d=null;n&&(d=El(e));let h,f=null;s&&(f=Cl(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));for(let m=0;m0&&(n=Tl(e,r));const s=Qr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=vl(e);if(1&Pl(e)){const i=Nl(e,4),r=Cl(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Cl(e);if(0===r)break;r>1&&Pt._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Cl(e):Number(Rl(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);Qr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;oe(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Pl(e),n=Boolean(2&r),s=Cl(e),a=t.encryptionInfo.defaultPerSampleIvSize;oe(null!==a);for(let o=0;o0?r.set(Tl(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Sl(e);s=[];for(let i=0;i0&&(null!=(Y=this.metadataTags).trackNumber||(Y.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(J=this.metadataTags).tracksTotal||(J.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(Z=this.metadataTags).trackNumber||(Z.trackNumber=t)),i>0&&(null!=(ee=this.metadataTags).tracksTotal||(ee.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(te=this.metadataTags).discNumber||(te.discNumber=t)),i>0&&(null!=(ie=this.metadataTags).discsTotal||(ie.discsTotal=i))}}}}}return e.filePos=ae,!0}}class Ur{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;oe(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 Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return Y(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Hr(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return Gr(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=Re(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=Ne(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 oe(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=jr(i,e);if(!r)return null;let n;if(t.metadataOnly)n=br;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ct(t)&&(t=yield t),!t)return null;if(n=Tl(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield Yr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=Re(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(ct(e)&&(e=yield e),!e)break;const i=k,s=Sr(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.moofOffsetY(this,null,function*(){var e,t,i,r,n,s,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=yield this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&bi(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&yi(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&gi(t.data);i&&(this.internalTrack.info.vp9CodecInfo=V(H({},null!=(e=this.internalTrack.info.vp9CodecInfo)?e:i),{videoFullRangeFlag:i.videoFullRangeFlag,colourPrimaries:i.colourPrimaries,transferCharacteristics:i.transferCharacteristics,matrixCoefficients:i.matrixCoefficients}))}else{const e=yield this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&ni(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&$t(e.data)}if(!Se(this.internalTrack.info.colorSpace)){const e=ir(this.internalTrack.info);null!=(t=this.internalTrack.info.colorSpace).primaries||(t.primaries=e.primaries),null!=(i=this.internalTrack.info.colorSpace).transfer||(i.transfer=e.transfer),null!=(r=this.internalTrack.info.colorSpace).matrix||(r.matrix=e.matrix),null!=(n=this.internalTrack.info.colorSpace).fullRange||(n.fullRange=e.fullRange)}const o={codec:tr(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(s=this.internalTrack.info.codecDescription)?s:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Wr extends Ur{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr(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 Hr=(e,t)=>{if(e.presentationTimestamps){const i=Re(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=Re(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)}},Vr=(e,t)=>{var i;if(!e.keySampleIndices)return Hr(e,t);if(e.presentationTimestamps){const i=Re(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!==_e(e.keySampleIndices,i,e=>e))return i}return-1}{const r=Hr(e,t),n=Re(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},jr=(e,t)=>{const i=Re(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=Re(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];oe(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;ge)}},Kr=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=Re(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},Xr=(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},$r=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Gr=e=>0===e.sampleSizes.length,Qr=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}},Yr=(e,t,i)=>Y(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{oe(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Tl(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Sl(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Zr=(e,t,i,r)=>Y(null,null,function*(){var n;oe(e.encryptionInfo);const s=e.encryptionInfo;oe(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=Y(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{oe(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;iY(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=>Y(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);oe(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=rn(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 d=yield a(c),h=new Uint8Array(r);let f=0;for(const e of o)for(const t of e.perSubsample)h.set(d.subarray(f,f+t.length),t.offset),f+=t.length;return h}),tn=(e,t,i,r)=>{const n=new Lr;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(oe(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;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 nn,sn;(sn=nn||(nn={}))[sn.EBML=440786851]="EBML",sn[sn.EBMLVersion=17030]="EBMLVersion",sn[sn.EBMLReadVersion=17143]="EBMLReadVersion",sn[sn.EBMLMaxIDLength=17138]="EBMLMaxIDLength",sn[sn.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",sn[sn.DocType=17026]="DocType",sn[sn.DocTypeVersion=17031]="DocTypeVersion",sn[sn.DocTypeReadVersion=17029]="DocTypeReadVersion",sn[sn.Void=236]="Void",sn[sn.Segment=408125543]="Segment",sn[sn.SeekHead=290298740]="SeekHead",sn[sn.Seek=19899]="Seek",sn[sn.SeekID=21419]="SeekID",sn[sn.SeekPosition=21420]="SeekPosition",sn[sn.Duration=17545]="Duration",sn[sn.Info=357149030]="Info",sn[sn.TimestampScale=2807729]="TimestampScale",sn[sn.MuxingApp=19840]="MuxingApp",sn[sn.WritingApp=22337]="WritingApp",sn[sn.Tracks=374648427]="Tracks",sn[sn.TrackEntry=174]="TrackEntry",sn[sn.TrackNumber=215]="TrackNumber",sn[sn.TrackUID=29637]="TrackUID",sn[sn.TrackType=131]="TrackType",sn[sn.FlagEnabled=185]="FlagEnabled",sn[sn.FlagDefault=136]="FlagDefault",sn[sn.FlagForced=21930]="FlagForced",sn[sn.FlagOriginal=21934]="FlagOriginal",sn[sn.FlagHearingImpaired=21931]="FlagHearingImpaired",sn[sn.FlagVisualImpaired=21932]="FlagVisualImpaired",sn[sn.FlagCommentary=21935]="FlagCommentary",sn[sn.FlagLacing=156]="FlagLacing",sn[sn.Name=21358]="Name",sn[sn.Language=2274716]="Language",sn[sn.LanguageBCP47=2274717]="LanguageBCP47",sn[sn.CodecID=134]="CodecID",sn[sn.CodecPrivate=25506]="CodecPrivate",sn[sn.CodecDelay=22186]="CodecDelay",sn[sn.SeekPreRoll=22203]="SeekPreRoll",sn[sn.DefaultDuration=2352003]="DefaultDuration",sn[sn.Video=224]="Video",sn[sn.PixelWidth=176]="PixelWidth",sn[sn.PixelHeight=186]="PixelHeight",sn[sn.DisplayWidth=21680]="DisplayWidth",sn[sn.DisplayHeight=21690]="DisplayHeight",sn[sn.DisplayUnit=21682]="DisplayUnit",sn[sn.AlphaMode=21440]="AlphaMode",sn[sn.Audio=225]="Audio",sn[sn.SamplingFrequency=181]="SamplingFrequency",sn[sn.Channels=159]="Channels",sn[sn.BitDepth=25188]="BitDepth",sn[sn.SimpleBlock=163]="SimpleBlock",sn[sn.BlockGroup=160]="BlockGroup",sn[sn.Block=161]="Block",sn[sn.BlockAdditions=30113]="BlockAdditions",sn[sn.BlockMore=166]="BlockMore",sn[sn.BlockAdditional=165]="BlockAdditional",sn[sn.BlockAddID=238]="BlockAddID",sn[sn.BlockDuration=155]="BlockDuration",sn[sn.ReferenceBlock=251]="ReferenceBlock",sn[sn.Cluster=524531317]="Cluster",sn[sn.Timestamp=231]="Timestamp",sn[sn.Cues=475249515]="Cues",sn[sn.CuePoint=187]="CuePoint",sn[sn.CueTime=179]="CueTime",sn[sn.CueTrackPositions=183]="CueTrackPositions",sn[sn.CueTrack=247]="CueTrack",sn[sn.CueClusterPosition=241]="CueClusterPosition",sn[sn.Colour=21936]="Colour",sn[sn.MatrixCoefficients=21937]="MatrixCoefficients",sn[sn.TransferCharacteristics=21946]="TransferCharacteristics",sn[sn.Primaries=21947]="Primaries",sn[sn.Range=21945]="Range",sn[sn.Projection=30320]="Projection",sn[sn.ProjectionType=30321]="ProjectionType",sn[sn.ProjectionPoseRoll=30325]="ProjectionPoseRoll",sn[sn.Attachments=423732329]="Attachments",sn[sn.AttachedFile=24999]="AttachedFile",sn[sn.FileDescription=18046]="FileDescription",sn[sn.FileName=18030]="FileName",sn[sn.FileMediaType=18016]="FileMediaType",sn[sn.FileData=18012]="FileData",sn[sn.FileUID=18094]="FileUID",sn[sn.Chapters=272869232]="Chapters",sn[sn.Tags=307544935]="Tags",sn[sn.Tag=29555]="Tag",sn[sn.Targets=25536]="Targets",sn[sn.TargetTypeValue=26826]="TargetTypeValue",sn[sn.TargetType=25546]="TargetType",sn[sn.TagTrackUID=25541]="TagTrackUID",sn[sn.TagEditionUID=25545]="TagEditionUID",sn[sn.TagChapterUID=25540]="TagChapterUID",sn[sn.TagAttachmentUID=25542]="TagAttachmentUID",sn[sn.SimpleTag=26568]="SimpleTag",sn[sn.TagName=17827]="TagName",sn[sn.TagLanguage=17530]="TagLanguage",sn[sn.TagString=17543]="TagString",sn[sn.TagBinary=17541]="TagBinary",sn[sn.ContentEncodings=28032]="ContentEncodings",sn[sn.ContentEncoding=25152]="ContentEncoding",sn[sn.ContentEncodingOrder=20529]="ContentEncodingOrder",sn[sn.ContentEncodingScope=20530]="ContentEncodingScope",sn[sn.ContentCompression=20532]="ContentCompression",sn[sn.ContentCompAlgo=16980]="ContentCompAlgo",sn[sn.ContentCompSettings=16981]="ContentCompSettings",sn[sn.ContentEncryption=20533]="ContentEncryption";const an=[nn.EBML,nn.Segment],on=[nn.SeekHead,nn.Info,nn.Cluster,nn.Tracks,nn.Cues,nn.Attachments,nn.Chapters,nn.Tags],ln=[...an,...on],cn=16,un=e=>{if(e.remainingLength<1)return null;const t=vl(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=vl(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=un(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===vl(e))return;e.skip(-1);const t=dn(e);return null===t?null:72057594037927940!==t?t:void 0},pn=e=>{oe(e.remainingLength>=2);const t=fn(e);if(null===t)return null;const i=mn(e);return null===i?null:{id:t,size:i}},gn=(e,t)=>{const i=Tl(e,t);let r=0;for(;r{const i=Tl(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Ml(e):Dl(e)},bn=(e,t,i,r)=>Y(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Tn=(e,t,i,r)=>Y(null,null,function*(){const n=q(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return Y(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 Y(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=H(H({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,cn);if(ct(t)&&(t=yield t),!t)break;const i=pn(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===nn.EBML){Dn(n);let e=this.reader.requestSlice(s,n);if(ct(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===nn.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===nn.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield bn(this.reader,s,ln,this.reader.fileSize)).pos-s}const e=ce(this.segments);e&&(e.elementEndPos=s+n)}Dn(n),e=s+n}}))()}readSegment(e,t){return Y(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||re.id===s);if(-1!==l){const e=Wn[l].flag;this.currentSegment[e]=!0,Dn(a);let t=this.reader.requestSlice(o,a);ct(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===nn.Tags||s===nn.Attachments){s===nn.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Dn(a);let e=this.reader.requestSlice(o,a);ct(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===nn.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=Wn.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,cn);if(ct(r)&&(r=yield r),!r)continue;const n=pn(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Dn(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);ct(o)&&(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;ta&&(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 Y(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,cn);ct(r)&&(r=yield r),oe(r);const n=e,s=pn(r);oe(s);oe(s.id===nn.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield bn(this.reader,o,ln,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);ct(l)&&(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,ln);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;oe(e.blocks.length>0);let i=!1;for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[ce(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=Re(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=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,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A,M,D,N,O,L,z,U,q,W,j,K,X,$,G,Q,Y,J,Z,ee;const te=pn(e);if(!te)return!1;if(t&&t.includes(te.id))return!1;const{id:ie,size:re}=te,ne=e.filePos;switch(Dn(re),ie){case nn.DocType:this.isWebM="webm"===gn(e,re);break;case nn.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case nn.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=hn(e,re)}break;case nn.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=hn(e,re)}break;case nn.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=hn(e,re),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case nn.Duration:if(!this.currentSegment)break;this.currentSegment.duration=yn(e,re);break;case nn.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:V(H({},Ct),{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(ne,re)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==Ln.Block||e.data.algorithm!==Un.HeaderStripping})&&(Pt._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===vn)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===wn)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Sn)this.currentTrack.info.codec="vp8";else if(t===Pn)this.currentTrack.info.codec="vp9";else if(t===In)this.currentTrack.info.codec="av1";else if(t===xn){const e=this.currentTrack.codecPrivate?pe.decode(this.currentTrack.codecPrivate):"";Zi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Kn(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Cn?(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===Bn?this.currentTrack.info.codec="mp3":t===En?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=nr):t===_n?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Rn?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fn?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===An?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Mn?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Xn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case nn.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=hn(e,re);break;case nn.TrackType:{if(!this.currentTrack)break;const t=hn(e,re);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:H({},Pe),alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case nn.FlagEnabled:if(!this.currentTrack)break;hn(e,re)||(this.currentTrack=null);break;case nn.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!hn(e,re);break;case nn.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!hn(e,re);break;case nn.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!hn(e,re);break;case nn.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!hn(e,re);break;case nn.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!hn(e,re);break;case nn.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!hn(e,re);break;case nn.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=gn(e,re);break;case nn.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Tl(e,re);break;case nn.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=hn(e,re);break;case nn.Name:if(!this.currentTrack)break;this.currentTrack.name=kn(e,re);break;case nn.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=gn(e,re),Ge(this.currentTrack.languageCode)||(this.currentTrack.languageCode=We);break;case nn.LanguageBCP47:{if(!this.currentTrack)break;const t=gn(e,re).split("-")[0];this.currentTrack.languageCode=t||We,this.currentTrack.hasLanguageBcp47=!0}break;case nn.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=hn(e,re);break;case nn.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=hn(e,re);break;case nn.DisplayWidth:if("video"!==(null==(d=null==(u=this.currentTrack)?void 0:u.info)?void 0:d.type))break;this.currentTrack.info.displayWidth=hn(e,re);break;case nn.DisplayHeight:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayHeight=hn(e,re);break;case nn.DisplayUnit:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayUnit=hn(e,re);break;case nn.AlphaMode:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.alphaMode=1===hn(e,re);break;case nn.Colour:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.MatrixCoefficients:{if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;const t=hn(e,re),i=we[t];this.currentTrack.info.colorSpace.matrix=i}break;case nn.Range:{if("video"!==(null==(S=null==(w=this.currentTrack)?void 0:w.info)?void 0:S.type))break;const t=hn(e,re);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case nn.TransferCharacteristics:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=hn(e,re),i=Te[t];this.currentTrack.info.colorSpace.transfer=i}break;case nn.Primaries:{if("video"!==(null==(C=null==(x=this.currentTrack)?void 0:x.info)?void 0:C.type))break;const t=hn(e,re),i=ye[t];this.currentTrack.info.colorSpace.primaries=i}break;case nn.Projection:if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.ProjectionPoseRoll:{if("video"!==(null==(R=null==(_=this.currentTrack)?void 0:_.info)?void 0:R.type))break;const t=-yn(e,re);try{this.currentTrack.info.rotation=le(t)}catch(se){}}break;case nn.Audio:if("audio"!==(null==(A=null==(F=this.currentTrack)?void 0:F.info)?void 0:A.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.SamplingFrequency:if("audio"!==(null==(D=null==(M=this.currentTrack)?void 0:M.info)?void 0:D.type))break;this.currentTrack.info.sampleRate=yn(e,re);break;case nn.Channels:if("audio"!==(null==(O=null==(N=this.currentTrack)?void 0:N.info)?void 0:O.type))break;this.currentTrack.info.numberOfChannels=hn(e,re);break;case nn.BitDepth:if("audio"!==(null==(z=null==(L=this.currentTrack)?void 0:L.info)?void 0:z.type))break;this.currentTrack.info.bitDepth=hn(e,re);break;case nn.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(ne,re)),this.currentCueTime=null;break;case nn.CueTime:this.currentCueTime=hn(e,re);break;case nn.CueTrackPositions:{if(null===this.currentCueTime)break;oe(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case nn.CueTrack:{const t=null==(U=this.currentSegment)?void 0:U.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=hn(e,re)}break;case nn.CueClusterPosition:{const t=null==(q=this.currentSegment)?void 0:q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;oe(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+hn(e,re)}break;case nn.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=hn(e,re);break;case nn.SimpleBlock:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(W=i.track.info)?void 0:W.type)&&i.track.info.codec&&(a=!0);const o=Tl(e,re-(e.filePos-ne)),l=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,postProcessed:!1,mainAdditional:null})}break;case nn.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(ne,re)),this.currentBlock=null;break;case nn.Block:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e)>>1&3,s=Tl(e,re-(e.filePos-ne)),a=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case nn.BlockAdditions:this.readContiguousElements(e.slice(ne,re));break;case nn.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case nn.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Tl(e,re);break;case nn.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=hn(e,re);break;case nn.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=hn(e,re);break;case nn.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case nn.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(ne,re));break;case nn.Targets:this.readContiguousElements(e.slice(ne,re));break;case nn.TargetTypeValue:50!==hn(e,re)&&(this.currentTagTargetIsMovie=!1);break;case nn.TagTrackUID:case nn.TagEditionUID:case nn.TagChapterUID:case nn.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case nn.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(ne,re));break;case nn.TagName:this.currentSimpleTagName=kn(e,re);break;case nn.TagString:{if(!this.currentSimpleTagName)break;const t=kn(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.TagBinary:{if(!this.currentSimpleTagName)break;const t=Tl(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(ne,re));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new xt(this.currentAttachedFile.fileData,null!=(j=this.currentAttachedFile.fileMediaType)?j:void 0,null!=(K=this.currentAttachedFile.fileName)?K:void 0,null!=(X=this.currentAttachedFile.fileDescription)?X:void 0)),(null==($=this.currentAttachedFile.fileMediaType)?void 0:$.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!=(G=this.currentAttachedFile.fileName)?G:void 0,description:null!=(Q=this.currentAttachedFile.fileDescription)?Q:void 0})}this.currentAttachedFile=null}break;case nn.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;rt.order-e.order);break;case nn.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ln.Block,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case nn.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=hn(e,re);break;case nn.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=hn(e,re);break;case nn.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Un.Zlib,settings:null},this.readContiguousElements(e.slice(ne,re));break;case nn.ContentCompAlgo:if("decompress"!==(null==(J=null==(Y=this.currentDecodingInstruction)?void 0:Y.data)?void 0:J.type))break;this.currentDecodingInstruction.data.algorithm=hn(e,re);break;case nn.ContentCompSettings:if("decompress"!==(null==(ee=null==(Z=this.currentDecodingInstruction)?void 0:Z.data)?void 0:ee.type))break;this.currentDecodingInstruction.data.settings=Tl(e,re);break;case nn.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=ne+re,!0}decodeBlockData(e,t){oe(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(oe(r.data),"decompress"===r.data.type)if(r.data.algorithm===Un.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))}}}getDurationFromMetadata(e){return Y(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){oe(r.trackBacking);const e=yield r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(null!=t?t:1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=null!=t?t:0,i})}}class jn{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return Y(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=Re(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=Ne(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 oe(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return Y(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(oe(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if("prores"===(null==(r=this.internalTrack.info)?void 0:r.codec)){if(!(s.data.length>=8&&105===s.data[4]&&99===s.data[5]&&112===s.data[6]&&102===s.data[7])){const e=new Uint8Array(s.data.length+8);me(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(s.data,8),s.data=e}}s.postProcessed=!0}const a=i.metadataOnly?br:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,l=s.duration/this.internalTrack.segment.timestampFactor,c={};s.mainAdditional&&"video"===(null==(n=this.internalTrack.info)?void 0:n.type)&&this.internalTrack.info.alphaMode&&(c.alpha=i.metadataOnly?br:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Tr(a,s.isKeyFrame?"key":"delta",o,l,e.dataStartPos+t,s.data.byteLength,c);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u})}performClusterLookup(e,t,i,r,n){return Y(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=Re(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=Re(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,y=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let b;for(e?null===y||e.elementStartPos>=y?(b=e.elementEndPos,d=e):b=y:b=null!=y?y:u.clusterSeekStartPos;null===u.elementEndPos||b<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(b,2,cn);if(ct(e)&&(e=yield e),!e)break;const i=b,s=pn(e);if(!s||!on.includes(s.id)&&s.id!==nn.Void){const e=yield Tn(c.reader,i,on,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+Hn));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===nn.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){oe(a!==nn.Cluster);l=(yield bn(c.reader,m,ln,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,cn);if(ct(e)&&(e=yield e),!e)break;if(fn(e)===nn.Segment){u.elementEndPos=p;break}}b=p}if(p&&(!h||h.elementStartPosY(this,null,function*(){var e,t,i,r,n;let s=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(s=yield this.getFirstPacket({}));const a={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&&s?$t(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?ni(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?gi(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?yi(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?bi(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!Se(this.internalTrack.info.colorSpace)){const n=ir(a);null!=(e=this.internalTrack.info.colorSpace).primaries||(e.primaries=n.primaries),null!=(t=this.internalTrack.info.colorSpace).transfer||(t.transfer=n.transfer),null!=(i=this.internalTrack.info.colorSpace).matrix||(i.matrix=n.matrix),null!=(r=this.internalTrack.info.colorSpace).fullRange||(r.fullRange=n.fullRange)}const o={codec:tr(a),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(n=this.internalTrack.info.codecDescription)?n:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Xn extends jn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}}))():null})}}const $n=(e,t,i,r=null)=>Y(null,null,function*(){const n=q(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Cl(a),n=null!==e.fileSize?e.fileSize-s:null,o=fr(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&kr(o.header.channel)===kr(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class Gn extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Qn(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield $n(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=hr(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ct(r)&&(r=yield r),r){const n=Cl(r);if(n===ur||n===dr){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ct(t)&&(t=yield t),t){const e=Tl(t,12),i=me(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&pr.FrameCount?i.getUint32(4,!1):null,fileSize:r&pr.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);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 Y(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(ct(n)&&(n=yield n),!n)break;$l(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Wl){let e=this.reader.requestSlice(this.reader.fileSize-Wl,Wl);ct(e)&&(e=yield e),oe(e);"TAG"===Nl(e,3)&&jl(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class Qn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){const e=this.demuxer;if(oe(null!==e.firstFrameHeader),oe(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<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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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>>0&4294967295}const Zn=e=>{const t=me(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n>>24^t])>>>0}return t.setUint32(22,i,!0),r},es=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){oe(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,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:Ti[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},ts=27,is=282,rs=e=>{const t=e.filePos;if(Bl(e)!==Yn)return null;e.skip(1);const i=vl(e),r=Al(e),n=Bl(e),s=Bl(e),a=Bl(e),o=vl(e),l=new Uint8Array(o);for(let d=0;de+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}},ns=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Yn)return!0;e.skip(1)}}return!1};class ss extends yr{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,ts,is);if(ct(t)&&(t=yield t),!t)break;const i=rs(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 as(t,this)))}}))()})}readVorbisMetadata(e,t){return Y(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=me(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:vi(n.data).modeBlockflags},Ii(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return Y(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=me(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=nr,t.codecInfo.opusInfo={preSkip:n.preSkip},Ii(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return Y(this,null,function*(){oe(te+t.length,0);if(0===o)return null;const l=new Uint8Array(o);let c=0;for(let e=0;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 Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class as{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new xe,this.internalSampleRate="opus"===e.codecInfo.codec?nr:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return oe(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return Y(this,null,function*(){var e;return oe(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 We}getDisposition(){return V(H({},Ct),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(oe(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=es(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Tr(i.metadataOnly?br: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 Y(this,null,function*(){oe(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(oe(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 Y(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 Y(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=He(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;oe(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.totalSizen?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,ts,is);ct(t)&&(t=yield t),oe(t);const i=rs(t);oe(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}oe(-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:br,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=ls(d,u,m);oe(e);const t=os(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=ls(d,u,m);if(!e)break;const t=os(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,y=null;for(;null!==u;){oe(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&mn||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 Y(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=He(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=Re(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.timestampe)break;if(n=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);oe(e),this.sequentialScanCache.length>0&&oe(ce(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 os=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}oe(-1===n);if(!(1&r.headerType)){n=0;break}const t=De(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=De(e,e=>e.headerStartPosY(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);ct(i)&&(i=yield i),oe(i);const r=Nl(i,4),n="RIFX"!==r,s="RF64"===r,a=xl(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Nl(i,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=i.filePos;for(;null===o||u=18&&357!==n){const e=wl(r,i),s=t-18;if(Math.min(s,e)>=22&&n===cs.EXTENSIBLE){r.skip(6);const e=Tl(r,16);n=e[0]|e[1]<<8}}if(n!==cs.MULAW&&n!==cs.ALAW||(l=8),n!==cs.PCM&&n!==cs.IEEE_FLOAT&&n!==cs.ALAW&&n!==cs.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===cs.PCM&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(n===cs.IEEE_FLOAT&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,i){return Y(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(ct(m)&&(m=yield m),!m)return;const p=Nl(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Nl(m,4),t=xl(m,i),p=Tl(m,t);let k=0;for(let i=0;i0&&(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 Y(this,null,function*(){let i=this.reader.requestSlice(e,t);if(ct(i)&&(i=yield i),!i)return;const r=Xl(i);if(r){const n=t-Hl;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+Hl,r.size);$l(t,r,this.metadataTags)}}})}getCodec(){if(oe(this.audioInfo),this.audioInfo.format===cs.MULAW)return"ulaw";if(this.audioInfo.format===cs.ALAW)return"alaw";if(this.audioInfo.format===cs.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===cs.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}oe(!1)}getMimeType(){return Y(this,null,function*(){return"audio/wav"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const hs=2048;class fs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return Y(this,null,function*(){const e=this.demuxer.getCodec();return e?(oe(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getDisposition(){return H({},Ct)}getPacketAtIndex(e,t){return Y(this,null,function*(){oe(e>=0),oe(this.demuxer.audioInfo);const i=e*hs*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(hs*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(ct(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=br;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);ct(e)&&(e=yield e),oe(e),n=Tl(e,r)}const s=e*hs/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 Tr(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return Y(this,null,function*(){oe(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/hs,(this.demuxer.dataSize-1)/(hs*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;oe(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){oe(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/hs);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ms=e=>{const t=e.filePos,i=Tl(e,9),r=new Bt(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}},ps=1024;class gs extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();oe(this.firstFrameHeader),this.trackBackings=[new ks(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ms(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=Et[t.samplingFrequencyIndex];oe(void 0!==i);const r=ps/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=ps,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return Y(this,null,function*(){return"audio/aac"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(t)&&(t=yield t),!t)break;const i=Xl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ct(r)&&(r=yield r),!r)break;$l(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class ks{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ps}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getCodec(){return"aac"}getInternalCodecId(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){oe(this.demuxer.firstFrameHeader);const e=_t[this.demuxer.firstFrameHeader.channelConfiguration];return oe(void 0!==e),e}getSampleRate(){oe(this.demuxer.firstFrameHeader);const e=Et[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return oe(void 0!==e),e}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.dataSize)}return new Tr(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=_e(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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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+1Y(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=Xl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);ct(r)&&(r=yield r),oe(r),$l(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(255===vl(s)){const t=s.filePos;if(vl(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=Tl(e,4),n=new Bt(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){oe(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){oe(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");oe(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*q(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?q(2,e):null)(n.readBits(4));if(!s)return null;oe(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 o=(e=>{let t=0;const i=new Bt(Tl(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Bt(Tl(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Sl(e)+1:"uncommon-u8"===t?vl(e)+1:"number"===typeof t?t:(Oe(t),void oe(!1)))(e,s),c=((e,t)=>"uncommon-u16"===t?Sl(e):"uncommon-u16-10"===t?10*Sl(e):"uncommon-u8"===t?vl(e):"number"===typeof t?t:null)(e,a);if(null===c)return null;if(c!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,d=vl(e);e.skip(-u),e.skip(-1);const h=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Tl(e,u));return d!==h?null:{num:o,blockSize:l,sampleRate:c}}advanceReader(){return Y(this,null,function*(){yield this.readMetadata(),oe(null!==this.lastLoadedPos),oe(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 bs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return We}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return Y(this,null,function*(){if(oe(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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 Y(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 Y(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.byteSize)}oe(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Tr(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return Y(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Ts=9e4,vs=q(2,33),ws=188,Ss="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.",Ps=new Set([133,134,162]),Is=new Set;class xs extends yr{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=this.reader.requestSlice(0,205);ct(e)&&(e=yield e),oe(e);const t=Tl(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ws;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}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){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 Bt(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=Bs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(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 As(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=$t(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];oe(t);const i=Jt(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[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=ni(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT).nalUnits[0];oe(t);const i=ri(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:tr({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(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=yl.tempFromBytes(r.suppliedPacket.data),i=ms(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=_t[i.channelConfiguration],e.info.sampleRate=Et[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Cl(yl.tempFromBytes(r.suppliedPacket.data)),i=fr(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=kr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Ci(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=xi[t.acmod]+t.lfeon,e.info.sampleRate=Mt[t.fscod]}else if("eac3"===e.info.codec){const t=_i(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Ri(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Fi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=qi(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:rr({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Bt(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),l=e.pos+8*n;let c=!1;for(;e.pos=4){const t=e.readBits(32);c||(c=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=l;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,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let l=null;const u=c&&Ps.has(t)?130:t;switch(u){case 27:case 36:l={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",l={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:a?l={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?l={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(l={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Is.has(t)||(Pt._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Is.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}s=!0}else{const e=new Bt(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)a.initialized&&("video"===a.info.type?this.trackBackingEntries.push(new _s(a)):this.trackBackingEntries.push(new Rs(a)))}))()})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(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 Y(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!==_e(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=Re(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 Y(this,null,function*(){let t=this.reader.requestSlice(e,4);if(ct(t)&&(t=yield t),!t)return null;if(71!==vl(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Sl(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:vl(t)>>4&3}})}readPacket(e){return Y(this,null,function*(){let t=this.reader.requestSlice(e,ws);if(ct(t)&&(t=yield t),!t)return null;const i=Tl(t,ws);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}})}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=vs-t?-vs:vs}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new Bt(t.payload);if(1!==r.readBits(24))return null;const n=r.readBits(8);if(r.skipBits(16),188===n||190===n||191===n||240===n||241===n||255===n||242===n||248===n)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let a=null;if(2===s||3===s)a=0,r.skipBits(4),a+=r.readBits(3)*(1<<30),r.skipBits(1),a+=32768*r.readBits(15),r.skipBits(1),a+=r.readBits(15),a=e.normalizeTimestamp(a);else if(i)throw new Error(Ss);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Bs=(e,t,i)=>{oe(null!==t.endPos);const r=Cs(e,t,i);if(!r)return null;const n=new Bt(t.payload);n.skipBits(32);const s=n.readBits(16);n.skipBits(16);const a=n.readBits(8),o=n.pos+8*a;n.pos=o;const l=o/8;oe(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return V(H({},r),{data:c})};class Es{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++,oe(r instanceof Es),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 We}getDisposition(){return V(H({},Ct),{primary:!1})}getTimeResolution(){return Ts}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Tr(i.metadataOnly?br:e.data,r,e.pts/Ts,Math.max(t/Ts,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return Y(this,null,function*(){const t=this.elementaryStream.firstSection;oe(t);const i=Bs(this.elementaryStream.demuxer,t,!0);oe(i);const r=new As(this.elementaryStream,i),n=new Ms(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 Y(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);oe(s);const a=Bs(n,s,!0);oe(a);const o=new As(this.elementaryStream,a);i=new Ms(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 Y(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 Y(this,null,function*(){var r,n,s,a,o,l;const c=He(e*Ts),u=this.elementaryStream.demuxer,{reader:d,seekChunkSize:h}=u,f=this.elementaryStream.pid,m=(e,t,i)=>Y(this,null,function*(){let r=e;for(;re.pts),T=-1!==b?y[b]:null;if(T&&c-T.pts<45e3)k=T.sectionStartPos;else{let e=0;if(null!==d.fileSize){const t=Math.ceil(d.fileSize/h);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=Ke(t*h,u.packetStride)+g.sectionStartPos,s=n+h,a=yield m(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}k=Ke(e*h,u.packetStride)+g.sectionStartPos}const v=yield m(k,null!=(r=d.fileSize)?r:1/0,!1);let w=null!=(n=null==v?void 0:v.pesPacketHeader)?n:null;w||(w=g);const S=this.getReorderSize(),P=(e,t)=>Y(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);oe(s);const a=Bs(u,s,!0);oe(a);const o=new As(this.elementaryStream,a),l=new Ms(this,o);for(;;){if((null!=(n=null==(r=ce(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=Ne(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();oe(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=w.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;w=e,Fs(this.elementaryStream,w);break}}}e+=u.packetStride}}e:for(let e=0;e=u.packetOffset;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){w=e;break}}}e-=u.packetStride}}return P(w.sectionStartPos,e=>e.pts<=c)}{let e=k,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=g.sectionStartPos;let k,y=null;if(n)k=g,y=p;else{const t=yield m(e,null!=(s=d.fileSize)?s:1/0,i);k=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,y=null!=(o=null==t?void 0:t.section)?o:null}let b=!1,T=0;e:for(;k&&!(null!==t&&k.sectionStartPos>=t);){if(k.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===k.randomAccessIndicator;else{oe(y);const t=Bs(u,y,!0);oe(t);const i=new As(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=k)}if(k.pts>c&&(b=!0),b&&(T++,T>S))break;let e=k.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){k=e,y=t,Fs(this.elementaryStream,k);break}}}e+=u.packetStride}}if(r){let e=r;if(0===T)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===f&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Cs(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield P(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return oe(t),t}if(n)return null;t=e,e=Math.max(Ke(e-g.sectionStartPos-h,u.packetStride)+g.sectionStartPos,g.sectionStartPos)}}})}}class _s extends Es{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 Y(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return Y(this,null,function*(){return!1})}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Rs extends Es{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Fs=(e,t)=>{const i=e.referencePesPackets,r=Re(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=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return oe(e),e}bufferData(e){return Y(this,null,function*(){const t=this.endPos+e;for(;this.endPos=c)break;u=t;const r=o+u;if(u+3>=c){this.seekTo(r);break}const d=l[u+1],h=l[u+2],f=l[u+3];let m=0;if(0===d&&0===h&&1===f?m=4:0===d&&1===h&&(m=3),0===m){u++;continue}const p=r;null!=n||(n=p);const g=u+m,k=g+i,y=6;if(k+("avc"===e?y:1)>c){this.seekTo(r);break}const b=l[g];let T,v,w;if("avc"===e)T=Ht(b),v=T===Nt.NON_IDR_SLICE||T===Nt.SLICE_DPA||T===Nt.IDR,w=T===Nt.SEI||T===Nt.SPS||T===Nt.PPS||T===Nt.AUD;else{T=ii(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=Lt.RASL_R||T>=Lt.BLA_W_LP&&T<=21,w=T>=Lt.VPS_NUT&&T<=37||T===Lt.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let S=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=ue(new Bt(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?S=!0:s=!0)}else w&&s&&(S=!0);if(S){const e=p-n;return this.seekTo(n),this.supplyPacket(e,0)}u+=m}if(rn){const e=this.endPos-n;return this.seekTo(n),this.supplyPacket(e,0)}}else{const n=r.info.codec,s=128;for(;;){let a=this.ensureBuffered(s);ct(a)&&(a=yield a);const o=this.currentPos;for(;this.currentPos-o>6,a=63&i[4];if(3===n||a>37){this.seekTo(e+1);continue}const o=Bi[3*a+n];oe(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),ct(t)&&(t=yield t);const l=Math.round(13824e4/r.info.sampleRate);return this.supplyPacket(t,l)}if("eac3"===n){if(11!==s)continue;this.skip(-1);const e=this.currentPos;let t=this.ensureBuffered(5);if(ct(t)&&(t=yield t),t<5)return;const i=this.readBytes(5);if(11!==i[0]||119!==i[1]){this.seekTo(e+1);continue}const n=2*(((7&i[2])<<8|i[3])+1),a=3===i[4]>>6?3:i[4]>>4&3,o=Ei[a];this.seekTo(e),t=this.ensureBuffered(n),ct(t)&&(t=yield t);const l=256*o,c=Math.round(l*Ts/r.info.sampleRate);return this.supplyPacket(t,c)}if("dts"===n){if(127!==s&&100!==s)continue;this.skip(-1);const n=this.currentPos;let a=this.ensureBuffered(18);if(ct(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=Hi(o);let c=l?null:Vi(o);if(!l&&!c){this.seekTo(n+1);continue}if(c&&!c.asset){this.seekTo(n);const t=Math.min(c.frameSize,4096);let i=this.ensureBuffered(t);ct(i)&&(i=yield i),c=null!=(e=Vi(this.readBytes(i)))?e:c}let u=l?l.frameSize:c.frameSize;if(l){let e=4*Math.ceil(l.frameSize/4);for(;;){this.seekTo(n);const t=e+10;let i=this.ensureBuffered(t);if(ct(i)&&(i=yield i),i=0)}readNext(){return Y(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(oe(-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 Y(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 Y(this,null,function*(){const e=this.decodeOrderPackets[0];for(oe(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;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const Ds="application/vnd.apple.mpegurl",Ns="#EXT-X-STREAM-INF:",Os="#EXT-X-I-FRAME-STREAM-INF:",Ls="#EXT-X-MEDIA:",zs="#EXTINF:",Us="#EXT-X-MAP:",qs="#EXT-X-KEY:",Ws="#EXT-X-MEDIA-SEQUENCE:",Hs="#EXT-X-BYTERANGE:",Vs="#EXT-X-PROGRAM-DATE-TIME:",js="#EXT-X-TARGETDURATION:",Ks="#EXT-X-PLAYLIST-TYPE:",Xs=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class $s{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sY(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,t,i))}else if("audio"===t.type){const i=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(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=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return Y(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 Y(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 Qs{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(this,null,function*(){var e,t;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.");let i=this.segmentedInput.firstSegment,r=null;for(;i;){const e=this.segmentedInput.getInputForSegment(i);if(r=null!=(t=(yield e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number))?t:null,r)break;i=yield this.segmentedInput.getNextSegment(i,{})}if(!r)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=r,this.firstSegment=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 Y(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 Y(this,null,function*(){return yield this.hydrate(),oe(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp})}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return Y(this,null,function*(){oe(e.sequenceNumber>=0),oe(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:je(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 Y(this,null,function*(){var t;yield this.hydrate(),oe(this.firstInputTrack),oe(this.firstSegment);let i=this.firstInputTrack,r=this.firstSegment;for(;;){if(i){const t=yield i._backing.getFirstPacket(e);if(t)return this.createAdjustedPacket(t,r,i)}if(r=yield this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;const n=this.segmentedInput.getInputForSegment(r);i=null!=(t=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number))?t:null}return null})}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}_getNextInternal(e,t,i){return Y(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 Y(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 Ys extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class Js extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}ft();const Zs=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ea extends vt{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}getSizeOrNull(){return Y(this,null,function*(){var e;if(this._disposed)throw new gl;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>Y(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,Zs),e=this._getFileSize(),oe(void 0!==e)),e}))()})}getSize(){return Y(this,null,function*(){if(this._disposed)throw new gl;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 ga(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 ta(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class ta{constructor(e){var t;if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),null==(t=e._refFinalizationRegistry)||t.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){var e;if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const t=this.source;oe(t._refCount>0),t._decrementRefCount(),null==(e=t._refFinalizationRegistry)||e.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class ia extends ea{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 ea||e instanceof ta))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ea?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ct(t)?t.then(i):i(t)}}const ra=(e,t)=>e.path===t.path;class na extends ia{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 ea?e.ref():e;return this._root=t,this._rootRequest=null,t};ct(e)?this._rootRequest=e.then(t):(t(e),oe(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())}}const sa="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class aa extends ea{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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new pa({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*q(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==sa||sa.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ma.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return Y(this,null,function*(){oe(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!it()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==sa||sa.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return Pt._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(q(2,e-2),16)},ca=new Set;class ua extends ia{constructor(e,t={}){var i,r,n,s;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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new ua(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=null!=(i=t.getRetryDelay)?i:la,this._requestInit=H({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=H({},Je(t.requestInit.headers)),i=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==i&&(a=e[i],delete e[i],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){null!=a||(a=t);const i=new Request(e);i.headers.delete("Range"),this._url=i}}if(null!==a){const e=ha(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new pa({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*q(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:ma.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){var e;if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const t=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===t?null!==this._length?this._length:null:qe(t-this._offset,0,null!=(e=this._length)?e:1/0)}_read(e,t,i,r){var n;if(null!==this._length&&t>this._length)return null;const s=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+t):this._orchestrator.read(s+e,s+t,Math.max(s+i,s),s+Math.min(r,null!=(n=this._length)?n:1/0)),o=e=>e?(e.offset-=this._offset,e):null;return ct(a)?a.then(o):o(a)}_runWorker(e){return Y(this,null,function*(){for(var t;;){const r=new AbortController,n=yield Ze(null!=(t=this._options.fetchFn)?t:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(null===this._orchestrator.fileSize&&(206===n.status||"basic"===n.type&&!n.headers.has("Content-Encoding"))){const t=n.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=n.headers.get("Content-Length");if(i){const t=206===n.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==n.status){if(this._sequentialBacking)return void n.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||ca.has(e.origin)||(Pt._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),ca.add(e.origin))}return void this._transitionToSequentialMode(n.body)}const s=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return r.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let t;try{t=yield s.read()}catch(i){if(this._disposed)throw i;const e=this._getRetryDelay(1,i,this._url);if(null!==e){Pt._error("Error while reading response stream. Attempting to resume.",i),yield Tt(1e3*e);break}throw i}if(e.aborted)continue;const{done:n,value:a}=t;if(n){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+a.length),this._orchestrator.supplyWorkerData(e,a)}}})}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const n=new ReadableStream({pull:e=>Y(this,null,function*(){for(var n;;){let a;try{a=yield t.read()}catch(s){if(this._disposed)throw s;const e=this._getRetryDelay(1,s,this._url);if(null===e)throw s;Pt._error("Error while reading response stream. Attempting to resume.",s),yield Tt(1e3*e);const a=yield Ze(null!=(n=this._options.fetchFn)?n:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!a.ok)throw new Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=a.body.getReader(),r=206===a.status?0:i;continue}if(a.done)return void e.close();let o=a.value;if(r>0){const e=Math.min(r,o.length);r-=e,o=o.subarray(e)}if(0!==o.length)return i+=o.length,void e.enqueue(o)}}),cancel:()=>t.cancel()}),s=new fa(n,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const a=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)a.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)a.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of a){const e=s._read(o.start,o.start+o.bytes.length);ct(e)?e.then(e=>{e?(oe(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(oe(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const da=/^bytes=(\d+)-(\d*)$/,ha=e=>{const t=da.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=Re(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=t)break;const r=Math.max(e,i.start);r>n&&this._throwDueToCacheMiss();const a=Math.min(t,i.end);rn&&this._throwDueToCacheMiss();const{promise:a,resolve:o,reject:l}=Ae();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)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),a}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}_pull(){return Y(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._currentIndex0;){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;for(const t of this._pendingSlices)t.reject(new gl);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const ma={fileSystem:(e,t)=>{const i=q(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=q(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*q(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(dt(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=q(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+oa)}}};class pa{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;oe(!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);oe(a<=e&&t<=o);let l=null;const c=Re(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=Re(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=o)break;if(r.end<=a)continue;const n=Math.max(a,r.start),s=Math.min(o,r.end);if(oe(n<=s),m=h.length&&(l={bytes:h,view:me(h),offset:e}),0===p.length)return oe(l),l;const{promise:g,resolve:k,reject:y}=Ae(),b=[];for(const v of p){const i=Math.max(e,v.start),r=Math.min(t,v.end);i===v.start&&r===v.end?b.push(v):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&v.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,v.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:v.start,end:v.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.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?g.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(oe(h),l=g.then(t=>t&&{bytes:t,view:me(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=q(2,17);if(dt(t.start-r,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=s),t.end<=t.start&&(i.holes.splice(e,1),e--)}0===i.holes.length&&(i.resolve(i.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){var t,i;const r=this.workers.indexOf(e);oe(-1!==r),e.running=!1,this.workers.splice(r,1),null==(i=(t=this.options).onIdleWorkerRemoved)||i.call(t,e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=Re(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=me(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=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=me(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;ithis._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return ct(n)?n.then(s):s(n)}_dispose(){var e;null==(e=this._ref)||e.free()}ref(){return null!=this._ref||(this._ref=this._baseSource.ref()),super.ref()}}var ka=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},ya=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 ba=/^0[xX][0-9a-fA-F]+$/,Ta=/^data:.*;base64,/i;class va extends Gs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>Y(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Tt(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 Y(this,null,function*(){var e,t,i,r,n,s,a,o;let l=this.nextLines;if(this.nextLines=null,!l){const e={stack:[],error:void 0,hasError:!1};try{const t=ka(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new kl(t.source),r=yield i.requestEntireFile();oe(r),l=Ol(r,r.length,{ignore:Xs}),t.source instanceof ia&&(this.rootPath=t.source.rootPath)}catch(x){e.error=x,e.hasError=!0}finally{ya(e)}}const c=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let u=!1,d=0,h=null,f=null,m=null,p=0,g=null,k=null,y=null,b=null,T=null,v=null,w=!1,S=null!=(t=ce(this.segments))?t:null;const P=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}},I=e=>{p=e,S&&(oe(null!==S.sequenceNumber),S.sequenceNumber0&&null!==v&&(d=p*v),w=!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(Us)){const t=new $s(e.slice(11)),i=t.get("uri");if(!i)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const r=t.get("byterange");let a=null;if(null!==r&&(a=P(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!S){const e={path:pt(this.rootPath,i),offset:null!=(n=null==a?void 0:a.offset)?n:0,length:null!=(s=null==a?void 0:a.length)?s: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:d,unixEpochTimestamp:h,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:m,initSegment:null,lastProgramDateTimeSeconds:T}}f=null,null===b?y=null:b=null}else if(e.startsWith(qs)){const t=new $s(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(!ba.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Er);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=me(i).getUint32(0);r=vr(i.subarray(8,Math.min(e,i.length)))}}m={method:i,psshBox:r}}}}else if(e.startsWith(Ws)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);I(i)}else if(e.startsWith(Hs)){const t=P(e.slice(17));if(null===t.offset){if(null===y)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=y}b=t,y=t.offset+t.length}else if(e.startsWith(Vs)){if(S)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(T===r)continue;if(null===T&&this.segments.length>0){const e=ce(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,c&&(i.timestamp=i.unixEpochTimestamp)}T=r,h=r,c&&(d=r)}else if("#EXT-X-DISCONTINUITY"===e)g=null;else if(e.startsWith(js)){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,v=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(Ks)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");u=!0}}if(!u)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return Y(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return Y(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=Re(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.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=V(H({},this.input._formatOptions),{isobmff:V(H({},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=>wr(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(V(H({},e),{psshBoxes:t}))})})}),o=new ml({source:new na(r.location.path,e=>Y(this,null,function*(){var t,i;oe(e.isRoot);const n=V(H({},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;oe(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 o=((e,t,i)=>{let r=!1,n=0;const s=q(2,16),a=new Lr;return new ReadableStream({pull:o=>Y(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(ct(c)&&(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=Tl(c,d),f=new Uint8Array(d);for(let e=0;e16)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 kl(t.source),()=>Y(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=ka(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},fl),!1),r=new kl(i.source),n=yield r.requestSlice(0,Er);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Tl(n,Er),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ya(t)}}),()=>{t.free()});s=new fa(o).ref()}else oe(!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 qa)),initInput:null!=s?s:void 0,formatOptions:a});o._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:o,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=kt(this.inputCache,e=>e.age);oe(-1!==e),this.inputCache.splice(e,1)}return o}getLiveRefreshInterval(){return Y(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class wa extends yr{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=(()=>Y(this,null,function*(){oe(this.input._rootSource instanceof ia);const e=yield this.input._reader.requestEntireFile();oe(e);const t=Ol(e,e.length,{ignore:Xs}),{rootPath:i}=this.input._rootSource,r=[],n=[];for(let u=1;u"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((e,t)=>Y(this,null,function*(){var r,o,l,c;const u=[],d=e.attributes.get("codecs");let h;if(d)h=d.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=yield t.getTrackBackings(),r=yield Promise.all(i.map(e=>Y(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));h=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const f=e.attributes.get("video"),m=e.attributes.get("audio"),p=h.some(e=>Ki.includes(or(e))),g=h.some(e=>$i.includes(or(e)));if(null!==f&&!p){if(!s.includes(f))throw new Error(`Invalid M3U8 file; variant stream references video group "${f}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===f&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}if(null!==m&&!g){if(!a.includes(m))throw new Error(`Invalid M3U8 file; variant stream references audio group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}h=[...new Set(h)];let k=null,y=null;const b=e.attributes.getAsNumber("bandwidth");oe(null!==b);const T=e.attributes.getAsNumber("average-bandwidth"),v=e.attributes.get("name");for(const i of h){const d=or(i);if(null!==d)if(Ki.includes(d)){if(null!==k)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");k=i;const a=e.attributes.get("video");if(null===a){const i=e.attributes.get("resolution");let r=null,n=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),n=Number(e[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:We,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:k,pairingMask:BigInt("1")<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 i of n){const n=i.attributes.get("group-id"),s=i.attributes.get("type");if(n!==r||"audio"!==s.toLowerCase())continue;const a=null!=(l=i.attributes.get("channels"))?l:e.attributes.get("channels"),o=null!==a?Number(a.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:xa(i.attributes),autoselect:xa(i.attributes)||Ca(i.attributes),languageCode:Ba(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:y,pairingMask:BigInt("1")<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===We&&(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 Pa(u)):this.trackBackings.push(new Ia(u));this.internalTracks=l}))()}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),oe(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 va(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(this,null,function*(){return Ds})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Sa{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(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 Pa){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{oe(this instanceof Ia);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 V(H({},Ct),{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(){oe(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Pa extends Sa{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Ia extends Sa{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const xa=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}".`)},Ca=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}".`)},Ba=e=>{if(null===e)return We;const t=e.split("-")[0];return t||We};class Ea{constructor(){this._isIsobmff=!1}}class _a extends Ea{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return null;t.skip(4);const i=Nl(t,4);return"ftyp"!==i&&"styp"!==i?null:Nl(t,4)})}_createDemuxer(e){return new zr(e)}}class Ra extends _a{_canReadInput(e){return Y(this,null,function*(){const t=yield this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(ct(t)&&(t=yield t),!t)return!1;let r=Cl(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ct(t)&&(t=yield t),!t)return!1;r=Rl(t),n=16}if(r8)return!1;if(hn(i,r)!==nn.EBML)return!1;const n=mn(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(ct(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=pn(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case nn.EBMLVersion:if(1!==hn(s,r))return!1;break;case nn.EBMLReadVersion:if(1!==hn(s,r))return!1;break;case nn.DocType:if(gn(s,r)!==t)return!1;break;case nn.DocTypeVersion:if(hn(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Vn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ma extends Aa{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Da extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}const i=yield $n(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=hr(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(ct(s)&&(s=yield s),!s)return!1;const a=Cl(s);if(a===ur||a===dr)return!0;t=i.startPos+i.header.totalSize;const o=yield $n(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 Gn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Na extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return!1;const i=Nl(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Nl(t,4)})}_createDemuxer(e){return new ds(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Oa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,4);return ct(t)&&(t=yield t),!!t&&"OggS"===Nl(t,4)})}_createDemuxer(e){return new ss(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class La extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ct(i)&&(i=yield i),!!i&&"fLaC"===Nl(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ys(e)}}class za extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ct(i)&&(i=yield i),!i)return!1;const r=ms(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ct(i)&&(i=yield i),!i)return!1;const n=ms(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new gs(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ua extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,205);if(ct(t)&&(t=yield t),!t)return!1;const i=Tl(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 xs(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class qa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,7);if(ct(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Nl(t,7)))return!1;if(!(e._rootSource instanceof ia))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 wa(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Ds}}const Wa=new Ra,Ha=new Fa,Va=new Aa,ja=new Ma,Ka=new Da,Xa=new Na,$a=new Oa,Ga=new za,Qa=new La,Ya=new Ua,Ja=new qa,Za=[Ja,Wa,Ha,Va,ja,Xa,$a,Qa,Ka,Ga,Ya],eo=[Ja,Wa,Ha,Ka,Ga,Ya];var to=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});ft();let io=-1/0,ro=-1/0,no=null;"undefined"!==typeof FinalizationRegistry&&(no=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-io>=1e3&&(Pt._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."),io=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ro>=1e3&&(Pt._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."),ro=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class so{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const ao=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],oo=new Set(ao);class lo{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(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*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,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F;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||!oo.has(t.format))throw new TypeError("init.format must be one of: "+ao.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&&bt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=null!=(i=t.rotation)?i:0,this.timestamp=t.timestamp,this.duration=null!=(r=t.duration)?r:0;const m=null!=(n=t.layout)?n:bo(t.format,t.codedWidth,t.codedHeight);let p=null!=(s=t.colorSpace)?s:null;null===p&&(p="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:null!=(o=null==(a=t.visibleRect)?void 0:a.left)?o:0,top:null!=(c=null==(l=t.visibleRect)?void 0:l.top)?c:0,width:null!=(d=null==(u=t.visibleRect)?void 0:u.width)?d:t.codedWidth,height:null!=(f=null==(h=t.visibleRect)?void 0:h.height)?f:t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?fe(e):fe(e).slice(),this._layout=m,this.colorSpace=new mo(p)}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)&&bt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:null!=(p=null==(m=e.visibleRect)?void 0:m.x)?p:0,top:null!=(k=null==(g=e.visibleRect)?void 0:g.y)?k:0,width:null!=(b=null==(y=e.visibleRect)?void 0:y.width)?b:e.codedWidth,height:null!=(v=null==(T=e.visibleRect)?void 0:T.height)?v:e.codedHeight},this.rotation=null!=(w=null==t?void 0:t.rotation)?w:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(S=null==t?void 0:t.timestamp)?S:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new mo(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&bt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new lo(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Qe),duration:Math.trunc((null!=(x=t.duration)?x:0)*Qe)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const n=null!=(C=t.visibleRect)?C:{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(n.width,n.height),a=s.getContext("2d",{alpha:nt(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-n.left,-n.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n.width,height:n.height},this.squarePixelWidth=n.width,this.squarePixelHeight=n.height,this.rotation=null!=(B=t.rotation)?B:0,this.timestamp=t.timestamp,this.duration=null!=(E=t.duration)?E:0,this.colorSpace=new mo({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof so))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!ao.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=null!=(_=t.rotation)?_:0,this.timestamp=t.timestamp,this.duration=null!=(R=t.duration)?R:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(F=null==t?void 0:t.encodeOptions)?F:{},this.pixelAspectRatio=yt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==no||no.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return oe(null!==this._data),this._data instanceof so?new lo(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):po(this._data)?new lo(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(oe(this._layout),new lo(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new lo(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof so?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(yo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(t=e.format)?t:this.format))throw new Error("Cannot get allocation size when format is null.");if(po(this._data))return this._data.allocationSize(e);return vo(this,e).allocationSize}copyTo(e){return Y(this,arguments,function*(e,t={}){var i,r;if(!Ie(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(i=t.format)?i:this.format))throw new Error("Cannot copy video sample data when format is null.");if(oe(null!==this._data),po(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof so)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=yield i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const n=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}(i,yield this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},null!=(r=t.colorSpace)?r:"srgb"),!1);if(!(n instanceof lo))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return yield n.copyTo(e,t)}catch(u){i.error=u,i.hasError=!0}finally{to(i)}}}const n=vo(this,t);oe(this.format);const s=fe(e);if(s.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=e}else if(this._data instanceof Uint8Array)oe(this._layout),oe(this._layout.length===a.length),o=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");oe(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:fe(t.data),stride:4*this.codedWidth}]}const l=[],c=a.length;for(let d=0;di.byteLength)throw new Error("Source buffer OOB read.");if(a+c>s.byteLength)throw new Error("Destination buffer OOB write.");const n=i.subarray(r,r+c);s.set(n,a),r+=t,a+=e.destinationStride}l.push(u)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),i=this.format.includes("X")&&t.format.includes("A");if(e||i)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const n=[];for(const s of e)i.set(s.data,r),n.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:n[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return po(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(oe(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,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&&ko(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=t.crop;T&&(T=go(T,m,p));const{sx:v,sy:w,sWidth:S,sHeight:P}=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 I=f%180===0?1:y/b;e.translate(d/2,h/2),e.rotate(f*Math.PI/180),e.scale(1/I,I),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),v,w,S,P,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}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,n=e.height,[s,a]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,l=i.crop?i.crop.height:a;let c=0;2*r0?fo(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=c;p>1;p--){const e=r*q(2,p),t=n*q(2,p);f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*n,0,0,r,n),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(oe(null!==this._data),this._data instanceof so||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return Y(this,null,function*(){var t,i,r,n,s;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&ko(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const a=le(this.rotation+(null!=(t=e.rotate)?t:0)),[o,l]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=e.crop;c&&(c=go(c,o,l));const u=c?c.width:o,d=c?c.height:l,h=u/d;let f,m;void 0!==e.width&&void 0===e.height?(f=e.width,m=f/h):void 0===e.width&&void 0!==e.height?(m=e.height,f=m*h):void 0!==e.width&&void 0!==e.height?(f=e.width,m=e.height):(f=u,m=d),f=Ve(f,null!=(i=e.roundDimensionsTo)?i:1),m=Ve(m,null!=(r=e.roundDimensionsTo)?r:1);const p={width:f,height:m,fit:null!=(n=e.fit)?n:"fill",rotation:a,crop:null!=c?c:{left:0,top:0,width:o,height:l},alpha:null!=(s=e.alpha)?s:"keep"};for(const e of co){let t=e(this,p);if(ct(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=fo(p.width,p.height);return this._drawWithFitAndMipmapping(g,k,{fit:p.fit,rotation:p.rotation,crop:p.crop,targetIsFresh:y,fillBlack:"discard"===p.alpha}),new lo(g,{timestamp:this.timestamp,duration:this.duration,rotation:0})})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const co=[],uo=[];let ho=0;const fo=(e,t)=>{for(const n of uo)if(n.canvas.width===e&&n.canvas.height===t)return n.age=ho++,{canvas:n.canvas,context:n.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return uo.length>=3&&uo.splice(kt(uo,e=>e.age),1),uo.push({canvas:i,context:r,age:ho++}),{canvas:i,context:r,isNew:!0}};class mo{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(ke);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(be);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(ve);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 po=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,go=(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 oe(s>=0),oe(a>=0),{left:r,top:n,width:s,height:a}},ko=(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.")},yo=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.")}},bo=(e,t,i)=>{const r=To(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},To=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:Oe(e),oe(!1)}},vo=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=wo(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let a;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");a=t.format}else a=e.format;return Po(n,a,s)},wo=(e,t,i,r,n)=>{const s=H({},e);if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!So(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},So=(e,t)=>{if(null===e)return!0;const i=To(e);for(let r=0;r{const r=To(t),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const a=[],o=[];for(let l=0;l4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let e=0;e 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/(Bo(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*Bo(this.format);if(i.byteLength=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=Bo(r),o=Eo(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(!Ie(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&&!Io.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:n}=t;let{planeIndex:s}=t,a=this.format;const o=null!=i?i:this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,u=null!=n?n:0;if(u>=l)throw new RangeError("frameOffset out of range");const d=void 0!==r?r:l-u;if(d>l-u)throw new RangeError("frameCount out of range");const h=Bo(o),f=Eo(o);if(f&&s>=c)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?d:d*c)*h;if(e.byteLength2&&o!==a)return void Ao(this._data,p,a,o,c,s,u,d);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:d,format:o})}catch(w){if("f32-planar"===o)throw w;a="f32-planar"}}const k=_o(a),y=Bo(a),b=Eo(a);let T;if(this._data instanceof xo){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*y*(b?1:c);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)T=e(s),s=0;else{T=new Uint8Array(l*y*c);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(n,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Co({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof xo?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fo(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof xo?this._createAudioDataFromData():Fo(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Eo(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const n=Math.min(s,o),l=new Float32Array(i*n);for(let t=0;t0;){const n=Math.min(s,o),c=new Float32Array(i*n);for(let t=0;t{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")}},Eo=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_o=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)}},Ro=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,qe(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,qe(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,qe(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Fo=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Ao=(e,t,i,r,n,s,a,o)=>{const l=_o(i),c=Ro(r),u=Bo(i),d=Bo(r),h=Eo(i);if(Eo(r))if(h){const r=new ArrayBuffer(o*u),n=me(r);e.copyTo(r,{planeIndex:s,frameOffset:a,frameCount:o,format:i});for(let e=0;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.")},Oo=e=>{if(!mt(e))throw new TypeError("timestamp must be a number.")},Lo=(e,t,i)=>i.verifyKeyPackets?t.then(t=>Y(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class zo{constructor(e){if(!(e instanceof el))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return Y(this,arguments,function*(e={}){if(No(e),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return Y(this,arguments,function*(e={}){No(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;oe("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;oe("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 Tr))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 Tr))throw new TypeError("endPacket must be an EncodedPacket.");if(No(i),this._track.input._disposed)throw new gl;const r=[];let{promise:n,resolve:s}=Ae(),{promise:a,resolve:o}=Ae(),l=!1,c=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(()=>Y(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}=Ae()),yield a):(r.push(u),s(),({promise:n,resolve:s}=Ae()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{next(){return Y(this,null,function*(){for(;;){if(m.input._disposed)throw new gl;if(c)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return Y(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Uo{constructor(e,t){this.onSample=e,this.onError=t}}class qo{mediaSamplesInRange(e=-1/0,t=1/0,i){Oo(e),Oo(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=Ae(),{promise:l,resolve:c}=Ae(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g=V(H({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){var i;f=yield this._createDecoder(i=>{c(),i.timestamp>=t&&(d=!0),d?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}=Ae())))},e=>{p||(m=e,p=!0,o())});const k=this._createPacketSink(),y=null!=(i=yield k.getKeyPacket(e,g))?i:yield k.getFirstKeyPacket(g);let b=y;const T=k.packets(null!=y?y:void 0,void 0,g);for(yield T.next();b&&!d&&!this._track.input._disposed;){const e=Wo(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:l,resolve:c}=Ae()),yield l;continue}f.decode(b);const t=yield T.next();if(t.done)break;b=t.value}yield T.return(),h||this._track.input._disposed||(yield f.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{null==f||f.close()});const k=this._track,y=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return Y(this,null,function*(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new gl;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};yield a}})},return(){return Y(this,null,function*(){return h=!0,d=!0,c(),o(),y(),{value:void 0,done:!0}})},throw(e){return Y(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 Z(this,null,function*(){Symbol.iterator in e?yield*ee(e[Symbol.iterator]()):yield*ee(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=Ae(),{promise:o,resolve:l}=Ae(),c=!1,u=!1,d=null,h=null,f=!1;const m=e=>{n.push(e),a(),({promise:s,resolve:a}=Ae())},p=V(H({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){d=yield this._createDecoder(e=>{if(l(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(h=e,f=!0,a())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=()=>Y(this,null,function*(){oe(s),oe(d);let t=s;for(d.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=Ae()),yield o;if(u)break;const r=yield e.getNextPacket(t,p);oe(r),d.decode(r),t=r}g=-1}),y=()=>Y(this,null,function*(){oe(d),yield d.flush();for(let e=0;e{f||(h=e,f=!0,a())}).finally(()=>{null==d||d.close()});const g=this._track,k=()=>{for(const e of n)null==e||e.close()};return{next(){return Y(this,null,function*(){for(;;){if(g.input._disposed)throw u=!0,k(),new gl;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),h;if(n.length>0){const e=n.shift();return oe(void 0!==e),l(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};yield s}})},return(){return Y(this,null,function*(){return u=!0,l(),a(),k(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Wo=e=>0===e?40:8;class Ho extends Uo{constructor(e,t,i,r,n,s){var a,o,l,c,u,d,h,f;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const m=Mo.find(e=>e.supports(i,r));if(m)this.customDecoder=new m,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof lo))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();oe(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(at()){if("avc"===i&&this.decoderConfig.description){const e=Qt(fe(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Jt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=V(H({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=ei(t),this.decoderConfig=V(H({},this.decoderConfig),{description:Gt(e)})))}}Se(this.decoderConfig.colorSpace)||(this.decoderConfig=V(H({},this.decoderConfig),{colorSpace:{primaries:null!=(o=null==(a=this.decoderConfig.colorSpace)?void 0:a.primaries)?o:"bt709",matrix:null!=(c=null==(l=this.decoderConfig.colorSpace)?void 0:l.matrix)?c:"bt709",transfer:null!=(d=null==(u=this.decoderConfig.colorSpace)?void 0:u.transfer)?d:"bt709",fullRange:null!=(f=null==(h=this.decoderConfig.colorSpace)?void 0:h.fullRange)&&f}}))}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:(oe(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)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(oe(this.decoder),it()||Fe(this.inputTimestamps,e.timestamp,e=>e),at()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of Wt(e.data,this.decoderConfig)){const r=Ht(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Nt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&fe(t.description)[4];return Xt(e,i+1)}return Kt(e)})(t,this.decoderConfig);e=new Tr(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=mi(e.data,this.decoderConfig);t&&(e=new Tr(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new jo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();oe(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();oe(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=wi(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 ti(e,this.decoderConfig)){const i=ii(e[t.offset]);if(i===Lt.RASL_N||i===Lt.RASL_R)return!0}return!1}sampleHandler(e){if(it()){if(this.sampleQueue.length>0&&e.timestamp>=ce(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Fe(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();oe(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){return Y(this,null,function*(){const i=Ae();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){oe(this.merger);const i=yield this.merger.merge(e,t);r.sample=new lo(i)}else r.sample=new lo(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){Me(this.finalSamples,r),this.onError(n)}finally{Me(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return Y(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),yield Promise.all(this.mergeAlphaPromises),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),it()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1})}close(){var e;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,null==(e=this.merger)||e.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}let Vo=null;class jo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Vo){const e=new Blob([`(${Ko.toString()})()`],{type:"application/javascript"});Vo=URL.createObjectURL(e)}const e=qe(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=Ae();this.pendingRequests.set(i,r);const n=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,n.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Ko=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>Y(null,null,function*(){try{const e=yield r(n,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{n.close(),s.close()}}))});const r=(e,t)=>Y(null,null,function*(){const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),l=i.includes("P12"),c=r.includes("P10"),u=r.includes("P12");if(c!==o||u!==l)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return yield n(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return yield s(e,t,i);if("NV12"===i)return yield a(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)}),n=(e,t,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=new Uint8Array(4*d);yield e.copyTo(h);const f=yield o(t,c,u,1);for(let e=0,t=3;eY(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=i.includes("P10"),h=i.includes("P12"),f=d||h?2:1;let m,p;i.startsWith("I420")?(m=Math.ceil(c/2),p=Math.ceil(u/2)):i.startsWith("I422")?(m=Math.ceil(c/2),p=u):(m=c,p=u);const g=c*u,k=g*f,y=m*p*f,b=new Uint8Array(k+2*y+g*f);yield e.copyTo(b);const T=yield o(t,c,u,f),v=k+2*y;b.set(T,v);const w={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:c,codedHeight:u,timestamp:e.timestamp,duration:null!=(l=e.duration)?l:void 0,transfer:[b.buffer]};return new VideoFrame(b,w)}),a=(e,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=Math.ceil(c/2)*Math.ceil(u/2),f=e.allocationSize();t&&t.byteLength===f||(t=new Uint8Array(f)),yield e.copyTo(t);const m=new Uint8Array(d+2*h+d);m.set(t.subarray(0,d),0);const p=d,g=d+h,k=d;for(let e=0;eY(null,null,function*(){const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),yield t.copyTo(e);const a=t.format;if("RGBA"===a||"BGRA"===a||"RGBX"===a||"BGRX"===a){const t="RGBA"===a||"RGBX"===a?0:2,n=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class $o extends qo{constructor(e,t={}){if(!(e instanceof rl))throw new TypeError("videoTrack must be an InputVideoTrack.");Xo(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ot("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getRotation();let n=yield this._track.getDecoderConfig();const s=yield this._track.getTimeResolution();return oe(i&&n),n=V(H({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new Ho(e,t,i,n,r,s)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Go{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof rl))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&&ko(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&Xo(t.decoderOptions),this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._options=t,this._fit=null!=(r=t.fit)?r:"fill",this._videoSampleSink=new $o(e,t.decoderOptions),this._canvasPool=Array.from({length:null!=(n=t.poolSize)?n:0},()=>null)}_ensureInit(){var e;return null!=(e=this._initPromise)?e:this._initPromise=(()=>Y(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=go(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||nt()});oe(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&nt()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return Y(this,null,function*(){Oo(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class Qo extends Uo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const n=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(n*s)/s),e(t)},s=Do.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 Co))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{n(new Co(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(oe(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(oe(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return Y(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Yo extends Uo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,oe(Xi.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=ar(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-q(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<(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<e.getUint16(t,s)-q(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):oe(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Le(e,t,s)-q(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Le(e,t,i)<<8>>8)(e,t,s):oe(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-q(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):oe(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):oe(!1);break;default:Oe(n),oe(!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+q(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:Oe(n),oe(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=me(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=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new Co({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return Y(this,null,function*(){})}close(){}}class Jo extends qo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(ot("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getDecoderConfig();return oe(i&&r),Xi.includes(r.codec)?new Yo(e,t,r):new Qo(e,t,i,r)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Zo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Jo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return Y(this,null,function*(){Oo(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return Ue(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Ue(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class el{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof rl}isAudioTrack(){return this instanceof nl}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return Y(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return tl(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return Y(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return tl(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return Y(this,null,function*(){return this._backing.getName()})}get name(){return tl(this._backing.getName(),"name","getName")}getTimeResolution(){return Y(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return tl(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return Y(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return Y(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return Y(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return Y(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return tl(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return Y(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return Y(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return Y(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 Y(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,H({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 je(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return Y(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return Y(this,null,function*(){const i=new zo(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=te(i.packets(void 0,void 0,H({metadataOnly:!0},t)));o=!(l=yield u.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){c=[l]}finally{try{o&&(l=u.return)&&(yield l.call(u))}finally{if(c)throw c[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 Y(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return Y(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof el))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 Y(this,null,function*(){return this.input.getTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return Y(this,null,function*(){return this.input.getVideoTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return Y(this,null,function*(){return this.input.getAudioTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return Y(this,null,function*(){return this.input.getPrimaryVideoTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return Y(this,null,function*(){return this.input.getPrimaryAudioTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return Y(this,null,function*(){e&&(e=il(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=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const tl=(e,t,i)=>{if(ct(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},il=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 ct(r)?r.then(i):i(r)}:void 0};class rl extends el{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:"prores"===(yield this._backing.getCodec())})}getCodedWidth(){return Y(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return tl(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return Y(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return tl(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return Y(this,null,function*(){return this._backing.getRotation()})}get rotation(){return tl(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return Y(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return tl(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return Y(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return tl(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return Y(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=yt({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=yt({num:tl(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:tl(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return Y(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=tl(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return tl(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return Y(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=tl(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return tl(r,"displayHeight","getDisplayHeight")}getColorSpace(){return Y(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return Y(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return Y(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Mo.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))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 oe(i),wi(t,i,e.data)})}computeFrameRateMetrics(){return Y(this,arguments,function*(e={}){var t,i;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!mt(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const r=yield this.getTimeResolution(),n=null!=(t=e.targetPacketCount)?t:256,s=new zo(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=te(s.packets(void 0,void 0,{metadataOnly:!0}));c=!(u=yield h.next()).done;c=!1){const e=u.value;if(a.length>=n&&e.timestamp>=o)break;a.push(e.timestamp),o=Math.max(o,e.timestamp),l++}}catch(u){d=[u]}finally{try{c&&(u=h.return)&&(yield u.call(h))}finally{if(d)throw d[0]}}const f=new Float64Array(a.length);for(let R=0;Re-t),I=S-1>>1,x=S>>1;let C=0,B=0,E=0;for(const R of P)if(E+=b.get(R),0===C&&E>I&&(C=R),E>x){B=R;break}const _=(k/C+k/B)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:hl(_),minFrameRate:k/v,maxFrameRate:k/T,averageFrameRate:k*S/w,medianFrameRate:_,frameRateIsConstant:null!==g&&1===T&&1===v,probedPacketCount:l}})}}class nl extends el{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(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 Y(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return tl(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return Y(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return tl(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Do.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 Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const sl=e=>-(null!=e?e:-1/0),al=e=>-e,ol=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 ct(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return ct(r)?r.then(i):i(r)}:void 0}},ll=(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 ct(s)?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 ct(o)||ct(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),cl=(e,t)=>Y(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=>ct(e))){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=>ct(e))?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;oe.track)}),ul=(e,t)=>{const i=1e6,r=1+1e-9,n=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let v=1;v0))return null;s[v-1]=t}const a=s.slice();a.sort();let o=a[Math.floor(.05*a.length)];for(let v=0;v<6;v++){let e=0,t=0;for(const n of s){const i=Math.max(1,Math.round(n/o));Math.abs(n-i*o)>=r||(e+=n,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let l=0,c=0,u=0;for(const v of s){const e=Math.max(1,Math.round(v/o));Math.abs(v-e*o)>=r||(l++,c+=v,u+=e)}if(l/s.length<.98)return null;o=c/u;const d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const v of n){if(vp)continue;const e=Math.abs(v/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,n=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof Ea)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ea||e.source instanceof ta))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ea&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof ml))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=null!=(t=e.initInput)?t:null,this._formatOptions=null!=(i=e.formatOptions)?i:{},e.source instanceof ea?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return Y(this,null,function*(){oe(this._rootSource instanceof ia);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&&ra(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ra(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>Y(this,null,function*(){const i=yield this._getSourceUncached(e);if(gt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=kt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);oe(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),Me(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);oe(-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=(()=>Y(this,null,function*(){var e;this._reader=new kl(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 pl}))()}get source(){return this._rootSource}getFormat(){return Y(this,null,function*(){return yield this._getDemuxer(),oe(this._format),this._format})}canRead(){return Y(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof pl)return!1;throw e}})}getFirstTimestamp(e){return Y(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._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>{var t;return null!=(t=null==e?void 0:e.timestamp)?t:1/0}));return r===1/0?0:r})}computeDuration(e,t){return Y(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 Y(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 Y(this,null,function*(){e&&(e=ol(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return cl(t,e)})}getVideoTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return cl(t,e)})}getAudioTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return cl(t,e)})}getPrimaryVideoTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=ll(e,{sortBy:e=>Y(null,null,function*(){return[al((yield e.getDisposition()).default),al(yield e.hasPairableAudioTrack()),al(!(yield e.hasOnlyKeyPackets())),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=yield this.getPrimaryVideoTrack(),r=ll(e,{sortBy:e=>Y(this,null,function*(){return[al(!i||e.canBePairedWith(i)),al((yield e.getDisposition()).default),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return Y(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 rl(this,e):new nl(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class pl extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class gl extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class kl{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 gl;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 yl(t,me(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Zs);return ct(r)?r.then(t=>t?new yl(t.bytes,t.view,t.offset,e,i):null):r?new yl(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new gl;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(oe(null!==this.fileSizeNonStrict),this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i)));return ct(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>Y(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(ct(i)&&(i=yield i),!i||0===i.length)break;const r=Tl(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return new yl(i,me(i),0,0,t)}))()}}class yl{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 yl(e,me(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new yl(this.bytes,this.view,this.offset,e,e+t)}}const bl=(e,t)=>{if(e.filePose.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.`)},Tl=(e,t)=>{bl(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},vl=e=>(bl(e,1),e.view.getUint8(e.bufferPos++)),wl=(e,t)=>{bl(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Sl=e=>{bl(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Pl=e=>{bl(e,3);const t=Le(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Il=e=>{bl(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},xl=(e,t)=>{bl(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Cl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Bl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},El=e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},_l=(e,t)=>{let i,r;return t?(i=xl(e,!0),r=xl(e,!0)):(r=xl(e,!1),i=xl(e,!1)),4294967296*r+i},Rl=e=>4294967296*Cl(e)+Cl(e),Fl=e=>4294967296*El(e)+Cl(e),Al=e=>{const t=Bl(e),i=(e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Ml=e=>{bl(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Dl=e=>{bl(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Nl=(e,t)=>{bl(e,t);let i="";for(let r=0;rpe.decode(Tl(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 Ll,zl,Ul,ql;(zl=Ll||(Ll={}))[zl.Unsynchronisation=128]="Unsynchronisation",zl[zl.ExtendedHeader=64]="ExtendedHeader",zl[zl.ExperimentalIndicator=32]="ExperimentalIndicator",zl[zl.Footer=16]="Footer",(ql=Ul||(Ul={}))[ql.ISO_8859_1=0]="ISO_8859_1",ql[ql.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",ql[ql.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",ql[ql.UTF_8=3]="UTF_8";const Wl=128,Hl=10,Vl=["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"],jl=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Tl(e,Wl-3)),e.filePos=r;const n=Kl(e,30);n&&(null!=t.title||(t.title=n));const s=Kl(e,30);s&&(null!=t.artist||(t.artist=s));const a=Kl(e,30);a&&(null!=t.album||(t.album=a));const o=Kl(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Tl(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=Kl(e,28),e.skip(2)}else e.skip(-30),u=Kl(e,30);u&&(null!=t.comment||(t.comment=u));const d=vl(e);d{const i=Tl(e,t),r=ut(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Nl(e,3),r=vl(e),n=vl(e),s=vl(e),a=Cl(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=mr(a);return s&Ll.Footer&&(o+=Hl),{majorVersion:r,revision:n,flags:s,size:o}},$l=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void Pt._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Ll.Footer?t.size-Hl:t.size,u=Tl(e,c),d=new Gl(t,u);if(t.flags&Ll.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Ll.ExtendedHeader){const e=d.readU32();3===t.majorVersion?d.pos+=e:d.pos+=e-4}for(;d.pos<=d.bytes.length-d.frameHeaderSize();){const e=d.readId3V2Frame();if(!e)break;const c=d.pos,u=d.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&Ll.Unsynchronisation)),h)Pt._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)Pt._warn(`Skipping compressed ID3v2 frame ${e.id}`),d.pos=u;else{if(m&&d.ununsynchronizeRegion(d.pos,u),null!=i.raw||(i.raw={}),"TXXX"===e.id){const e=null!=(n=(r=i.raw).TXXX)?n:r.TXXX={},t=d.readId3V2TextEncoding(),s=d.readId3V2Text(t,u),a=d.readId3V2Text(t,u);null!=e[s]||(e[s]=a)}else"T"===e.id[0]?null!=(s=i.raw)[a=e.id]||(s[a]=d.readId3V2EncodingAndText(u)):null!=(o=i.raw)[l=e.id]||(o[l]=d.readBytes(e.size));switch(d.pos=c,e.id){case"TIT2":case"TT2":null!=i.title||(i.title=d.readId3V2EncodingAndText(u));break;case"TIT3":case"TT3":null!=i.description||(i.description=d.readId3V2EncodingAndText(u));break;case"TPE1":case"TP1":null!=i.artist||(i.artist=d.readId3V2EncodingAndText(u));break;case"TALB":case"TAL":null!=i.album||(i.album=d.readId3V2EncodingAndText(u));break;case"TPE2":case"TP2":null!=i.albumArtist||(i.albumArtist=d.readId3V2EncodingAndText(u));break;case"TRCK":case"TRK":{const e=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}null!=i.genre||(i.genre=e)}break;case"TDRC":case"TDAT":{const e=d.readId3V2EncodingAndText(u),t=new Date(e);Number.isNaN(t.getTime())||null!=i.date||(i.date=t)}break;case"TYER":case"TYE":{const e=d.readId3V2EncodingAndText(u),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=i.date||(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.lyrics||(i.lyrics=d.readId3V2Text(e,u))}break;case"COMM":case"COM":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.comment||(i.comment=d.readId3V2Text(e,u))}break;case"APIC":case"PIC":{const e=d.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=d.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=d.readId3V2Text(e,u);const n=d.readU8(),s=d.readId3V2Text(e,u).trimEnd(),a=u-d.pos;if(a>=0){const e=d.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:d.pos+=e.size}d.pos=u}}};class Gl{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{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:mr(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 Ul.ISO_8859_1:{let e="";for(let t=0;t0===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=ut(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=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}case Ul.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=ut(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 Ul.UTF_8:{const e=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ql{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch(n){i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(s){try{null==r||r.disconnect()}catch(a){console.warn("MediaBunny gain setup cleanup:",a)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),s}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{null==t||t.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Yl{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(n){r=!0,i=n}try{e.disconnect()}catch(n){r||(r=!0,i=n)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const n=function(e,t,i,r){const n=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(n+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(n,r),offset:n=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===n.offset?s.start(n.startAt):s.start(n.startAt,n.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,n.endMediaTime)}catch(a){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw a}}}const Jl=Symbol("cancelled");class Zl{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Jl);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function ec(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class tc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}stopIterator(){return Y(this,null,function*(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),yield t})}cancel(){var e;null==(e=this.task)||e.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}run(e){return Y(this,null,function*(){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Zl;this.task=r;let n=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!n||this.host.audioIterator===n);try{for(n=t.buffers(this.host.currentTime),this.host.audioIterator=n;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=yield r.wait(n.next());if(i===Jl||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if((yield r.wait(this.contexts.resume(i)))===Jl||!s())return;ec(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(yield r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(yield r.delay(50))||!s())return}}catch(a){if(s())throw a}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}})}}class ic{constructor(e,d){X(this,u),X(this,t,!1),X(this,i,0),X(this,r),X(this,n),X(this,s),X(this,a,null),X(this,o,null),X(this,l,null),X(this,c),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,$(this,r,new Ql(this)),$(this,n,new Yl(this)),$(this,s,new tc(this,K(this,r),K(this,n))),$(this,c,d)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){K(this,r).ensure(e)}updateGain(){K(this,r).updateGain()}stopQueuedNodes(){K(this,n).stop()}stopIterator(){return Y(this,null,function*(){yield K(this,s).stopIterator()})}handleNoAudioTrack(){K(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){Q(this,i)._++;try{this.pause()}finally{$(this,l,null),this.input=null,this.audioSink=null}}load(e,r){return Y(this,null,function*(){if(K(this,t))return;this.cancelPending();const n=K(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>G(this,u,d).call(this,e,n,r));$(this,l,s);try{yield s}finally{K(this,l)===s&&$(this,l,null)}})}runIterator(e){return Y(this,null,function*(){K(this,t)||(yield K(this,s).run(e))})}play(){return Y(this,null,function*(){if(K(this,t))return;if(K(this,o))return K(this,o);if(!this.paused)return;const e=new Zl;$(this,a,e);const r=K(this,i),n=G(this,u,f).call(this,e,r);$(this,o,n);try{yield n}finally{K(this,a)===e&&($(this,a,null),$(this,o,null))}})}pause(){var e;this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,null==(e=K(this,a))||e.cancel(),$(this,a,null),$(this,o,null),K(this,s).cancel(),this.stopQueuedNodes()}seek(e){return Y(this,null,function*(){var i,r;if(K(this,t))return;const n=!this.paused;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.latestScheduledEndTime=this.playbackTimeAtStart;const a=++this.asyncId;n&&G(this,u,h).call(this,a)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){var i,r;if(K(this,t)||e===this.playbackRate)return;const n=this.currentTime;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=n,this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.playbackRate=e,this.latestScheduledEndTime=n;const a=++this.asyncId;this.paused||G(this,u,h).call(this,a)}destroy(){if(K(this,t))return;$(this,t,!0),Q(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>K(this,r).destroy()])try{t()}catch(n){e.push(n)}if(this.input=null,this.audioSink=null,$(this,l,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakSet,d=function(e,r,n){return Y(this,arguments,function*({input:e,audioTrack:r,duration:n},s,a){const o=()=>!K(this,t)&&K(this,i)===s;if(o()){this.input=e,this.duration=n;try{const e=r&&null!==r.codec&&(yield r.canDecode());if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new Zo(r)}else this.handleNoAudioTrack();o()&&(null==a||a())}catch(l){if(o())throw l}}})},h=function(e){this.runIterator(e).catch(i=>{if(!K(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{K(this,c)?K(this,c).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=function(e,n){return Y(this,null,function*(){const s=()=>!K(this,t)&&!e.cancelled&&K(this,i)===n;try{const t=K(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if((yield e.wait(K(this,r).resume(t)))===Jl||!s())return}if(K(this,l)){if((yield e.wait(K(this,l)))===Jl||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,G(this,u,h).call(this,++this.asyncId)}catch(a){if(s())throw a}})};const rc=new WeakMap;function nc(e,t,i){return Y(this,null,function*(){var r;const{input:n,loadSeq:s}=e;if(!(null==(r=e.media)?void 0:r.isHls)||!n||e.destroyed)return;const a={};rc.set(e,a);const o=()=>!e.destroyed&&e.loadSeq===s&&e.input===n&&rc.get(e)===a;for(;o();){const r=e.media;if(!(null==r?void 0:r.isHls))return;let s;try{s=yield i(n,r,t,o)}catch(l){if(!o())return;if(e.media===r)throw l;continue}if(!o())return;if(e.media===r){if(s)try{yield e.replaceTracks(s)}catch(l){if(o())throw l}return}}})}function sc(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getVideoTracks();if(!r())return null;const a="auto"===i?yield e.getPrimaryVideoTrack():null!=(n=s.find(e=>e.id===i))?n:t.videoTrack;if(!r()||!a)return null;let o=t.audioTrack,l=t.audioMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableAudioTrack(),l="auto"),{videoTrack:a,audioTrack:o,videoMode:"auto"===i?"auto":"manual",audioMode:l}})}function ac(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getAudioTracks();if(!r())return null;const a="auto"===i?t.videoTrack?yield t.videoTrack.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack():null!=(n=s.find(e=>e.id===i))?n:t.audioTrack;if(!r()||!a)return null;let o=t.videoTrack,l=t.videoMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableVideoTrack(),l="auto"),{videoTrack:o,audioTrack:a,videoMode:l,audioMode:"auto"===i?"auto":"manual"}})}function oc(e){return Y(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const lc=/\.m3u8(?:$|[?#])/i;function cc(e){return"string"===typeof e&&lc.test(e)}function uc(e){const t=function(e){return"string"===typeof e?new ua(e):e instanceof Blob?new aa(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new fa(e):null!=e?e:null}(e);return t?new ml({source:t,formats:cc(e)?eo:Za}):null}class dc{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){var e;return null==(e=this.controller)?void 0:e.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}wait(e,t){return Y(this,null,function*(){try{yield Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}})}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,null==e||e.dispose()}cancel(){var e;if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),null==(e=this.controller)||e.abort(),this.disposeInput()}}}function hc(e){return Y(this,arguments,function*({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),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 fc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class mc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return V(H({},fc()),{source:this.host.loadSeq,complete:fc()})}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,null==e||e.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,null==e||e.complete.resolve(),null==e||e.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}runPlay(e){return Y(this,null,function*(){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(yield this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,yield this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),ec(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}})}seek(e,t){return this.position(t=>Y(this,null,function*(){const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();yield Promise.all([i,r])}),["seeked"],!1,t)}replace(e,t){return this.position(i=>Y(this,null,function*(){e.duration=yield hc(e),i()&&(this.host.media=e,yield Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(yield Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))}),["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=null!=r?r:this.seeking?this.wanted:!this.host.paused,this.cancelPlay();const n=this.seeking,s=this.operation();return this.seeking=s,null==n||n.complete.resolve(),null==n||n.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}runPosition(e,t,i,r){return Y(this,null,function*(){const n=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!n())return;if(this.host.ended=!1,this.host.seeking=!0,ec(this.host.events,n,["seeking","waiting"]),!n())return;if(r||this.stop(),!n())return;if(yield t(n),!n())return;if(this.host.seeking=!1,e.complete.resolve(),ec(this.host.events,n,i),!n())return;this.seeking=null,s=this.wanted}catch(a){if(!n())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(a),a}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&(yield this.play())})}}const pc=new WeakMap,gc=new WeakMap;function kc(e){const t=gc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>{var t;return null!=(t=e.value)?t:null});gc.set(e,i);const r=()=>{gc.get(e)===i&&gc.delete(e)};return i.then(r,r),i}function yc(e,t,i,r,n){const s=i?Math.max(.06,r/Math.max(1,n)):0;return i&&e{if(this.image===n&&t()){this.cancel();try{i(n)}catch(e){r(e)}}},n.onerror=()=>{this.image===n&&this.cancel()},n.src=e}}class Tc{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}update(e){return Y(this,null,function*(){var t;const i=this.host.videoIterator;if(!i||!this.ready()||!this.current(e)||this.host.isFetching)return;const r={};this.fetching=r,this.host.isFetching=!0;const n=()=>this.current(e)&&this.host.videoIterator===i;try{for(;n();){const e=yield kc(i);if(!n()||!e)return;const r=null==(t=this.host.audioClock)?void 0:t.currentTime;if(void 0===r)return;const s=yc(e.timestamp,r,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==s){if("draw"!==s)return void(this.host.nextFrame=e);this.draw(e)}}}catch(s){if(n())throw s}finally{this.fetching===r&&(this.fetching=null,this.host.isFetching=!1)}})}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void ec(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(ec(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!K(this,T),e=>G(this,P,E).call(this,e,!0),e=>G(this,P,C).call(this,e)))}preflight(e,t,i){return Y(this,null,function*(){return function(e,t,i,r,n=()=>!0){return Y(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||cc(e))return!0;try{const t=yield fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if((null==r?void 0:r.aborted)||!n())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!((null==r?void 0:r.aborted)||!n())&&(console.warn("Preflight check failed:",s),!0)}})}(e,this.preflightRange,this.events,t,i)})}drawPoster(){if(K(this,b)||!this.poster||this.posterDrawn)return;const e=K(this,m);K(this,v).draw(this.poster,()=>G(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,G(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>G(this,P,C).call(this,e))}stopIterator(){return Y(this,null,function*(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,yield function(e){if(!e)return Promise.resolve();const t=pc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return pc.set(e,i),i}(e)})}clear(){G(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){Q(this,m)._++,Q(this,p)._++,this.stop(),G(this,P,B).call(this),K(this,v).cancel(),$(this,T,!1),$(this,g,null),$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null}load(e,t){return Y(this,null,function*(){if(K(this,b))return;this.cancelPending();const i=K(this,m),r=K(this,p);$(this,T,!0);const n=Promise.resolve().then(()=>G(this,P,_).call(this,e,i,r,t));$(this,g,n);try{yield n}finally{K(this,g)===n&&$(this,g,null)}})}handleNoVideoTrack(){K(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}resetIterator(e){return Y(this,null,function*(){if(K(this,b))return;const t=K(this,m),i=++Q(this,p)._,r=K(this,g);this.stop(),K(this,v).cancel(),$(this,T,!0);try{r&&(yield r),yield G(this,P,R).call(this,e,t,i)}catch(n){if(G(this,P,I).call(this,t)&&K(this,p)===i)throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})}updateNextFrame(e){return Y(this,null,function*(){yield K(this,w).update(e)})}render(){K(this,w).render()}start(e){K(this,w).start(e)}stop(){K(this,w).stop()}seek(e){return Y(this,null,function*(){yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){K(this,b)||($(this,b,!0),Q(this,m)._++,K(this,w).destroy(),K(this,v).cancel(),G(this,P,B).call(this),this.posterDrawn=!1,$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,T=new WeakMap,v=new WeakMap,w=new WeakMap,S=new WeakMap,P=new WeakSet,I=function(e){return!K(this,b)&&K(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){K(this,b)||(G(this,P,B).call(this),K(this,S)?K(this,S).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){K(this,v).cancel(),t&&this.clear(),G(this,P,x).call(this).drawImage(e.canvas,0,0)},_=function(e,t,i,r){return Y(this,null,function*(){if(G(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:n,videoTrack:s,duration:a}=e;if(this.input=n,this.duration=a,!s)return this.handleNoVideoTrack(),void(null==r||r());const o=null!==s.codec&&(yield s.canDecode());if(!G(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void(null==r||r());const l=yield s.canBeTransparent();if(!G(this,P,I).call(this,t))return;$(this,k,()=>new Go(s,{poolSize:2,fit:"contain",alpha:l})),this.videoSink=K(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==r||r(),G(this,P,I).call(this,t)&&(yield G(this,P,R).call(this,0,t,i))}catch(n){if(G(this,P,I).call(this,t))throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})},R=function(e,t,i){return Y(this,null,function*(){if(!G(this,P,I).call(this,t)||K(this,p)!==i)return;G(this,P,B).call(this),K(this,k)&&this.videoSink===K(this,y)&&(this.videoSink=K(this,k).call(this));const r=this.videoSink;if(!r||!G(this,P,I).call(this,t))return;$(this,y,r);const n=r.canvases(e);this.videoIterator=n;const s=()=>G(this,P,I).call(this,t)&&K(this,p)===i&&this.videoIterator===n,a=yield kc(n);if(!s())return;const o=yield kc(n);s()&&(this.nextFrame=o,a?G(this,P,E).call(this,a,!1):this.drawPoster())})};class wc{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l;X(this,F),this.events=i,this.option=r,this.audio=new ic(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new vc({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,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,$(this,F,new mc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,K(this,F).ended(),this.audio.pause())})}load(e){return Y(this,null,function*(){var t,i;if(this.destroyed)return;const r=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),null==(t=this.loadSession)||t.cancel(),r!==this.loadSeq||this.destroyed)return;if(this.pause(),r!==this.loadSeq||this.destroyed)return;this.disposeInput();const n=new dc;this.loadSession=n,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,n.defer(()=>this.events.emit("waiting")),n.defer(()=>this.events.emit("loadstart"));const s=Number.isFinite(this.option.loadTimeout)&&null!=(i=this.option.loadTimeout)?i:0;try{yield n.wait(this.performLoad(e,r,n),s)}catch(a){if(r!==this.loadSeq)return;const e=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),n.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}})}performLoad(e,t){return Y(this,arguments,function*(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(yield this.video.preflight(e,i.signal,r))||!r())return;const n=uc(e);if(!n)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(n);const s=yield function(e,t){return Y(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield hc({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=cc(t);return{input:e,videoTrack:i,audioTrack:r,duration:n,isLive:!Number.isFinite(n)&&Boolean(s&&(yield s.isLive())),isHls:a,videoMode:a?"auto":"manual",audioMode:a?"auto":"manual"}})}(n,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=n,this.media=s;const a=function(e,t){let i=!1,r=!1,n=!1;function s(s){t()&&!n&&("video"===s?i=!0:r=!0,i&&r&&(n=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,ec(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,a.video),t=r()?this.audio.load(s,a.audio):Promise.resolve();if(yield Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,ec(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}})}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){var e;null==(e=this.loadSession)||e.disposeInput(),this.input=null,this.media=null}replaceTracks(e){return Y(this,null,function*(){if(this.media&&!this.destroyed)return K(this,F).replace(H(H({},this.media),e),this.currentTime)})}selectHlsQuality(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,sc)}(this,e)})}selectHlsAudio(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,ac)}(this,e)})}getHlsState(){return Y(this,null,function*(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=yield function(e){return Y(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)=>Y(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield oc(e)}}))),Promise.all(a.map((e,t)=>Y(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 oc(e)}})))]);return{levels:o,audios:l,currentLevel:e.videoTrack&&null!=(t=o.find(t=>{var i;return t.id===(null==(i=e.videoTrack)?void 0:i.id)}))?t:null,currentAudio:e.audioTrack&&null!=(i=l.find(t=>{var i;return t.id===(null==(i=e.audioTrack)?void 0:i.id)}))?i:null,videoMode:null!=(r=e.videoMode)?r:"auto",audioMode:null!=(n=e.audioMode)?n:"auto"}})}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}})}play(){return Y(this,null,function*(){return K(this,F).play()})}pause(){K(this,F).pause()}seek(e){return Y(this,null,function*(){return K(this,F).seek(e)})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,K(this,F).invalidate();const e=[];for(const i of[()=>{var e;return null==(e=this.loadSession)?void 0:e.cancel()},()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){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}}F=new WeakMap;const Sc=new WeakMap;function Pc(e){let t=Sc.get(e);return t||(t={closed:!1,frames:new Set},Sc.set(e,t)),t}class Ic{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new ae,this.engine=new wc({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){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=Pc(e);if(i.closed)return 0;const r=requestAnimationFrame(n=>{i.frames.delete(r),i.closed||t(n,{presentationTime:e.engine.currentTime,expectedDisplayTime:n+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:n,receiveTime:n,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){Pc(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=Pc(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}return function(e={}){return t=>{const{constructor:i}=t,{createElement:r}=i.utils,n=r("canvas"),s=n.getContext("2d"),a=new Ic({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),se({art:t,shim:a,option:e}),t.on("destroy",()=>{delete t.mediabunny,a.destroy()}),n}}}); +!function(e,t){"object"===typeof exports&&"undefined"!==typeof module?module.exports=t():"function"==typeof define&&define.amd?(e.artplayerProxyMediabunny=t(),define(function(){return e.artplayerProxyMediabunny})):(e="undefined"!==typeof globalThis?globalThis:e||self).artplayerProxyMediabunny=t()}(this,function(){"use strict";var e,t,i,r,n,s,a,o,l,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A=Object.defineProperty,M=Object.defineProperties,D=Object.getOwnPropertyDescriptors,N=Object.getOwnPropertySymbols,O=Object.prototype.hasOwnProperty,L=Object.prototype.propertyIsEnumerable,z=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),U=e=>{throw TypeError(e)},q=Math.pow,W=(e,t,i)=>t in e?A(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i,H=(e,t)=>{for(var i in t||(t={}))O.call(t,i)&&W(e,i,t[i]);if(N)for(var i of N(t))L.call(t,i)&&W(e,i,t[i]);return e},V=(e,t)=>M(e,D(t)),j=(e,t,i)=>t.has(e)||U("Cannot "+i),K=(e,t,i)=>(j(e,t,"read from private field"),i?i.call(e):t.get(e)),X=(e,t,i)=>t.has(e)?U("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(e):t.set(e,i),$=(e,t,i,r)=>(j(e,t,"write to private field"),r?r.call(e,i):t.set(e,i),i),G=(e,t,i)=>(j(e,t,"access private method"),i),Q=(e,t,i,r)=>({set _(r){$(e,t,r,i)},get _(){return K(e,t,r)}}),Y=(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())}),J=function(e,t){this[0]=e,this[1]=t},Z=(e,t,i)=>{var r,n=(e,t,r,s)=>{try{var a=i[e](t),o=(t=a.value)instanceof J,l=a.done;Promise.resolve(o?t[0]:t).then(i=>o?n("return"===e?e:"next",t[1]?{done:i.done,value:i.value}:i,r,s):r({value:i,done:l})).catch(e=>n("throw",e,r,s))}catch(c){s(c)}},s=(e,t,i,s)=>a[e]=a=>(t=new Promise((t,i,s)=>(s=()=>n(e,a,t,i),r?r.then(s):s())),s=()=>r===i&&(r=0),r=i=t.then(s,s),t),a={};return i=i.apply(e,t),a[z("asyncIterator")]=()=>a,s("next"),s("throw"),s("return"),a},ee=e=>{var t,i=e[z("asyncIterator")],r=!1,n={};return null==i?(i=e[z("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 J(new Promise(r=>{var n=i[e](t);n instanceof Object||U("Object expected"),r(n)}),1)}}),n[z("iterator")]=()=>n,t("next"),"throw"in i?t("throw"):n.throw=e=>{throw e},"return"in i&&t("return"),n},te=(e,t,i)=>(t=e[z("asyncIterator")])?t.call(e):(e=e[z("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 ie(e){const t=[];for(const r of e)try{r()}catch(i){t.push(i)}if(t.length)throw t[0]}function re(e,t,i){const r={control:!1,setting:!1};let n=null;function s(i){r[i]&&(r[i]=!1,"control"===i?e.controls.cache.has(t)&&e.controls.remove(t):e.setting.find(t)&&e.setting.remove(t))}function a(){n=null,ie([()=>s("control"),()=>s("setting")])}return{update:function(o,l,c,u){if(!o)return void a();n=o;const d=()=>n===o&&c(),h=e=>Y(null,null,function*(){return d()&&o.selector.some(t=>t.value===e.value)?u(e,o.title):e.html});l.control?(r.control=!0,e.controls.update({name:t,position:"right",html:o.html,style:{padding:"0 10px"},selector:o.selector,onSelect:h})):s("control"),d()&&(l.setting?(r.setting=!0,e.setting.update({name:t,tooltip:o.html,html:o.title,icon:i,width:200,selector:o.selector,onSelect:h})):s("setting"))},clear:a}}function ne(e){const t=new Map,i=[];for(const r of e){const e=t.get(r.html);void 0!==r.html&&void 0!==e?r.default&&(i[e]=r):(t.set(r.html,i.length),i.push(r))}return i}function se({art:e,shim:t,option:i}){if(!i.m3u8)return;let r=!1,n=0,s=0;const a=re(e,"mediabunny-quality",''),o=re(e,"mediabunny-audio",''),l=e=>!r&&!t.engine.destroyed&&t.engine.loadSeq===e;function c(){return Y(this,null,function*(){var e,s;if(r||t.engine.destroyed)return;const c=++n,d=t.engine.loadSeq,h=()=>c===n&&l(d);try{const r=yield t.getM3u8State();if(!h())return;const n=(null==(e=i.m3u8)?void 0:e.quality)||{},c=function(e,t,i){var r;if(!t.control&&!t.setting||!(null==e?void 0:e.levels.length))return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||`${e.height}P`),a=e.currentLevel?s(e.currentLevel):n,o=[];for(const u of e.levels){if(!i())return null;o.push({html:s(u),value:u.id,default:(null==(r=e.currentLevel)?void 0:r.id)===u.id})}const l=new Map(e.levels.map(e=>[e.id,e.height])),c=ne(o).sort((e,t)=>("auto"===t.value?0:l.get(t.value)||0)-("auto"===e.value?0:l.get(e.value)||0));return c.push({html:n,value:"auto",default:!e.currentLevel}),{title:t.title||"Quality",html:a,selector:c}}(r,n,h);if(!h())return;if(a.update(c,n,()=>l(d),(e,t)=>u("quality",e,t)),!h())return;const f=(null==(s=i.m3u8)?void 0:s.audio)||{},m=function(e,t,i){var r;if(!t.control&&!t.setting||!e||e.audios.length<2)return null;const n=t.auto||"Auto",s=t.getName||(e=>e.name||e.lang||e.language),a=e.currentAudio?s(e.currentAudio):n,o=[];for(const c of e.audios){if(!i())return null;o.push({html:s(c),value:c.id,default:(null==(r=e.currentAudio)?void 0:r.id)===c.id})}const l=ne(o);return l.push({html:n,value:"auto",default:!e.currentAudio}),{title:t.title||"Audio",html:a,selector:l}}(r,f,h);h()&&o.update(m,f,()=>l(d),(e,t)=>u("audio",e,t))}catch(f){if(h())throw f}})}function u(i,r,a){return Y(this,null,function*(){const o=++s,u=t.engine.loadSeq;n++;const h=()=>o===s&&l(u);try{"quality"===i?yield t.switchM3u8Quality(r.value):yield t.switchM3u8Audio(r.value),h()&&(yield c(),h()&&(e.notice.show=`${a}: ${r.html}`))}catch(f){if(h()&&(yield d(),h()))throw f}return r.html})}function d(){return c().catch(e=>console.warn("MediaBunny HLS menu update:",e))}function h(){n++,s++;try{ie([a.clear,o.clear])}catch(e){console.warn("MediaBunny HLS menu cleanup:",e)}}function f(){if(!r){r=!0,h();try{ie([()=>e.off("video:loadedmetadata",d),()=>e.off("restart",d),()=>e.off("video:loadstart",h),()=>e.off("video:error",h),()=>e.off("destroy",f)])}catch(t){console.warn("MediaBunny HLS listener cleanup:",t)}}}try{e.on("video:loadedmetadata",d),e.on("restart",d),e.on("video:loadstart",h),e.on("video:error",h),e.on("destroy",f)}catch(m){throw f(),m}return{update:c,destroy:f}}class ae{constructor(){X(this,e,!1),this.listeners=new Map}addEventListener(t,i){var r;K(this,e)||(this.listeners.has(t)||this.listeners.set(t,[]),null==(r=this.listeners.get(t))||r.push(i))}removeEventListener(e,t){const i=this.listeners.get(e);if(!i)return;const r=i.indexOf(t);r>=0&&i.splice(r,1)}emit(t,i){var r;if(K(this,e))return;const n=Object.assign(new Event(t),{detail:i});null==(r=this.listeners.get(t))||r.forEach(t=>{K(this,e)||t(n)})}destroy(){$(this,e,!0),this.listeners.clear()}}function oe(e){if(!e)throw new Error("Assertion failed.")}e=new WeakMap;const le=e=>{const t=(e%360+360)%360;if(0===t||90===t||180===t||270===t)return t;throw new Error(`Invalid rotation ${e}.`)},ce=e=>e&&e[e.length-1],ue=e=>{let t=0;for(;0===e.readBits(1)&&t<32;)t++;if(t>=32)throw new Error("Invalid exponential-Golomb code.");return(1<{const i=t+1,r=Math.floor(Math.log2(i));e.writeBits(r,0),e.writeBits(1,1),e.writeBits(r,i-q(2,r))},he=e=>{const t=ue(e);return 0===(1&t)?-(t>>1):t+1>>1},fe=e=>e.constructor===Uint8Array?e:ArrayBuffer.isView(e)?new Uint8Array(e.buffer,e.byteOffset,e.byteLength):new Uint8Array(e),me=e=>e.constructor===DataView?e:ArrayBuffer.isView(e)?new DataView(e.buffer,e.byteOffset,e.byteLength):new DataView(e),pe=new TextDecoder,ge=e=>Object.fromEntries(Object.entries(e).map(([e,t])=>[t,e])),ke={bt709:1,bt470bg:5,smpte170m:6,bt2020:9,smpte432:12},ye=ge(ke),be={bt709:1,smpte170m:6,linear:8,"iec61966-2-1":13,pq:16,hlg:18},Te=ge(be),ve={rgb:0,bt709:1,bt470bg:5,smpte170m:6,"bt2020-ncl":9},we=ge(ve),Se=e=>!!e&&!!e.primaries&&!!e.transfer&&!!e.matrix&&void 0!==e.fullRange,Pe={primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0},Ie=e=>e instanceof ArrayBuffer||"undefined"!==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||ArrayBuffer.isView(e);class xe{constructor(){this.currentPromise=Promise.resolve(),this.pending=0}acquire(){return Y(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 Ce=/^[0-9a-fA-F]+$/,Be=e=>[...e].map(e=>e.toString(16).padStart(2,"0")).join(""),Ee=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,_e=(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{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},Fe=(e,t,i)=>{const r=Re(e,i(t),i);e.splice(r+1,0,t)},Ae=()=>{let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}},Me=(e,t)=>{const i=e.indexOf(t);-1!==i&&e.splice(i,1)},De=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return e[i]},Ne=(e,t)=>{for(let i=e.length-1;i>=0;i--)if(t(e[i]))return i;return-1},Oe=e=>{throw new Error(`Unexpected value: ${e}`)},Le=(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},ze=(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)},Ue=(e,t)=>({next(){return Y(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}}),qe=(e,t,i)=>Math.max(t,Math.min(i,e)),We="und",He=e=>{const t=Math.round(e);return Math.abs(e/t-1)<10*Number.EPSILON?t:e},Ve=(e,t)=>Math.round(e/t)*t,je=(e,t)=>Math.round(e*t)/t,Ke=(e,t)=>Math.floor(e/t)*t,Xe=e=>{let t=0;for(;0!==e;)e&=e-1,t++;return t},$e=/^[a-z]{3}$/,Ge=e=>$e.test(e),Qe=1e6*(1+Number.EPSILON),Ye=(e,t)=>{const i=H(H({},e),t);if(e.headers||t.headers){const r=e.headers?Je(e.headers):{},n=t.headers?Je(t.headers):{},s=H({},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},Je=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},Ze=(e,t,i,r,n)=>Y(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(Pt._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 Tt(1e3*e)),n())throw a}});class et{constructor(){this.currentPromise=Promise.resolve()}call(e){return this.currentPromise=this.currentPromise.then(e)}}let tt=null;const it=()=>{var e;return null!==tt?tt:tt=!("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 rt=null;const nt=()=>{var e;return null!==rt?rt:rt="undefined"!==typeof navigator&&(null==(e=navigator.userAgent)?void 0:e.includes("Firefox"))};let st=null;const at=()=>{var e;return null!==st?st:st=!("undefined"===typeof navigator||!(null==(e=navigator.vendor)?void 0:e.includes("Google Inc"))&&!/Chrome/.test(navigator.userAgent))},ot=e=>"undefined"===typeof globalThis.isSecureContext||globalThis.isSecureContext?`${e} is not available in this environment.`:`${e} is not available in this environment; this may be because this page is running in an insecure context. Try serving your page over HTTPS or use localhost.`,lt=Y(null,null,function*(){}).constructor,ct=e=>e instanceof lt||e instanceof Promise||"function"===typeof(null==e?void 0:e.then),ut=(e,t)=>-1!==e?e:t,dt=(e,t,i,r)=>e<=r&&i<=t,ht=e=>{const t=atob(e),i=new Uint8Array(t.length);for(let r=0;r{null!=Symbol.dispose||(Symbol.dispose=Symbol("Symbol.dispose"))},mt=e=>"number"===typeof e&&!Number.isNaN(e),pt=(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("/")},gt=(e,t)=>{let i=0;for(let r=0;r{let i=-1,r=1/0;for(let n=0;n{oe(Number.isInteger(e.num)),oe(Number.isInteger(e.den)),oe(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}},bt=(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.`)},Tt=e=>new Promise(t=>setTimeout(t,e));class vt{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)}}}var wt,St;(St=wt||(wt={}))[St.Silent=0]="Silent",St[St.Errors=1]="Errors",St[St.Warnings=2]="Warnings",St[St.Info=3]="Info";class Pt{constructor(){}static get level(){return Pt._level}static set level(e){if(e!==wt.Silent&&e!==wt.Errors&&e!==wt.Warnings&&e!==wt.Info)throw new TypeError("Invalid log level. Use one of the values of the LogLevel enum.");Pt._level=e}static get _emitter(){var e;return null!=(e=Pt._emitterInstance)?e:Pt._emitterInstance=new vt}static on(e,t,i){return Pt._emitter.on(e,t,i)}static _error(...e){Pt._emitter._emit("error",e),Pt._level>=wt.Errors&&console.error(...e)}static _warn(...e){Pt._emitter._emit("warn",e),Pt._level>=wt.Warnings&&console.warn(...e)}static _info(...e){Pt._emitter._emit("info",e),Pt._level>=wt.Info&&console.info(...e)}}Pt._level=wt.Info,Pt._emitterInstance=null;class It{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 xt{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 Ct={default:!0,primary:!0,forced:!1,original:!1,commentary:!1,hearingImpaired:!1,visuallyImpaired:!1};class Bt{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;return this.pos++,n}readBits(e){if(1===e)return this.readBit();let t=0;for(let i=0;i>i-r-1<0&&this.writeBits(r,t.readBits(r))}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 Bt(this.bytes);return e.pos=this.pos,e}}const Et=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],_t=[-1,1,2,3,4,5,6,8],Rt=e=>{if(!e||e.byteLength<2)throw new TypeError("AAC description must be at least 2 bytes long.");const t=new Bt(e),i=Ft(t),{frequencyIndex:r,sampleRate:n}=At(t),s=t.readBits(4);let a=null;s>=1&&s<=7&&(a=_t[s]);let o=i,l=!1,c=n;if(5===i||29===i)l=29===i,c=At(t).sampleRate,o=Ft(t),22===o&&t.skipBits(4);else for(;t.getBitsLeft()>15;){const e=t.pos;if(695===t.readBits(11)){5===Ft(t)&&t.readBits(1)&&(c=At(t).sampleRate,t.getBitsLeft()>11&&1352===t.readBits(11)&&(l=!!t.readBits(1)));break}t.pos=e+1}return null!==a&&a>1&&(l=!1),{objectType:i,coreObjectType:o,frequencyIndex:r,channelConfiguration:s,outputSampleRate:c,outputNumberOfChannels:l&&1===a?2:a}},Ft=e=>{const t=e.readBits(5);return 31===t?32+e.readBits(6):t},At=e=>{const t=e.readBits(4);return 15===t?{frequencyIndex:t,sampleRate:e.readBits(24)}:{frequencyIndex:t,sampleRate:t=e.length-2)break;t=r;let n=0;t+3i&&(yield{offset:i,length:t-i}),i=t+n,t=i):t++}-1!==i&&i{if(t.description){const i=3&fe(t.description)[4];return qt(e,i+1)}return Ut(e)},Ht=e=>31&e,Vt=e=>{const t=[],i=e.length;for(let r=0;r{const t=e.reduce((e,t)=>e+jt.byteLength+t.byteLength,0),i=new Uint8Array(t);let r=0;for(const n of e)i.set(jt,r),r+=jt.byteLength,i.set(n,r),r+=n.byteLength;return i},Xt=(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:ze(e,n,s.byteLength);break;case 4:e.setUint32(n,s.byteLength,!1)}n+=t,r.set(s,n),n+=s.byteLength}return r},$t=e=>{try{const t=[],i=[],r=[];for(const o of Ut(e)){const n=e.subarray(o.offset,o.offset+o.length),s=Ht(n[0]);s===Nt.SPS?t.push(n):s===Nt.PPS?i.push(n):s===Nt.SPS_EXT&&r.push(n)}if(0===t.length)return null;if(0===i.length)return null;const n=t[0],s=Jt(n);oe(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 Pt._error("Error building AVC Decoder Configuration Record:",t),null}},Gt=e=>{const t=[];t.push(e.configurationVersion),t.push(e.avcProfileIndication),t.push(e.profileCompatibility),t.push(e.avcLevelIndication),t.push(252|3&e.lengthSizeMinusOne),t.push(224|31&e.sequenceParameterSets.length);for(const i of e.sequenceParameterSets){const e=i.byteLength;t.push(e>>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r>8),t.push(255&e);for(let r=0;r{try{const t=me(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{var t;try{const i=Vt(e),r=new Bt(i);r.skipBits(1),r.skipBits(2);if(7!==r.readBits(5))return null;const n=r.readAlignedByte(),s=r.readAlignedByte(),a=r.readAlignedByte();ue(r);let o=1,l=0,c=0,u=0;if(100===n||110===n||122===n||244===n||44===n||83===n||86===n||118===n||128===n){o=ue(r),3===o&&(u=r.readBits(1)),l=ue(r),c=ue(r),r.skipBits(1);if(r.readBits(1))for(let e=0;e<(3!==o?8:12);e++){if(r.readBits(1)){const t=e<6?16:64;let i=8,n=8;for(let e=0;ee.level>=a))?t:ce(Gi),n=Math.min(Math.floor(r.maxDpbMbs/(e*i)),16);P=n,I=n}else P=0,I=0}return oe(null!==I),{emulationUnpreventedBytes:i,profileIdc:n,constraintFlags:s,levelIdc:a,frameMbsOnlyFlag:y,chromaFormatIdc:o,bitDepthLumaMinus8:l,bitDepthChromaMinus8:c,codedWidth:m,codedHeight:p,displayWidth:g,displayHeight:k,pixelAspectRatio:S,colourPrimaries:b,matrixCoefficients:v,transferCharacteristics:T,fullRangeFlag:w,numReorderFrames:P,maxDecFrameBuffering:I,vuiParametersFlagBitOffset:B,bitstreamRestrictionFlagBitOffset:x,bitstreamRestrictionFlag:C}}catch(i){return Pt._error("Error parsing AVC SPS:",i),null}},Zt=e=>{const t=ue(e);e.skipBits(4),e.skipBits(4);for(let i=0;i<=t;i++)ue(e),ue(e),e.skipBits(1);e.skipBits(5),e.skipBits(5),e.skipBits(5),e.skipBits(5)},ei=e=>{oe(1!==e.bitstreamRestrictionFlag);const t=new Uint8Array(e.emulationUnpreventedBytes.byteLength+64),i=new Bt(e.emulationUnpreventedBytes),r=new Bt(t);null===e.bitstreamRestrictionFlag?(r.copyBits(e.vuiParametersFlagBitOffset,i),r.writeBits(1,1),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0),r.writeBits(1,0)):(oe(null!==e.bitstreamRestrictionFlagBitOffset),r.copyBits(e.bitstreamRestrictionFlagBitOffset,i)),r.writeBits(1,1),r.writeBits(1,1),de(r,2),de(r,1),de(r,16),de(r,16),de(r,e.numReorderFrames),de(r,e.maxDecFrameBuffering),r.writeBits(1,1),r.writeBits((8-r.pos%8)%8,0);const n=r.pos/8;return oe(Number.isInteger(n)),(e=>{const t=[];let i=0;for(const r of e)2===i&&r<=3&&(t.push(3),i=0),t.push(r),i=0===r?i+1:0;return new Uint8Array(t)})(t.subarray(0,n))},ti=(e,t)=>{if(t.description){const i=3&fe(t.description)[21];return qt(e,i+1)}return Ut(e)},ii=e=>e>>1&63,ri=e=>{try{const t=new Bt(Vt(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}=si(t,i);ue(t);const u=ue(t);let d=0;3===u&&(d=t.readBits(1));const h=ue(t),f=ue(t);let m=h,p=f;if(t.readBits(1)){const e=ue(t),i=ue(t),r=ue(t),n=ue(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=ue(t),k=ue(t);ue(t);const y=t.readBits(1);let b=0;for(let e=y?0:i;e<=i;e++)ue(t),b=ue(t),ue(t);ue(t),ue(t),ue(t),ue(t),ue(t),ue(t),t.readBits(1)&&t.readBits(1)&&ai(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&(t.skipBits(4),t.skipBits(4),ue(t),ue(t),t.skipBits(1));const T=ue(t);if(oi(t,T),t.readBits(1)){const e=ue(t);for(let i=0;i{try{const t=[],i=[],r=[],n=[];for(const l of Ut(e)){const s=e.subarray(l.offset,l.offset+l.length),a=ii(s[0]);a===Lt.VPS_NUT?t.push(s):a===Lt.SPS_NUT?i.push(s):a===Lt.PPS_NUT?r.push(s):a!==Lt.PREFIX_SEI_NUT&&a!==Lt.SUFFIX_SEI_NUT||n.push(s)}if(0===i.length||0===r.length)return null;const s=ri(i[0]);if(!s)return null;let a=0;if(r.length>0){const e=r[0],t=new Bt(Vt(e));t.skipBits(16),ue(t),ue(t),t.skipBits(1),t.skipBits(1),t.skipBits(3),t.skipBits(1),t.skipBits(1),ue(t),ue(t),he(t),t.skipBits(1),t.skipBits(1),t.readBits(1)&&ue(t),he(t),he(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:Lt.VPS_NUT,nalUnits:t}]:[],...i.length?[{arrayCompleteness:1,nalUnitType:Lt.SPS_NUT,nalUnits:i}]:[],...r.length?[{arrayCompleteness:1,nalUnitType:Lt.PPS_NUT,nalUnits:r}]:[],...n.length?[{arrayCompleteness:1,nalUnitType:ii(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 Pt._error("Error building HEVC Decoder Configuration Record:",t),null}},si=(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;u0)for(let u=t;u<8;u++)e.skipBits(2);for(let u=0;u{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&&he(e);for(let t=0;t{const i=[];for(let r=0;r{var n;let s=0,a=0,o=0;if(0!==t&&(a=e.readBits(1)),a){if(t===i){o=t-(ue(e)+1)}else o=t-1;e.readBits(1),ue(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=ue(e),i=ue(e);for(let r=0;r{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=Yt[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)&&(ue(e),ue(e)),e.readBits(1),e.readBits(1),e.readBits(1),e.readBits(1)&&(ue(e),ue(e),ue(e),ue(e)),e.readBits(1)&&(e.readBits(32),e.readBits(32),e.readBits(1)&&ue(e),e.readBits(1)&&ui(e,!0,t)),e.readBits(1)&&(e.readBits(1),e.readBits(1),e.readBits(1),a=ue(e),ue(e),ue(e),ue(e),ue(e)),{pixelAspectRatio:o,colourPrimaries:i,transferCharacteristics:r,matrixCoefficients:n,fullRangeFlag:s,minSpatialSegmentationIdc:a}},ui=(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?ue(e):i=1===e.readBits(1);let a=1;if(!i){a=ue(e)+1}r&&di(e,a,s),n&&di(e,a,s)}},di=(e,t,i)=>{for(let r=0;r{const i=new Set;let r=hi.audAllowed;for(const s of ti(e,t)){if(r===hi.noMoreDataAllowed){i.add(s.offset);continue}const t=ii(e[s.offset]);if(r===hi.eoBitstreamAllowed&&37!==t){i.add(s.offset);continue}let n=!1;35===t?r>hi.audAllowed?n=!0:r=hi.beforeFirstVcl:t<=31?r>hi.afterFirstVcl?n=!0:r=hi.afterFirstVcl:36===t?r!==hi.afterFirstVcl?n=!0:r=hi.eoBitstreamAllowed:37===t?r=41&&t<=44||t>=48&&t<=55?r>hi.beforeFirstVcl?n=!0:r=hi.beforeFirstVcl:(38===t||40===t||t>=45&&t<=47||t>=56&&t<=63)&&r{if(t.description){const i=3&fe(t.description)[21];return Xt(e,i+1)}return Kt(e)})(n,t)},pi={1:{colourPrimaries:5,transferCharacteristics:6,matrixCoefficients:5},2:{colourPrimaries:1,transferCharacteristics:1,matrixCoefficients:1},3:{colourPrimaries:6,transferCharacteristics:6,matrixCoefficients:6},4:{colourPrimaries:7,transferCharacteristics:7,matrixCoefficients:7},5:{colourPrimaries:9,transferCharacteristics:14,matrixCoefficients:9},7:{colourPrimaries:1,transferCharacteristics:13,matrixCoefficients:0}},gi=e=>{var t,i,r;const n=new Bt(e);if(2!==n.readBits(2))return null;const s=n.readBits(1),a=(n.readBits(1)<<1)+s;3===a&&n.skipBits(1);if(1===n.readBits(1))return null;if(0!==n.readBits(1))return null;n.skipBits(2);if(4817730!==n.readBits(24))return null;let o=8;if(a>=2){o=n.readBits(1)?12:10}const l=n.readBits(3);let c=0,u=0;if(7!==l){if(u=n.readBits(1),1===a||3===a){const e=n.readBits(1),t=n.readBits(1);c=e||t?e&&!t?2:1:3,n.skipBits(1)}else c=1}else c=3,u=1;const d=(n.readBits(16)+1)*(n.readBits(16)+1);let h=ce(Qi).level;for(const m of Qi)if(d<=m.maxPictureSize){h=m.level;break}const f=pi[l];return{profile:a,level:h,bitDepth:o,chromaSubsampling:c,videoFullRangeFlag:u,colourPrimaries:null!=(t=null==f?void 0:f.colourPrimaries)?t:2,transferCharacteristics:null!=(i=null==f?void 0:f.transferCharacteristics)?i:2,matrixCoefficients:null!=(r=null==f?void 0:f.matrixCoefficients)?r:2}},ki=function*(e){const t=new Bt(e),i=()=>{let e=0;for(let i=0;i<8;i++){const r=t.readAlignedByte();if(e+=(127&r)*q(2,7*i),!(128&r))break;if(7===i&&128&r)return null}return e>q(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);oe(t.pos%8===0),yield{type:r,data:e.subarray(t.pos/8,t.pos/8+a)},t.skipBits(8*a)}},yi=e=>{for(const{type:t,data:i}of ki(e)){if(1!==t)continue;const e=new Bt(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{let t=0;if(e.readBits(1)){e.skipBits(32),e.skipBits(32);if(e.readBits(1)){let t=0;for(;t<32&&!e.readBits(1);)t++;t<32&&e.skipBits(t)}t=e.readBits(1),t&&(o=e.readBits(5),e.skipBits(32),e.skipBits(5),e.skipBits(5))}const i=e.readBits(1),r=e.readBits(5);for(let n=0;n<=r;n++){e.skipBits(12);const r=e.readBits(5);if(0===n&&(s=r),r>7){const t=e.readBits(1);0===n&&(a=t)}if(t){if(e.readBits(1)){const t=o+1;e.skipBits(t),e.skipBits(t),e.skipBits(1)}}if(i){e.readBits(1)&&e.skipBits(4)}}}const 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=2,k=2,y=2;e.readBits(1)&&(g=e.readBits(8),k=e.readBits(8),y=e.readBits(8));let b=0,T=1,v=1,w=0;return p?b=e.readBits(1):1===g&&13===k&&0===y?(b=1,T=0,v=0):(b=e.readBits(1),0===r?(T=1,v=1):1===r?(T=0,v=0):12===m?(T=e.readBits(1),v=T?e.readBits(1):0):(T=1,v=0),T&&v&&(w=e.readBits(2))),{profile:r,level:s,tier:a,bitDepth:m,monochrome:p,chromaSubsamplingX:T,chromaSubsamplingY:v,chromaSamplePosition:w,videoFullRangeFlag:b,colourPrimaries:g,transferCharacteristics:k,matrixCoefficients:y}}return null},bi=e=>{if(e.length<36)return null;const t=me(e);if(1768124518!==t.getUint32(4))return null;return t.getUint16(8)<28?null:{fullRange:!1,colourPrimaries:t.getUint8(22),transferCharacteristics:t.getUint8(23),matrixCoefficients:t.getUint8(24)}},Ti=[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],vi=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;u97;)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}},wi=(e,t,i)=>{switch(e){case"avc":for(const e of Wt(i,t)){const t=i[e.offset],r=Ht(t);if(r>=Nt.NON_IDR_SLICE&&r<=Nt.SLICE_DPC)return"delta";if(r===Nt.IDR)return"key";if(r===Nt.SEI&&!at()){const t=i.subarray(e.offset,e.offset+e.length),r=Vt(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 Bt(r);e.pos=8*n;const t=ue(e),i=e.readBits(1);if(0===t&&1===i)return"key"}n+=t}while(n{var i,r;const n=me(e);let s=0;const a=n.getUint32(s,!0);s+=4;const o=pe.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;c0&&(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=ht(c),i=me(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=pe.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})}}}},xi=[2,1,2,3,3,4,4,5],Ci=e=>{if(e.length<7)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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)}},Bi=[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],Ei=[1,2,3,6],_i=e=>{if(e.length<6)return null;if(11!==e[0]||119!==e[1])return null;const t=new Bt(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=Ei[s];let d;d=n<3?Mt[n]/1e3:Dt[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}]}},Ri=e=>{const t=e.substreams[0];return oe(t),t.fscod<3?Mt[t.fscod]:null!==t.fscod2&&t.fscod2<3?Dt[t.fscod2]:null},Fi=e=>{const t=e.substreams[0];oe(t);let i=xi[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},Ai=[0,8e3,16e3,32e3,0,0,11025,22050,44100,0,0,12e3,24e3,48e3,96e3,192e3],Mi=[32e3,56e3,64e3,96e3,112e3,128e3,192e3,224e3,256e3,32e4,384e3,448e3,512e3,576e3,64e4,768e3,96e4,1024e3,1152e3,128e4,1344e3,1408e3,1411200,1472e3,1536e3,192e4,2048e3,3072e3,384e4,0,0,0],Di=[16,16,20,20,0,24,24,0],Ni=[1,2,2,2,2,3,3,4,4,5,6,6,6,7,8,8],Oi=[1,2,2,2,2,3,18,19,6,7,518,323,83,519,582,535],Li=[32e3,44100,48e3,0],zi=[8e3,16e3,32e3,64e3,128e3,22050,44100,88200,176400,352800,12e3,24e3,48e3,96e3,192e3,384e3],Ui=[512,1024,2048,4096],qi=e=>{const t=Hi(e),i=me(e);let r=t?4*Math.ceil(t.frameSize/4):0,n=null;for(;r+4<=e.length&&1683496997===i.getUint32(r);){const t=Vi(e.subarray(r));if(!t)break;null!=n||(n=t),r+=t.frameSize}if(t)return{frameSize:n?r:t.frameSize,sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,sampleCount:t.sampleCount,channelLayout:t.channelLayout,pcmResolution:t.pcmResolution,bitRate:t.bitRate,core:t,hasExtensions:null!==n};if(!(null==n?void 0:n.asset))return null;const{asset:s}=n;return{frameSize:r,sampleRate:s.sampleRate,numberOfChannels:s.numberOfChannels,sampleCount:s.sampleCount,channelLayout:s.channelLayout,pcmResolution:s.pcmResolution,bitRate:0,core:null,hasExtensions:!0}},Wi=e=>{const t=qi(e);return(null==t?void 0:t.core)?t.hasExtensions?"dtsh":"dtsc":null},Hi=e=>{if(e.length<18)return null;if(127!==e[0]||254!==e[1]||128!==e[2]||1!==e[3])return null;const t=new Bt(e);if(t.skipBits(32),t.skipBits(1),31!==t.readBits(5))return null;const i=t.readBits(1),r=t.readBits(7)+1;if(r%8!==0)return null;const n=t.readBits(14)+1;if(n<96)return null;const s=t.readBits(6);if(s>=Ni.length)return null;const a=Ai[t.readBits(4)];if(0===a)return null;const o=Mi[t.readBits(5)];if(0!==t.readBits(1))return null;t.skipBits(4),t.skipBits(5);const l=t.readBits(2);if(3===l)return null;t.skipBits(1),i&&t.skipBits(16),t.skipBits(7);const c=Di[t.readBits(3)];if(0===c)return null;const u=0!==l;return{frameSize:n,sampleRate:a,numberOfChannels:Ni[s]+(u?1:0),sampleCount:32*r,channelLayout:Oi[s]|(u?8:0),amode:s,lfePresent:u,bitRate:o,pcmResolution:c}},Vi=e=>{if(e.length<10)return null;if(100!==e[0]||88!==e[1]||32!==e[2]||37!==e[3])return null;const t=new Bt(e);t.skipBits(32),t.skipBits(8);const i=t.readBits(2),r=t.readBits(1),n=8+4*r,s=16+4*r;t.skipBits(n);const a=t.readBits(s)+1,o={frameSize:a,asset:null};if(!t.readBits(1))return o;const l=Li[t.readBits(2)],c=512*(t.readBits(3)+1);t.readBits(1)&&t.skipBits(36);const u=t.readBits(3)+1,d=t.readBits(3)+1,h=[];for(let k=0;k2&&t.skipBits(1),p>6&&t.skipBits(1),t.readBits(1))){const e=t.readBits(2)+1<<2;g=t.readBits(e)}return 0===l||t.getBitsLeft()<0?o:{frameSize:a,asset:{sampleRate:m,numberOfChannels:p,sampleCount:Math.round(c*m/l),channelLayout:g,pcmResolution:f}}},ji=e=>Xe(e)+Xe(44646&e),Ki=["avc","hevc","vp9","av1","vp8","prores"],Xi=["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"],$i=["aac","opus","mp3","vorbis","flac","ac3","eac3","dts",...Xi],Gi=[{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}],Qi=[{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}],Yi=".01.01.01.01.00",Ji=".0.110.01.01.01.0",Zi=["ap4x","ap4h","apch","apcn","apcs","apco"],er=["dtsc","dtsh","dtsl","dtse"],tr=e=>{const{codec:t,codecDescription:i,colorSpace:r,avcCodecInfo:n,hevcCodecInfo:s,vp9CodecInfo:a,av1CodecInfo:o,proresFormat:l}=e;if("avc"===t){if(oe(null!==e.avcType),n){const t=new Uint8Array([n.avcProfileIndication,n.profileCompatibility,n.avcLevelIndication]);return`avc${e.avcType}.${Be(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}.${Be(i.subarray(1,4))}`}if("hevc"===t){let e,t,r,n,a,o;if(s)e=s.generalProfileSpace,t=s.generalProfileIdc,r=Ee(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=me(i),l=s.getUint8(1);e=l>>6&3,t=31&l,r=Ee(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=ce(Qi).level;for(const e of Qi)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(Yi)&&(t=t.slice(0,-15)),t}if("av1"===t){if(!o){const t=e.width*e.height;let i=ce(Qi).level;for(const e of Qi)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)?ke[r.primaries]:1,u=(null==r?void 0:r.transfer)?be[r.transfer]:1,d=(null==r?void 0:r.matrix)?ve[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(Ji)&&(f=f.slice(0,-17)),f}if("prores"===t)return null!=l?l:"apch";throw null!==t&&Oe(t),new TypeError(`Unhandled codec '${t}'.`)},ir=e=>{var t,i,r,n,s,a;switch(e.codec){case"avc":{let r=null==(t=e.avcCodecInfo)?void 0:t.sequenceParameterSets[0];if(!r&&e.codecDescription&&(r=null==(i=Qt(e.codecDescription))?void 0:i.sequenceParameterSets[0]),r){const e=Jt(r);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"hevc":{let t=null==(n=null==(r=e.hevcCodecInfo)?void 0:r.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT))?void 0:n.nalUnits[0];if(!t&&e.codecDescription&&(t=null==(a=null==(s=(e=>{try{const t=me(e);let i=0;const r=t.getUint8(i++),n=t.getUint8(i++),s=n>>6&3,a=n>>5&1,o=31&n,l=t.getUint32(i,!1);i+=4;const c=e.subarray(i,i+6);i+=6;const u=t.getUint8(i++),d=(15&t.getUint8(i++))<<8|t.getUint8(i++),h=3&t.getUint8(i++),f=3&t.getUint8(i++),m=7&t.getUint8(i++),p=7&t.getUint8(i++),g=t.getUint16(i,!1);i+=2;const k=t.getUint8(i++),y=k>>6&3,b=k>>3&7,T=k>>2&1,v=3&k,w=t.getUint8(i++),S=[];for(let P=0;P>7&1,s=63&r,a=t.getUint16(i,!1);i+=2;const o=[];for(let l=0;le.nalUnitType===Lt.SPS_NUT))?void 0:a.nalUnits[0]),t){const e=ri(t);if(e)return{primaries:ye[e.colourPrimaries],transfer:Te[e.transferCharacteristics],matrix:we[e.matrixCoefficients],fullRange:!!e.fullRangeFlag}}}break;case"vp8":break;case"vp9":if(e.vp9CodecInfo)return{primaries:ye[e.vp9CodecInfo.colourPrimaries],transfer:Te[e.vp9CodecInfo.transferCharacteristics],matrix:we[e.vp9CodecInfo.matrixCoefficients],fullRange:!!e.vp9CodecInfo.videoFullRangeFlag};break;case"av1":if(e.av1CodecInfo)return{primaries:ye[e.av1CodecInfo.colourPrimaries],transfer:Te[e.av1CodecInfo.transferCharacteristics],matrix:we[e.av1CodecInfo.matrixCoefficients],fullRange:!!e.av1CodecInfo.videoFullRangeFlag};break;case"prores":if(e.proresCodecInfo)return{primaries:ye[e.proresCodecInfo.colourPrimaries],transfer:Te[e.proresCodecInfo.transferCharacteristics],matrix:we[e.proresCodecInfo.matrixCoefficients],fullRange:e.proresCodecInfo.fullRange}}return{primaries:void 0,transfer:void 0,matrix:void 0,fullRange:void 0}},rr=e=>{const{codec:t,codecDescription:i,aacCodecInfo:r,dtsFormat:n}=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=Rt(i).objectType}return`mp4a.40.${e}`}}if("mp3"===t)return"mp3";if("opus"===t)return"opus";if("vorbis"===t)return"vorbis";if("flac"===t)return"flac";if("ac3"===t)return"ac-3";if("eac3"===t)return"ec-3";if("dts"===t)return null!=n?n:"dtsc";if(t&&Xi.includes(t))return t;throw new TypeError(`Unhandled codec '${t}'.`)},nr=48e3,sr=/^pcm-([usf])(\d+)(be)?$/,ar=e=>{if(oe(Xi.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=sr.exec(e);let i;oe(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?q(2,7):0}},or=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":Zi.includes(e)?"prores":"mp3"===e||"mp4a.69"===e||"mp4a.6B"===e||"mp4a.6b"===e||"mp4a.40.34"===e?"mp3":e.startsWith("mp4a.40.")||"mp4a.67"===e?"aac":"opus"===e?"opus":"vorbis"===e?"vorbis":"flac"===e?"flac":"ac-3"===e||"ac3"===e?"ac3":"ec-3"===e||"eac3"===e?"eac3":er.includes(e)?"dts":"ulaw"===e?"ulaw":"alaw"===e?"alaw":sr.test(e)?e:"webvtt"===e?"webvtt":null,lr=[44100,48e3,32e3],cr=[-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],ur=1483304551,dr=1231971951,hr=(e,t)=>3===e?3===t?21:36:3===t?13:21,fr=(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=cr[16*a*4+16*c+(n>>4&15)];if(-1===g)return{header:null,bytesAdvanced:1};const k=1e3*g,y=lr[u]>>a+o,b=((e,t,i,r,n)=>0===t?0:1===t?Math.floor(144*i/(r<>1&1);if(null!==t&&t{let t=2130706432,i=0;for(;0!==t;)i>>=1,i|=e&t,t>>=8;return i};var pr,gr;(gr=pr||(pr={}))[gr.FrameCount=1]="FrameCount",gr[gr.FileSize=2]="FileSize",gr[gr.Toc=4]="Toc";const kr=e=>3===e?1:2;class yr{constructor(e){this.input=e}dispose(){}}const br=new Uint8Array(0);class Tr{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===br&&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===br}get microsecondTimestamp(){return Math.trunc(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*this.duration)}toEncodedVideoChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}alphaToEncodedVideoChunk(e=this.type){if(!this.sideData.alpha)throw new TypeError("This packet does not contain alpha side data.");if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to a video chunk.");if("undefined"===typeof EncodedVideoChunk)throw new Error("EncodedVideoChunk is not available in this environment.");return new EncodedVideoChunk({data:this.sideData.alpha,type:e,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}toEncodedAudioChunk(){if(this.isMetadataOnly)throw new TypeError("Metadata-only packets cannot be converted to an audio chunk.");if("undefined"===typeof EncodedAudioChunk)throw new Error("EncodedAudioChunk is not available in this environment.");return new EncodedAudioChunk({data:this.data,type:this.type,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration})}static fromEncodedChunk(e,t){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 Tr(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 Tr(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 vr=e=>{const t=me(e);let i=0;const r=t.getUint8(i);i+=1,i+=3;const n=Be(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;te.systemId===t.systemId&&((e,t)=>{if(e.length!==t.length)return!1;for(let i=0;i{let t=Cl(e);const i=Nl(e,4);let r=8;1===t&&(t=Rl(e),r=16);const n=t-r;return n<0?null:{name:i,totalSize:t,headerSize:r,contentSize:n}},Pr=e=>El(e)/65536,Ir=e=>El(e)/1073741824,xr=e=>{let t=0;for(let i=0;i<4;i++){t<<=7;const i=vl(e);if(t|=127&i,0===(128&i))break}return t},Cr=e=>{let t=Sl(e);return e.skip(2),t=Math.min(t,e.remainingLength),pe.decode(Tl(e,t))},Br=e=>{const t=Sr(e);if(!t||"data"!==t.name)return null;if(e.remainingLength<8)return null;const i=Cl(e);e.skip(4);const r=Tl(e,t.contentSize-8);switch(i){case 1:return pe.decode(r);case 2:return new TextDecoder("utf-16be").decode(r);case 13:return new It(r,"image/jpeg");case 14:return new It(r,"image/png");case 27:return new It(r,"image/bmp");default:return r}},Er=16,_r=new Uint32Array(256),Rr=new Uint32Array(256),Fr=new Uint32Array(256),Ar=new Uint32Array(256),Mr=new Uint32Array(256),Dr=new Uint32Array(256),Nr=new Uint32Array(10);let Or=!1;class Lr{constructor(){this.roundkey=new Uint32Array(44),this.iv=new Uint32Array(Er/Uint32Array.BYTES_PER_ELEMENT),this.in=new Uint8Array(Er),this.out=new Uint8Array(Er),this.inView=new DataView(this.in.buffer),this.outView=new DataView(this.out.buffer)}init({key:e,iv:t}){oe(16===e.byteLength),oe(16===t.byteLength),Or||(()=>{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);_r[s]=t<<24|t<<16|t<<8|t,Dr[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);Rr[s]=n,Fr[s]=n>>>8|n<<24,Ar[s]=n>>>16|n<<16,Mr[s]=n>>>24|n<<8}let n=1;for(let s=0;s<10;s++)Nr[s]=n<<24,n=n<<1^(128&n?283:0);Or=!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&_r[e>>>16&255]^16711680&_r[e>>>8&255]^65280&_r[e>>>0&255]^255&_r[e>>>24&255]^Nr[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>>24&255]]^Fr[255&_r[t>>>16&255]]^Ar[255&_r[t>>>8&255]]^Mr[255&_r[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=Rr[e>>>24]^Fr[r>>>16&255]^Ar[i>>>8&255]^Mr[255&t]^this.roundkey[n],c=Rr[t>>>24]^Fr[e>>>16&255]^Ar[r>>>8&255]^Mr[255&i]^this.roundkey[n+1],u=Rr[i>>>24]^Fr[t>>>16&255]^Ar[e>>>8&255]^Mr[255&r]^this.roundkey[n+2],d=Rr[r>>>24]^Fr[i>>>16&255]^Ar[t>>>8&255]^Mr[255&e]^this.roundkey[n+3],e=l,t=c,i=u,r=d}const h=4278190080&Dr[e>>>24&255]^16711680&Dr[r>>>16&255]^65280&Dr[i>>>8&255]^255&Dr[t>>>0&255]^this.roundkey[40],f=4278190080&Dr[t>>>24&255]^16711680&Dr[e>>>16&255]^65280&Dr[r>>>8&255]^255&Dr[i>>>0&255]^this.roundkey[41],m=4278190080&Dr[i>>>24&255]^16711680&Dr[t>>>16&255]^65280&Dr[e>>>8&255]^255&Dr[r>>>0&255]^this.roundkey[42],p=4278190080&Dr[r>>>24&255]^16711680&Dr[i>>>16&255]^65280&Dr[t>>>8&255]^255&Dr[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 zr extends yr{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 Y(this,null,function*(){return yield this.readMetadata(),this.tracks.map(e=>e.trackBacking)})}getMimeType(){return Y(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 Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}readMetadata(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0,t=!1,i=!1;for(;;){let r=this.reader.requestSliceRange(e,8,16);if(ct(r)&&(r=yield r),!r)break;const n=e,s=Sr(r);if(!s)break;if("ftyp"===s.name||"styp"===s.name){const e=Nl(r,4);this.isQuickTime="qt "===e}else{if("moov"===s.name){let e=this.reader.requestSlice(r.filePos,s.contentSize);if(ct(e)&&(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>n+s.totalSize,i=!0;break}if("moof"===s.name){if(!this.input._initInput)throw new Error('"moof" box encountered with no "moov" box present; this file is likely a Segment as described in ISO/IEC 14496-12 Section 8.16. A separate init file that contains a "moov" box is required to read this file, please provide it using InputOptions.initInput.');yield this.copyMetadataFromInitInput(this.input._initInput),t=!1,i=!0;break}}e=n+s.totalSize}if(!i&&this.input._initInput&&(yield this.copyMetadataFromInitInput(this.input._initInput)),t){oe(null!==this.reader.fileSize);let e=this.reader.requestSlice(this.reader.fileSize-4,4);ct(e)&&(e=yield e),oe(e);const t=Cl(e),i=this.reader.fileSize-t;if(i>=0&&i<=this.reader.fileSize-16){let e=this.reader.requestSliceRange(i,8,16);if(ct(e)&&(e=yield e),e){const t=Sr(e);if(t&&"mfra"===t.name){let i=this.reader.requestSlice(e.filePos,t.contentSize);ct(i)&&(i=yield i),i&&this.readContiguousBoxes(i)}}}}}))()}copyMetadataFromInitInput(e){return Y(this,null,function*(){const t=yield e._getDemuxer();if(t.constructor!==zr)throw new Error("Init input must match the input's format.");yield t.readMetadata(),this.movieTimescale=t.movieTimescale,this.movieDurationInTimescale=t.movieDurationInTimescale,this.metadataTags=t.metadataTags,this.isFragmented=!0,this.fragmentTrackDefaults=t.fragmentTrackDefaults,this.psshBoxes=t.psshBoxes;for(const e of t.tracks){const t={id:e.id,demuxer:this,trackBacking:null,disposition:e.disposition,timescale:e.timescale,durationInMediaTimescale:e.durationInMediaTimescale,durationInMovieTimescale:e.durationInMovieTimescale,rotation:e.rotation,internalCodecId:e.internalCodecId,name:e.name,languageCode:e.languageCode,sampleTableByteOffset:null,sampleTable:null,fragmentLookupTable:[],currentFragmentState:null,fragmentPositionCache:[],editListPreviousSegmentDurations:e.editListPreviousSegmentDurations,editListOffset:e.editListOffset,encryptionInfo:e.encryptionInfo,encryptionAuxInfo:null,frmaCodecString:null,info:e.info};if(e.trackBacking)if(oe(t.info),"video"===t.info.type&&-1!==t.info.width){const e=t;t.trackBacking=new qr(e),this.tracks.push(t)}else if("audio"===t.info.type&&-1!==t.info.numberOfChannels){const e=t;t.trackBacking=new Wr(e),this.tracks.push(t)}}})}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;oe(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&&Xi.includes(e.info.codec)&&0===r.sampleCompositionTimeOffsets.length){oe("audio"===(null==(i=e.info)?void 0:i.type));const t=ar(e.info.codec),n=[],s=[];for(let i=0;ie.startIndex),u=r.sampleTimingEntries[c],d=Re(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=ce(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;te.presentationTimestamp-t.presentationTimestamp),r.presentationTimestampIndexMap=Array(r.presentationTimestamps.length).fill(-1);for(let e=0;ee.moofOffset===s.moofOffset);if(r)Xr(e,r.timestamp);else{const t=Re(i,s.moofOffset-1,e=>e.moofOffset);if(-1!==t){const r=i[t];Xr(e,r.endTimestamp)}}e.startTimestampIsFinal=!0}const r=Re(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 Yr(this.reader,t.encryptionInfo,e.encryptionAuxInfo);for(let t=0;t0){t.languageCode="";for(let e=0;e<3;e++)t.languageCode=String.fromCharCode(96+(31&r))+t.languageCode,r>>=5;Ge(t.languageCode)||(t.languageCode=We)}}break;case"hdlr":{const t=this.currentTrack;if(!t)break;e.skip(8);const i=Nl(e,4);"vide"===i?t.info={type:"video",width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,codec:null,codecDescription:null,colorSpace:H({},Pe),avcType:null,avcCodecInfo:null,hevcCodecInfo:null,vp9CodecInfo:null,av1CodecInfo:null,proresCodecInfo:null,proresFormat:null}:"soun"===i&&(t.info={type:"audio",numberOfChannels:-1,sampleRate:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null,pcmLittleEndian:!1,pcmSampleSize:null})}break;case"stbl":{const t=this.currentTrack;if(!t)break;t.sampleTableByteOffset=re,this.readContiguousBoxes(e.slice(se,ne.contentSize))}break;case"stsd":{const t=this.currentTrack;if(!t)break;if(null===t.info||t.sampleTable)break;const i=vl(e);e.skip(3);const r=Cl(e);for(let n=0;n0&&(1===a?(e.skip(4),l=8*Cl(e),e.skip(8)):2===a&&(e.skip(4),c=Dl(e),o=Cl(e),e.skip(4),l=Cl(e),u=Cl(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=nr;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(er.includes(d))t.info.codec="dts",t.info.dtsFormat=d;else if("twos"===d)8===l?t.info.codec="pcm-s8":16===l?t.info.codec=t.info.pcmLittleEndian?"pcm-s16":"pcm-s16be":(Pt._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":(Pt._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":(Pt._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":(Pt._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":(Pt._warn(`Invalid fpcm sample size ${e}.`),t.info.codec=null):32===e?t.info.codec="pcm-f32be":64===e?t.info.codec="pcm-f64be":(Pt._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<0?(t.encryptionInfo.defaultCryptByteBlock=r>>4,t.encryptionInfo.defaultSkipByteBlock=15&r):(t.encryptionInfo.defaultCryptByteBlock=0,t.encryptionInfo.defaultSkipByteBlock=0),t.encryptionInfo.defaultIsProtected=0!==vl(e),t.encryptionInfo.defaultPerSampleIvSize=vl(e),t.encryptionInfo.defaultKid=Be(Tl(e,16)),t.encryptionInfo.defaultIsProtected&&0===t.encryptionInfo.defaultPerSampleIvSize){const i=vl(e),r=new Uint8Array(16);r.set(Tl(e,i),0),t.encryptionInfo.defaultConstantIv=r}}break;case"avcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"hvcC":{const t=this.currentTrack;if(!t)break;if(oe(t.info),0===ne.contentSize)break;t.info.codecDescription=Tl(e,ne.contentSize)}break;case"vpcC":{const i=this.currentTrack;if(!i)break;oe("video"===(null==(t=i.info)?void 0:t.type)),e.skip(4);const r=vl(e),n=vl(e),s=vl(e),a=s>>4,o=s>>1&7,l=1&s,c=vl(e),u=vl(e),d=vl(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;oe("video"===(null==(i=t.info)?void 0:i.type)),e.skip(1);const o=vl(e),l=o>>5,c=31&o,u=vl(e),d=u>>7,h=u>>6&1,f=u>>4&1,m=u>>3&1,p=u>>2&1,g=3&u,k=2===l&&h?u>>5&1?12:10:h?10:8;e.skip(1);const y=Tl(e,ne.contentSize-4),b=yi(y);t.info.av1CodecInfo={profile:l,level:c,tier:d,bitDepth:k,monochrome:f,chromaSubsamplingX:m,chromaSubsamplingY:p,chromaSamplePosition:g,videoFullRangeFlag:null!=(r=null==b?void 0:b.videoFullRangeFlag)?r:0,colourPrimaries:null!=(n=null==b?void 0:b.colourPrimaries)?n:2,transferCharacteristics:null!=(s=null==b?void 0:b.transferCharacteristics)?s:2,matrixCoefficients:null!=(a=null==b?void 0:b.matrixCoefficients)?a:2}}break;case"colr":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(o=t.info)?void 0:o.type));const i=Nl(e,4);if("nclx"!==i&&"nclc"!==i)break;const r=Sl(e),n=Sl(e),s=Sl(e);let a;"nclx"===i&&(a=Boolean(128&vl(e))),t.info.colorSpace={primaries:ye[r],transfer:Te[n],matrix:we[s],fullRange:a}}break;case"pasp":{const t=this.currentTrack;if(!t)break;oe("video"===(null==(l=t.info)?void 0:l.type));const i=Cl(e),r=Cl(e);i>0&&r>0&&(i>r?t.info.squarePixelWidth=Math.round(t.info.width*i/r):t.info.squarePixelHeight=Math.round(t.info.height*r/i))}break;case"esds":{const t=this.currentTrack;if(!t||"audio"!==(null==(c=t.info)?void 0:c.type))break;e.skip(4);oe(3===vl(e)),xr(e),e.skip(2);const i=vl(e),r=0!==(64&i),n=0!==(32&i);if(0!==(128&i)&&e.skip(2),r){const t=vl(e);e.skip(t)}n&&e.skip(2);oe(4===vl(e));const s=xr(e),a=e.filePos,o=vl(e);if(64===o||103===o?(t.info.codec="aac",t.info.aacCodecInfo={isMpeg2:103===o,objectType:null}):105===o||107===o?t.info.codec="mp3":221===o?t.info.codec="vorbis":169===o?t.info.codec="dts":Pt._warn(`Unsupported audio codec (objectTypeIndication ${o}) - discarding track.`),e.skip(12),s>e.filePos-a){oe(5===vl(e));const i=xr(e);if(t.info.codecDescription=Tl(e,i),"aac"===t.info.codec){const e=Rt(t.info.codecDescription);null!==e.outputNumberOfChannels&&(t.info.numberOfChannels=e.outputNumberOfChannels),null!==e.outputSampleRate&&(t.info.sampleRate=e.outputSampleRate)}}}break;case"enda":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(u=t.info)?void 0:u.type)),t.info.pcmLittleEndian=!!(255&Sl(e))}break;case"pcmC":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(d=t.info)?void 0:d.type)),e.skip(4);const i=vl(e);t.info.pcmLittleEndian=Boolean(1&i),t.info.pcmSampleSize=vl(e)}break;case"dOps":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(h=t.info)?void 0:h.type)),e.skip(1);const i=vl(e),r=Sl(e),n=Cl(e),s=Il(e),a=vl(e);let o;o=0!==a?Tl(e,2+i):new Uint8Array(0);const l=new Uint8Array(19+o.byteLength),c=new DataView(l.buffer);c.setUint32(0,1332770163,!1),c.setUint32(4,1214603620,!1),c.setUint8(8,1),c.setUint8(9,i),c.setUint16(10,r,!0),c.setUint32(12,n,!0),c.setInt16(16,s,!0),c.setUint8(18,a),l.set(o,19),t.info.codecDescription=l,t.info.numberOfChannels=i}break;case"dfLa":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(f=t.info)?void 0:f.type)),e.skip(4);const i=127,r=128,n=e.filePos;for(;e.filePos>>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=Tl(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;oe("audio"===(null==(m=t.info)?void 0:m.type));const i=Tl(e,3),r=new Bt(i),n=r.readBits(2);r.skipBits(8);const s=r.readBits(3),a=r.readBits(1);n<3&&(t.info.sampleRate=Mt[n]),t.info.numberOfChannels=xi[s]+a}break;case"dec3":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(p=t.info)?void 0:p.type));const i=(e=>{if(e.length<2)return null;const t=new Bt(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}})(Tl(e,ne.contentSize));if(!i){Pt._warn("Invalid dec3 box contents, ignoring.");break}const r=Ri(i);null!==r&&(t.info.sampleRate=r),t.info.numberOfChannels=Fi(i)}break;case"ddts":{const t=this.currentTrack;if(!t)break;oe("audio"===(null==(g=t.info)?void 0:g.type));const i=(e=>{if(e.length<20)return null;const t=me(e),i=t.getUint32(0);if(0===i)return null;const r=new Bt(e);r.seekToByte(13);const n=r.readBits(2);r.skipBits(5);const s=r.readBits(1),a=r.readBits(6);r.skipBits(14),r.skipBits(1),r.skipBits(3);const o=r.readBits(16);let l=null;return 0!==o?l=ji(o):ae.id===i);if(!r)break;const n=Cl(e),s=(12&n)>>2,a=3&n,o=[vl,Sl,Pl,Cl],l=o[(48&n)>>4],c=o[s],u=o[a],d=Cl(e);for(let h=0;he.timestamp-t.timestamp);for(let e=0;e({presentationTimestamp:e.presentationTimestamp,sampleIndex:t})).sort((e,t)=>e.presentationTimestamp-t.presentationTimestamp);for(let n=0;ne.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!=(y=null==d?void 0:d.defaultSampleDescriptionIndex)?y:null,defaultSampleDuration:null!=(b=null==d?void 0:d.defaultSampleDuration)?b:null,defaultSampleSize:null!=(T=null==d?void 0:d.defaultSampleSize)?T:null,defaultSampleFlags:null!=(v=null==d?void 0:d.defaultSampleFlags)?v:null,startTimestamp:null,encryptionAuxInfo:null},i?u.currentFragmentState.baseDataOffset=Rl(e):l&&(u.currentFragmentState.baseDataOffset=this.currentFragment.moofOffset),r&&(u.currentFragmentState.sampleDescriptionIndex=Cl(e)),n&&(u.currentFragmentState.defaultSampleDuration=Cl(e)),s&&(u.currentFragmentState.defaultSampleSize=Cl(e)),a&&(u.currentFragmentState.defaultSampleFlags=Cl(e)),o&&(u.currentFragmentState.defaultSampleDuration=0)}break;case"tfdt":{const t=this.currentTrack;if(!t)break;oe(t.currentFragmentState);const i=vl(e);e.skip(3);const r=0===i?Cl(e):Rl(e);t.currentFragmentState.startTimestamp=r}break;case"trun":{const t=this.currentTrack;if(!t)break;oe(this.currentFragment),oe(t.currentFragmentState);const i=vl(e),r=Pl(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=Cl(e);let d=null;n&&(d=El(e));let h,f=null;s&&(f=Cl(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));for(let m=0;m0&&(n=Tl(e,r));const s=Qr(t);s.defaultSampleInfoSize=i,s.sampleSizes=n,s.sampleCount=r}break;case"saio":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;const i=vl(e);if(1&Pl(e)){const i=Nl(e,4),r=Cl(e);if(i!==t.encryptionInfo.scheme||0!==r)break}const r=Cl(e);if(0===r)break;r>1&&Pt._warn("Multiple saio entries are not supported; using the first offset only.");let n=0===i?Cl(e):Number(Rl(e));this.currentFragment&&(n+=this.currentFragment.moofOffset);Qr(t).offset=n}break;case"senc":{const t=this.currentTrack;if(!t||!t.encryptionInfo)break;oe(this.currentFragment);const i=this.currentFragment.trackData.get(t.id);if(!i)break;e.skip(1);const r=Pl(e),n=Boolean(2&r),s=Cl(e),a=t.encryptionInfo.defaultPerSampleIvSize;oe(null!==a);for(let o=0;o0?r.set(Tl(e,a),0):r.set(t.encryptionInfo.defaultConstantIv,0);let s=null;if(n){const t=Sl(e);s=[];for(let i=0;i0&&(null!=(Y=this.metadataTags).trackNumber||(Y.trackNumber=t)),i&&Number.isInteger(i)&&i>0&&(null!=(J=this.metadataTags).tracksTotal||(J.tracksTotal=i))}break;case"trkn":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(Z=this.metadataTags).trackNumber||(Z.trackNumber=t)),i>0&&(null!=(ee=this.metadataTags).tracksTotal||(ee.tracksTotal=i))}break;case"disc":case"disk":if(n instanceof Uint8Array&&n.length>=6){const e=me(n),t=e.getUint16(2,!1),i=e.getUint16(4,!1);t>0&&(null!=(te=this.metadataTags).discNumber||(te.discNumber=t)),i>0&&(null!=(ie=this.metadataTags).discsTotal||(ie.discsTotal=i))}}}}}return e.filePos=ae,!0}}class Ur{constructor(e){this.internalTrack=e,this.packetToSampleIndex=new WeakMap,this.packetToFragmentLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.tracks)if(r.trackBacking.getType()===t&&i++,r===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.internalCodecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.timescale}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){var e;const t=this.internalTrack;if(t.durationInMediaTimescale<=0)return null;oe(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 Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.timescale)+this.internalTrack.editListOffset}getPacket(e,t){return Y(this,null,function*(){const i=this.mapTimestampIntoTimescale(e),r=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),n=Hr(r,i),s=yield this.fetchPacketForSampleIndex(n,t);return Gr(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=Re(t.presentationTimestamps,i,e=>e.presentationTimestamp);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{if(e===r.fragment){const t=e.trackData.get(this.internalTrack.id);if(r.sampleIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{sampleIndex:-1,correctSampleFound:!1};const r=Ne(t.presentationTimestamps,e=>t.samples[e.sampleIndex].isKeyFrame&&e.presentationTimestamp<=i);return{sampleIndex:-1!==r?t.presentationTimestamps[r].sampleIndex:-1,correctSampleFound:-1!==r&&i{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 oe(-1!==e),{sampleIndex:e,correctSampleFound:!0}}}return{sampleIndex:-1,correctSampleFound:!1}},-1/0,1/0,t)})}fetchPacketForSampleIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.internalTrack.demuxer.getSampleTableForTrack(this.internalTrack),r=jr(i,e);if(!r)return null;let n;if(t.metadataOnly)n=br;else{let t=this.internalTrack.demuxer.reader.requestSlice(r.sampleOffset,r.sampleSize);if(ct(t)&&(t=yield t),!t)return null;if(n=Tl(t,r.sampleSize),this.internalTrack.encryptionInfo){let t=null;if(this.internalTrack.encryptionAuxInfo){const i=yield Yr(this.internalTrack.demuxer.reader,this.internalTrack.encryptionInfo,this.internalTrack.encryptionAuxInfo);ee.timestamp),f=-1!==h?this.internalTrack.fragmentLookupTable[h]:null,m=Re(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(ct(e)&&(e=yield e),!e)break;const i=k,s=Sr(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.moofOffsetY(this,null,function*(){var e,t,i,r,n,s,a;if("avc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("hevc"!==this.internalTrack.info.codec||this.internalTrack.info.codecDescription)if("vp9"!==this.internalTrack.info.codec||this.internalTrack.info.vp9CodecInfo&&(2!==(a=this.internalTrack.info.vp9CodecInfo).colourPrimaries||2!==a.transferCharacteristics||2!==a.matrixCoefficients))if("av1"!==this.internalTrack.info.codec||this.internalTrack.info.av1CodecInfo&&(e=>2!==e.colourPrimaries||2!==e.transferCharacteristics||2!==e.matrixCoefficients)(this.internalTrack.info.av1CodecInfo)){if("prores"===this.internalTrack.info.codec&&!this.internalTrack.info.proresCodecInfo){const e=yield this.getFirstPacket({});this.internalTrack.info.proresCodecInfo=e&&bi(e.data)}}else{const e=yield this.getFirstPacket({}),t=e&&yi(e.data);t&&(this.internalTrack.info.av1CodecInfo=t)}else{const t=yield this.getFirstPacket({}),i=t&&gi(t.data);i&&(this.internalTrack.info.vp9CodecInfo=V(H({},null!=(e=this.internalTrack.info.vp9CodecInfo)?e:i),{videoFullRangeFlag:i.videoFullRangeFlag,colourPrimaries:i.colourPrimaries,transferCharacteristics:i.transferCharacteristics,matrixCoefficients:i.matrixCoefficients}))}else{const e=yield this.getFirstPacket({});this.internalTrack.info.hevcCodecInfo=e&&ni(e.data)}else{const e=yield this.getFirstPacket({});this.internalTrack.info.avcCodecInfo=e&&$t(e.data)}if(!Se(this.internalTrack.info.colorSpace)){const e=ir(this.internalTrack.info);null!=(t=this.internalTrack.info.colorSpace).primaries||(t.primaries=e.primaries),null!=(i=this.internalTrack.info.colorSpace).transfer||(i.transfer=e.transfer),null!=(r=this.internalTrack.info.colorSpace).matrix||(r.matrix=e.matrix),null!=(n=this.internalTrack.info.colorSpace).fullRange||(n.fullRange=e.fullRange)}const o={codec:tr(this.internalTrack.info),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(s=this.internalTrack.info.codecDescription)?s:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Wr extends Ur{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr(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 Hr=(e,t)=>{if(e.presentationTimestamps){const i=Re(e.presentationTimestamps,t,e=>e.presentationTimestamp);return-1===i?-1:e.presentationTimestamps[i].sampleIndex}{const i=Re(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)}},Vr=(e,t)=>{var i;if(!e.keySampleIndices)return Hr(e,t);if(e.presentationTimestamps){const i=Re(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!==_e(e.keySampleIndices,i,e=>e))return i}return-1}{const r=Hr(e,t),n=Re(e.keySampleIndices,r,e=>e);return null!=(i=e.keySampleIndices[n])?i:-1}},jr=(e,t)=>{const i=Re(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=Re(e.sampleCompositionTimeOffsets,t,e=>e.startIndex),a=e.sampleCompositionTimeOffsets[s];a&&t-a.startIndexe.startSampleIndex),c=e.sampleToChunk[l];oe(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;ge)}},Kr=(e,t)=>{var i;if(!e.keySampleIndices)return t+1;const r=Re(e.keySampleIndices,t,e=>e);return null!=(i=e.keySampleIndices[r+1])?i:-1},Xr=(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},$r=e=>{const[t,i]=e,r=Math.atan2(i,t);return Number.isFinite(r)?r*(180/Math.PI):0},Gr=e=>0===e.sampleSizes.length,Qr=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}},Yr=(e,t,i)=>Y(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{oe(i.sampleSizes);for(let e=0;e0?i.defaultSampleInfoSize:i.sampleSizes[e],o=new Uint8Array(16);s>0?o.set(Tl(n,s),0):o.set(t.defaultConstantIv,0);let l=null;if(r>s){const e=Sl(n);l=[];for(let t=0;te.defaultConstantIv?{iv:e.defaultConstantIv,subsamples:null}:null,Zr=(e,t,i,r)=>Y(null,null,function*(){var n;oe(e.encryptionInfo);const s=e.encryptionInfo;oe(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=Y(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{oe(e.length%2===0);const t=new Uint8Array(e.length/2);for(let i=0;iY(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=>Y(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);oe(null!==t.defaultCryptByteBlock&&null!==t.defaultSkipByteBlock);const o=rn(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 d=yield a(c),h=new Uint8Array(r);let f=0;for(const e of o)for(const t of e.perSubsample)h.set(d.subarray(f,f+t.length),t.offset),f+=t.length;return h}),tn=(e,t,i,r)=>{const n=new Lr;n.init({key:e,iv:i.iv});const s=t.defaultCryptByteBlock,a=t.defaultSkipByteBlock;if(oe(null!==s&&null!==a),!i.subsamples){const e=new Uint8Array(r),t=Math.floor(r.length/16);for(let i=0;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 nn,sn;(sn=nn||(nn={}))[sn.EBML=440786851]="EBML",sn[sn.EBMLVersion=17030]="EBMLVersion",sn[sn.EBMLReadVersion=17143]="EBMLReadVersion",sn[sn.EBMLMaxIDLength=17138]="EBMLMaxIDLength",sn[sn.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",sn[sn.DocType=17026]="DocType",sn[sn.DocTypeVersion=17031]="DocTypeVersion",sn[sn.DocTypeReadVersion=17029]="DocTypeReadVersion",sn[sn.Void=236]="Void",sn[sn.Segment=408125543]="Segment",sn[sn.SeekHead=290298740]="SeekHead",sn[sn.Seek=19899]="Seek",sn[sn.SeekID=21419]="SeekID",sn[sn.SeekPosition=21420]="SeekPosition",sn[sn.Duration=17545]="Duration",sn[sn.Info=357149030]="Info",sn[sn.TimestampScale=2807729]="TimestampScale",sn[sn.MuxingApp=19840]="MuxingApp",sn[sn.WritingApp=22337]="WritingApp",sn[sn.Tracks=374648427]="Tracks",sn[sn.TrackEntry=174]="TrackEntry",sn[sn.TrackNumber=215]="TrackNumber",sn[sn.TrackUID=29637]="TrackUID",sn[sn.TrackType=131]="TrackType",sn[sn.FlagEnabled=185]="FlagEnabled",sn[sn.FlagDefault=136]="FlagDefault",sn[sn.FlagForced=21930]="FlagForced",sn[sn.FlagOriginal=21934]="FlagOriginal",sn[sn.FlagHearingImpaired=21931]="FlagHearingImpaired",sn[sn.FlagVisualImpaired=21932]="FlagVisualImpaired",sn[sn.FlagCommentary=21935]="FlagCommentary",sn[sn.FlagLacing=156]="FlagLacing",sn[sn.Name=21358]="Name",sn[sn.Language=2274716]="Language",sn[sn.LanguageBCP47=2274717]="LanguageBCP47",sn[sn.CodecID=134]="CodecID",sn[sn.CodecPrivate=25506]="CodecPrivate",sn[sn.CodecDelay=22186]="CodecDelay",sn[sn.SeekPreRoll=22203]="SeekPreRoll",sn[sn.DefaultDuration=2352003]="DefaultDuration",sn[sn.Video=224]="Video",sn[sn.PixelWidth=176]="PixelWidth",sn[sn.PixelHeight=186]="PixelHeight",sn[sn.DisplayWidth=21680]="DisplayWidth",sn[sn.DisplayHeight=21690]="DisplayHeight",sn[sn.DisplayUnit=21682]="DisplayUnit",sn[sn.AlphaMode=21440]="AlphaMode",sn[sn.Audio=225]="Audio",sn[sn.SamplingFrequency=181]="SamplingFrequency",sn[sn.Channels=159]="Channels",sn[sn.BitDepth=25188]="BitDepth",sn[sn.SimpleBlock=163]="SimpleBlock",sn[sn.BlockGroup=160]="BlockGroup",sn[sn.Block=161]="Block",sn[sn.BlockAdditions=30113]="BlockAdditions",sn[sn.BlockMore=166]="BlockMore",sn[sn.BlockAdditional=165]="BlockAdditional",sn[sn.BlockAddID=238]="BlockAddID",sn[sn.BlockDuration=155]="BlockDuration",sn[sn.ReferenceBlock=251]="ReferenceBlock",sn[sn.Cluster=524531317]="Cluster",sn[sn.Timestamp=231]="Timestamp",sn[sn.Cues=475249515]="Cues",sn[sn.CuePoint=187]="CuePoint",sn[sn.CueTime=179]="CueTime",sn[sn.CueTrackPositions=183]="CueTrackPositions",sn[sn.CueTrack=247]="CueTrack",sn[sn.CueClusterPosition=241]="CueClusterPosition",sn[sn.Colour=21936]="Colour",sn[sn.MatrixCoefficients=21937]="MatrixCoefficients",sn[sn.TransferCharacteristics=21946]="TransferCharacteristics",sn[sn.Primaries=21947]="Primaries",sn[sn.Range=21945]="Range",sn[sn.Projection=30320]="Projection",sn[sn.ProjectionType=30321]="ProjectionType",sn[sn.ProjectionPoseRoll=30325]="ProjectionPoseRoll",sn[sn.Attachments=423732329]="Attachments",sn[sn.AttachedFile=24999]="AttachedFile",sn[sn.FileDescription=18046]="FileDescription",sn[sn.FileName=18030]="FileName",sn[sn.FileMediaType=18016]="FileMediaType",sn[sn.FileData=18012]="FileData",sn[sn.FileUID=18094]="FileUID",sn[sn.Chapters=272869232]="Chapters",sn[sn.Tags=307544935]="Tags",sn[sn.Tag=29555]="Tag",sn[sn.Targets=25536]="Targets",sn[sn.TargetTypeValue=26826]="TargetTypeValue",sn[sn.TargetType=25546]="TargetType",sn[sn.TagTrackUID=25541]="TagTrackUID",sn[sn.TagEditionUID=25545]="TagEditionUID",sn[sn.TagChapterUID=25540]="TagChapterUID",sn[sn.TagAttachmentUID=25542]="TagAttachmentUID",sn[sn.SimpleTag=26568]="SimpleTag",sn[sn.TagName=17827]="TagName",sn[sn.TagLanguage=17530]="TagLanguage",sn[sn.TagString=17543]="TagString",sn[sn.TagBinary=17541]="TagBinary",sn[sn.ContentEncodings=28032]="ContentEncodings",sn[sn.ContentEncoding=25152]="ContentEncoding",sn[sn.ContentEncodingOrder=20529]="ContentEncodingOrder",sn[sn.ContentEncodingScope=20530]="ContentEncodingScope",sn[sn.ContentCompression=20532]="ContentCompression",sn[sn.ContentCompAlgo=16980]="ContentCompAlgo",sn[sn.ContentCompSettings=16981]="ContentCompSettings",sn[sn.ContentEncryption=20533]="ContentEncryption";const an=[nn.EBML,nn.Segment],on=[nn.SeekHead,nn.Info,nn.Cluster,nn.Tracks,nn.Cues,nn.Attachments,nn.Chapters,nn.Tags],ln=[...an,...on],cn=16,un=e=>{if(e.remainingLength<1)return null;const t=vl(e);if(e.skip(-1),0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;return e.remainingLength{if(e.remainingLength<1)return null;const t=vl(e);if(0===t)return null;let i=1,r=128;for(;0===(t&r);)i++,r>>=1;if(e.remainingLength{if(t<1||t>8)throw new Error("Bad unsigned int size "+t);let i=0;for(let r=0;r{const t=un(e);if(null===t)return null;if(e.remainingLength{if(e.remainingLength<1)return null;if(255===vl(e))return;e.skip(-1);const t=dn(e);return null===t?null:72057594037927940!==t?t:void 0},pn=e=>{oe(e.remainingLength>=2);const t=fn(e);if(null===t)return null;const i=mn(e);return null===i?null:{id:t,size:i}},gn=(e,t)=>{const i=Tl(e,t);let r=0;for(;r{const i=Tl(e,t);let r=0;for(;r{if(0===t)return 0;if(4!==t&&8!==t)throw new Error("Bad float size "+t);return 4===t?Ml(e):Dl(e)},bn=(e,t,i,r)=>Y(null,null,function*(){const n=new Set(i);let s=t;for(;null===r||ss?r:s,found:!1}}),Tn=(e,t,i,r)=>Y(null,null,function*(){const n=q(2,16),s=new Set(i);let a=t;for(;ae.tracks.map(e=>e.trackBacking))})}getMimeType(){return Y(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 Y(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=H(H({},e),t.metadataTags);return e})}readMetadata(){var e;return null!=(e=this.readMetadataPromise)?e:this.readMetadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,2,cn);if(ct(t)&&(t=yield t),!t)break;const i=pn(t);if(!i)break;const r=i.id;let n=i.size;const s=t.filePos;if(r===nn.EBML){Dn(n);let e=this.reader.requestSlice(s,n);if(ct(e)&&(e=yield e),!e)break;this.readContiguousElements(e)}else if(r===nn.Segment){if(yield this.readSegment(s,n),void 0===n)break;if(null===this.reader.fileSize)break}else if(r===nn.Cluster){if(null===this.reader.fileSize)break;if(void 0===n){n=(yield bn(this.reader,s,ln,this.reader.fileSize)).pos-s}const e=ce(this.segments);e&&(e.elementEndPos=s+n)}Dn(n),e=s+n}}))()}readSegment(e,t){return Y(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||re.id===s);if(-1!==l){const e=Wn[l].flag;this.currentSegment[e]=!0,Dn(a);let t=this.reader.requestSlice(o,a);ct(t)&&(t=yield t),t&&this.readContiguousElements(t)}else if(s===nn.Tags||s===nn.Attachments){s===nn.Tags?this.currentSegment.tagsSeen=!0:this.currentSegment.attachmentsSeen=!0,Dn(a);let e=this.reader.requestSlice(o,a);ct(e)&&(e=yield e),e&&this.readContiguousElements(e)}else if(s===nn.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=Wn.find(e=>e.id===t.id);if(!i)continue;if(this.currentSegment[i.flag])continue;let r=this.reader.requestSliceRange(e+t.segmentPosition,2,cn);if(ct(r)&&(r=yield r),!r)continue;const n=pn(r);if(!n)continue;const{id:s,size:a}=n;if(s!==i.id)continue;Dn(a),this.currentSegment[i.flag]=!0;let o=this.reader.requestSlice(r.filePos,a);ct(o)&&(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;ta&&(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 Y(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,cn);ct(r)&&(r=yield r),oe(r);const n=e,s=pn(r);oe(s);oe(s.id===nn.Cluster);let a=s.size;const o=r.filePos;if(void 0===a){a=(yield bn(this.reader,o,ln,t.elementEndPos)).pos-o}let l=this.reader.requestSlice(o,a);ct(l)&&(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,ln);c.elementEndPos=e}for(const[,e]of c.trackData){const t=e.track;oe(e.blocks.length>0);let i=!1;for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp);for(let n=0;n({timestamp:e.timestamp,blockIndex:t})).sort((e,t)=>e.timestamp-t.timestamp));const r=e.blocks[e.presentationTimestamps[0].blockIndex],s=e.blocks[ce(e.presentationTimestamps).blockIndex];e.startTimestamp=r.timestamp,e.endTimestamp=s.timestamp+s.duration;const a=Re(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=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,c,u,d,h,f,m,p,g,k,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F,A,M,D,N,O,L,z,U,q,W,j,K,X,$,G,Q,Y,J,Z,ee;const te=pn(e);if(!te)return!1;if(t&&t.includes(te.id))return!1;const{id:ie,size:re}=te,ne=e.filePos;switch(Dn(re),ie){case nn.DocType:this.isWebM="webm"===gn(e,re);break;case nn.Seek:{if(!this.currentSegment)break;const t={id:-1,segmentPosition:-1};this.currentSegment.seekEntries.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.id&&-1!==t.segmentPosition||this.currentSegment.seekEntries.pop()}break;case nn.SeekID:{const t=null==(i=this.currentSegment)?void 0:i.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.id=hn(e,re)}break;case nn.SeekPosition:{const t=null==(r=this.currentSegment)?void 0:r.seekEntries[this.currentSegment.seekEntries.length-1];if(!t)break;t.segmentPosition=hn(e,re)}break;case nn.TimestampScale:if(!this.currentSegment)break;this.currentSegment.timestampScale=hn(e,re),this.currentSegment.timestampFactor=1e9/this.currentSegment.timestampScale;break;case nn.Duration:if(!this.currentSegment)break;this.currentSegment.duration=yn(e,re);break;case nn.TrackEntry:if(!this.currentSegment)break;if(this.currentTrack={id:-1,segment:this.currentSegment,demuxer:this,clusterPositionCache:[],cuePoints:[],disposition:V(H({},Ct),{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(ne,re)),!this.currentTrack)break;if(this.currentTrack.decodingInstructions.some(e=>{var t;return"decompress"!==(null==(t=e.data)?void 0:t.type)||e.scope!==Ln.Block||e.data.algorithm!==Un.HeaderStripping})&&(Pt._warn(`Track #${this.currentTrack.id} has an unsupported content encoding; dropping.`),this.currentTrack=null),this.currentTrack&&-1!==this.currentTrack.id&&this.currentTrack.codecId&&this.currentTrack.info){const e=this.currentTrack.codecId.indexOf("/"),t=-1===e?this.currentTrack.codecId:this.currentTrack.codecId.slice(0,e);if("video"===this.currentTrack.info.type&&-1!==this.currentTrack.info.width&&-1!==this.currentTrack.info.height){if(this.currentTrack.info.squarePixelWidth=this.currentTrack.info.width,this.currentTrack.info.squarePixelHeight=this.currentTrack.info.height,null!==this.currentTrack.info.displayWidth&&null!==this.currentTrack.info.displayHeight){const e=this.currentTrack.info.displayWidth*this.currentTrack.info.height,t=this.currentTrack.info.displayHeight*this.currentTrack.info.width;e>0&&t>0&&(e>t?this.currentTrack.info.squarePixelWidth=Math.round(this.currentTrack.info.width*e/t):this.currentTrack.info.squarePixelHeight=Math.round(this.currentTrack.info.height*t/e))}if(this.currentTrack.codecId===vn)this.currentTrack.info.codec="avc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(this.currentTrack.codecId===wn)this.currentTrack.info.codec="hevc",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate;else if(t===Sn)this.currentTrack.info.codec="vp8";else if(t===Pn)this.currentTrack.info.codec="vp9";else if(t===In)this.currentTrack.info.codec="av1";else if(t===xn){const e=this.currentTrack.codecPrivate?pe.decode(this.currentTrack.codecPrivate):"";Zi.includes(e)&&(this.currentTrack.info.codec="prores",this.currentTrack.info.proresFormat=e)}const e=this.currentTrack;this.currentTrack.trackBacking=new Kn(e),this.currentSegment.tracks.push(this.currentTrack)}else if("audio"===this.currentTrack.info.type){t===Cn?(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===Bn?this.currentTrack.info.codec="mp3":t===En?(this.currentTrack.info.codec="opus",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate,this.currentTrack.info.sampleRate=nr):t===_n?(this.currentTrack.info.codec="vorbis",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Rn?(this.currentTrack.info.codec="flac",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Fn?(this.currentTrack.info.codec="ac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===An?(this.currentTrack.info.codec="eac3",this.currentTrack.info.codecDescription=this.currentTrack.codecPrivate):t===Mn?(this.currentTrack.info.codec="dts","A_DTS/EXPRESS"===this.currentTrack.codecId?this.currentTrack.info.dtsFormat="dtse":"A_DTS/LOSSLESS"===this.currentTrack.codecId&&(this.currentTrack.info.dtsFormat="dtsl")):"A_PCM/INT/LIT"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32"):"A_PCM/INT/BIG"===this.currentTrack.codecId?8===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-u8":16===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s16be":24===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-s24be":32===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-s32be"):"A_PCM/FLOAT/IEEE"===this.currentTrack.codecId&&(32===this.currentTrack.info.bitDepth?this.currentTrack.info.codec="pcm-f32":64===this.currentTrack.info.bitDepth&&(this.currentTrack.info.codec="pcm-f64"));const e=this.currentTrack;this.currentTrack.trackBacking=new Xn(e),this.currentSegment.tracks.push(this.currentTrack)}}this.currentTrack=null;break;case nn.TrackNumber:if(!this.currentTrack)break;this.currentTrack.id=hn(e,re);break;case nn.TrackType:{if(!this.currentTrack)break;const t=hn(e,re);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:H({},Pe),alphaMode:!1,proresFormat:null}:2===t&&(this.currentTrack.info={type:"audio",numberOfChannels:1,sampleRate:8e3,bitDepth:-1,codec:null,codecDescription:null,aacCodecInfo:null,dtsFormat:null})}break;case nn.FlagEnabled:if(!this.currentTrack)break;hn(e,re)||(this.currentTrack=null);break;case nn.FlagDefault:if(!this.currentTrack)break;this.currentTrack.disposition.default=!!hn(e,re);break;case nn.FlagForced:if(!this.currentTrack)break;this.currentTrack.disposition.forced=!!hn(e,re);break;case nn.FlagOriginal:if(!this.currentTrack)break;this.currentTrack.disposition.original=!!hn(e,re);break;case nn.FlagHearingImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.hearingImpaired=!!hn(e,re);break;case nn.FlagVisualImpaired:if(!this.currentTrack)break;this.currentTrack.disposition.visuallyImpaired=!!hn(e,re);break;case nn.FlagCommentary:if(!this.currentTrack)break;this.currentTrack.disposition.commentary=!!hn(e,re);break;case nn.CodecID:if(!this.currentTrack)break;this.currentTrack.codecId=gn(e,re);break;case nn.CodecPrivate:if(!this.currentTrack)break;this.currentTrack.codecPrivate=Tl(e,re);break;case nn.DefaultDuration:if(!this.currentTrack)break;this.currentTrack.defaultDurationNs=hn(e,re);break;case nn.Name:if(!this.currentTrack)break;this.currentTrack.name=kn(e,re);break;case nn.Language:if(!this.currentTrack)break;if(this.currentTrack.hasLanguageBcp47)break;this.currentTrack.languageCode=gn(e,re),Ge(this.currentTrack.languageCode)||(this.currentTrack.languageCode=We);break;case nn.LanguageBCP47:{if(!this.currentTrack)break;const t=gn(e,re).split("-")[0];this.currentTrack.languageCode=t||We,this.currentTrack.hasLanguageBcp47=!0}break;case nn.Video:if("video"!==(null==(s=null==(n=this.currentTrack)?void 0:n.info)?void 0:s.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.PixelWidth:if("video"!==(null==(o=null==(a=this.currentTrack)?void 0:a.info)?void 0:o.type))break;this.currentTrack.info.width=hn(e,re);break;case nn.PixelHeight:if("video"!==(null==(c=null==(l=this.currentTrack)?void 0:l.info)?void 0:c.type))break;this.currentTrack.info.height=hn(e,re);break;case nn.DisplayWidth:if("video"!==(null==(d=null==(u=this.currentTrack)?void 0:u.info)?void 0:d.type))break;this.currentTrack.info.displayWidth=hn(e,re);break;case nn.DisplayHeight:if("video"!==(null==(f=null==(h=this.currentTrack)?void 0:h.info)?void 0:f.type))break;this.currentTrack.info.displayHeight=hn(e,re);break;case nn.DisplayUnit:if("video"!==(null==(p=null==(m=this.currentTrack)?void 0:m.info)?void 0:p.type))break;this.currentTrack.info.displayUnit=hn(e,re);break;case nn.AlphaMode:if("video"!==(null==(k=null==(g=this.currentTrack)?void 0:g.info)?void 0:k.type))break;this.currentTrack.info.alphaMode=1===hn(e,re);break;case nn.Colour:if("video"!==(null==(b=null==(y=this.currentTrack)?void 0:y.info)?void 0:b.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.MatrixCoefficients:{if("video"!==(null==(v=null==(T=this.currentTrack)?void 0:T.info)?void 0:v.type))break;const t=hn(e,re),i=we[t];this.currentTrack.info.colorSpace.matrix=i}break;case nn.Range:{if("video"!==(null==(S=null==(w=this.currentTrack)?void 0:w.info)?void 0:S.type))break;const t=hn(e,re);this.currentTrack.info.colorSpace.fullRange=1===t||2===t?2===t:void 0}break;case nn.TransferCharacteristics:{if("video"!==(null==(I=null==(P=this.currentTrack)?void 0:P.info)?void 0:I.type))break;const t=hn(e,re),i=Te[t];this.currentTrack.info.colorSpace.transfer=i}break;case nn.Primaries:{if("video"!==(null==(C=null==(x=this.currentTrack)?void 0:x.info)?void 0:C.type))break;const t=hn(e,re),i=ye[t];this.currentTrack.info.colorSpace.primaries=i}break;case nn.Projection:if("video"!==(null==(E=null==(B=this.currentTrack)?void 0:B.info)?void 0:E.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.ProjectionPoseRoll:{if("video"!==(null==(R=null==(_=this.currentTrack)?void 0:_.info)?void 0:R.type))break;const t=-yn(e,re);try{this.currentTrack.info.rotation=le(t)}catch(se){}}break;case nn.Audio:if("audio"!==(null==(A=null==(F=this.currentTrack)?void 0:F.info)?void 0:A.type))break;this.readContiguousElements(e.slice(ne,re));break;case nn.SamplingFrequency:if("audio"!==(null==(D=null==(M=this.currentTrack)?void 0:M.info)?void 0:D.type))break;this.currentTrack.info.sampleRate=yn(e,re);break;case nn.Channels:if("audio"!==(null==(O=null==(N=this.currentTrack)?void 0:N.info)?void 0:O.type))break;this.currentTrack.info.numberOfChannels=hn(e,re);break;case nn.BitDepth:if("audio"!==(null==(z=null==(L=this.currentTrack)?void 0:L.info)?void 0:z.type))break;this.currentTrack.info.bitDepth=hn(e,re);break;case nn.CuePoint:if(!this.currentSegment)break;this.readContiguousElements(e.slice(ne,re)),this.currentCueTime=null;break;case nn.CueTime:this.currentCueTime=hn(e,re);break;case nn.CueTrackPositions:{if(null===this.currentCueTime)break;oe(this.currentSegment);const t={time:this.currentCueTime,trackId:-1,clusterPosition:-1};this.currentSegment.cuePoints.push(t),this.readContiguousElements(e.slice(ne,re)),-1!==t.trackId&&-1!==t.clusterPosition||this.currentSegment.cuePoints.pop()}break;case nn.CueTrack:{const t=null==(U=this.currentSegment)?void 0:U.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;t.trackId=hn(e,re)}break;case nn.CueClusterPosition:{const t=null==(q=this.currentSegment)?void 0:q.cuePoints[this.currentSegment.cuePoints.length-1];if(!t)break;oe(this.currentSegment),t.clusterPosition=this.currentSegment.dataStartPos+hn(e,re)}break;case nn.Timestamp:if(!this.currentCluster)break;this.currentCluster.timestamp=hn(e,re);break;case nn.SimpleBlock:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e),s=n>>1&3;let a=!!(128&n);"audio"===(null==(W=i.track.info)?void 0:W.type)&&i.track.info.codec&&(a=!0);const o=Tl(e,re-(e.filePos-ne)),l=i.track.decodingInstructions.length>0;i.blocks.push({timestamp:r,duration:0,isKeyFrame:a,data:o,lacing:s,decoded:!l,postProcessed:!1,mainAdditional:null})}break;case nn.BlockGroup:if(!this.currentCluster)break;this.readContiguousElements(e.slice(ne,re)),this.currentBlock=null;break;case nn.Block:{if(!this.currentCluster)break;const t=dn(e);if(null===t)break;const i=this.getTrackDataInCluster(this.currentCluster,t);if(!i)break;const r=Il(e),n=vl(e)>>1&3,s=Tl(e,re-(e.filePos-ne)),a=i.track.decodingInstructions.length>0;this.currentBlock={timestamp:r,duration:0,isKeyFrame:!0,data:s,lacing:n,decoded:!a,postProcessed:!1,mainAdditional:null},i.blocks.push(this.currentBlock)}break;case nn.BlockAdditions:this.readContiguousElements(e.slice(ne,re));break;case nn.BlockMore:if(!this.currentBlock)break;this.currentBlockAdditional={addId:1,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentBlockAdditional.data&&1===this.currentBlockAdditional.addId&&(this.currentBlock.mainAdditional=this.currentBlockAdditional.data),this.currentBlockAdditional=null;break;case nn.BlockAdditional:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.data=Tl(e,re);break;case nn.BlockAddID:if(!this.currentBlockAdditional)break;this.currentBlockAdditional.addId=hn(e,re);break;case nn.BlockDuration:if(!this.currentBlock)break;this.currentBlock.duration=hn(e,re);break;case nn.ReferenceBlock:if(!this.currentBlock)break;this.currentBlock.isKeyFrame=!1;break;case nn.Tag:this.currentTagTargetIsMovie=!0,this.readContiguousElements(e.slice(ne,re));break;case nn.Targets:this.readContiguousElements(e.slice(ne,re));break;case nn.TargetTypeValue:50!==hn(e,re)&&(this.currentTagTargetIsMovie=!1);break;case nn.TagTrackUID:case nn.TagEditionUID:case nn.TagChapterUID:case nn.TagAttachmentUID:this.currentTagTargetIsMovie=!1;break;case nn.SimpleTag:if(!this.currentTagTargetIsMovie)break;this.currentSimpleTagName=null,this.readContiguousElements(e.slice(ne,re));break;case nn.TagName:this.currentSimpleTagName=kn(e,re);break;case nn.TagString:{if(!this.currentSimpleTagName)break;const t=kn(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.TagBinary:{if(!this.currentSimpleTagName)break;const t=Tl(e,re);this.processTagValue(this.currentSimpleTagName,t)}break;case nn.AttachedFile:{if(!this.currentSegment)break;this.currentAttachedFile={fileUid:null,fileName:null,fileMediaType:null,fileData:null,fileDescription:null},this.readContiguousElements(e.slice(ne,re));const t=this.currentSegment.metadataTags;if(this.currentAttachedFile.fileUid&&this.currentAttachedFile.fileData&&(null!=t.raw||(t.raw={}),t.raw[this.currentAttachedFile.fileUid.toString()]=new xt(this.currentAttachedFile.fileData,null!=(j=this.currentAttachedFile.fileMediaType)?j:void 0,null!=(K=this.currentAttachedFile.fileName)?K:void 0,null!=(X=this.currentAttachedFile.fileDescription)?X:void 0)),(null==($=this.currentAttachedFile.fileMediaType)?void 0:$.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!=(G=this.currentAttachedFile.fileName)?G:void 0,description:null!=(Q=this.currentAttachedFile.fileDescription)?Q:void 0})}this.currentAttachedFile=null}break;case nn.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;rt.order-e.order);break;case nn.ContentEncoding:this.currentDecodingInstruction={order:0,scope:Ln.Block,data:null},this.readContiguousElements(e.slice(ne,re)),this.currentDecodingInstruction.data&&this.currentTrack.decodingInstructions.push(this.currentDecodingInstruction),this.currentDecodingInstruction=null;break;case nn.ContentEncodingOrder:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.order=hn(e,re);break;case nn.ContentEncodingScope:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.scope=hn(e,re);break;case nn.ContentCompression:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decompress",algorithm:Un.Zlib,settings:null},this.readContiguousElements(e.slice(ne,re));break;case nn.ContentCompAlgo:if("decompress"!==(null==(J=null==(Y=this.currentDecodingInstruction)?void 0:Y.data)?void 0:J.type))break;this.currentDecodingInstruction.data.algorithm=hn(e,re);break;case nn.ContentCompSettings:if("decompress"!==(null==(ee=null==(Z=this.currentDecodingInstruction)?void 0:Z.data)?void 0:ee.type))break;this.currentDecodingInstruction.data.settings=Tl(e,re);break;case nn.ContentEncryption:if(!this.currentDecodingInstruction)break;this.currentDecodingInstruction.data={type:"decrypt"}}return e.filePos=ne+re,!0}decodeBlockData(e,t){oe(e.decodingInstructions.length>0);let i=t;for(const r of e.decodingInstructions)if(oe(r.data),"decompress"===r.data.type)if(r.data.algorithm===Un.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))}}}getDurationFromMetadata(e){return Y(this,null,function*(){if(e.duration<=0)return null;let t=null;for(const r of e.tracks){oe(r.trackBacking);const e=yield r.trackBacking.getFirstPacket({metadataOnly:!0});e&&(t=Math.min(null!=t?t:1/0,e.timestamp))}let i=e.duration/e.timestampFactor;return i+=null!=t?t:0,i})}}class jn{constructor(e){this.internalTrack=e,this.packetToClusterLocation=new WeakMap}getId(){return this.internalTrack.id}getNumber(){const e=this.internalTrack.demuxer,t=this.internalTrack.trackBacking.getType();let i=0;for(const r of e.segments)for(const e of r.tracks)if(e.trackBacking.getType()===t&&i++,e===this.internalTrack)break;return i}getCodec(){throw new Error("Not implemented on base class.")}getInternalCodecId(){return this.internalTrack.codecId}getName(){return this.internalTrack.name}getLanguageCode(){return this.internalTrack.languageCode}getTimeResolution(){return this.internalTrack.segment.timestampFactor}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getDisposition(){return this.internalTrack.disposition}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return this.internalTrack.demuxer.getDurationFromMetadata(this.internalTrack.segment)})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getFirstPacket(e){return Y(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 He(e*this.internalTrack.segment.timestampFactor)}getPacket(e,t){return Y(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=Re(t.presentationTimestamps,i,e=>e.timestamp);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{if(e===i.cluster){const t=e.trackData.get(this.internalTrack.id);if(i.blockIndex+1{const t=e.trackData.get(this.internalTrack.id);if(!t)return{blockIndex:-1,correctBlockFound:!1};const r=Ne(t.presentationTimestamps,e=>t.blocks[e.blockIndex].isKeyFrame&&e.timestamp<=i);return{blockIndex:-1!==r?t.presentationTimestamps[r].blockIndex:-1,correctBlockFound:-1!==r&&i{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 oe(-1!==e),{blockIndex:e,correctBlockFound:!0}}}return{blockIndex:-1,correctBlockFound:!1}},-1/0,1/0,t)})}fetchPacketInCluster(e,t,i){return Y(this,null,function*(){var r,n;if(-1===t)return null;const s=e.trackData.get(this.internalTrack.id).blocks[t];if(oe(s),s.decoded||(s.data=this.internalTrack.demuxer.decodeBlockData(this.internalTrack,s.data),s.decoded=!0),!s.postProcessed){if("prores"===(null==(r=this.internalTrack.info)?void 0:r.codec)){if(!(s.data.length>=8&&105===s.data[4]&&99===s.data[5]&&112===s.data[6]&&102===s.data[7])){const e=new Uint8Array(s.data.length+8);me(e).setUint32(0,e.length,!1),e[4]=105,e[5]=99,e[6]=112,e[7]=102,e.set(s.data,8),s.data=e}}s.postProcessed=!0}const a=i.metadataOnly?br:s.data,o=s.timestamp/this.internalTrack.segment.timestampFactor,l=s.duration/this.internalTrack.segment.timestampFactor,c={};s.mainAdditional&&"video"===(null==(n=this.internalTrack.info)?void 0:n.type)&&this.internalTrack.info.alphaMode&&(c.alpha=i.metadataOnly?br:s.mainAdditional,c.alphaByteLength=s.mainAdditional.byteLength);const u=new Tr(a,s.isKeyFrame?"key":"delta",o,l,e.dataStartPos+t,s.data.byteLength,c);return this.packetToClusterLocation.set(u,{cluster:e,blockIndex:t}),u})}performClusterLookup(e,t,i,r,n){return Y(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=Re(this.internalTrack.cuePoints,i,e=>e.time),p=-1!==m?this.internalTrack.cuePoints[m]:null,g=Re(this.internalTrack.clusterPositionCache,i,e=>e.startTimestamp),k=-1!==g?this.internalTrack.clusterPositionCache[g]:null,y=Math.max(null!=(s=null==p?void 0:p.clusterPosition)?s:0,null!=(a=null==k?void 0:k.elementStartPos)?a:0)||null;let b;for(e?null===y||e.elementStartPos>=y?(b=e.elementEndPos,d=e):b=y:b=null!=y?y:u.clusterSeekStartPos;null===u.elementEndPos||b<=u.elementEndPos-2;){if(d){const e=d.trackData.get(this.internalTrack.id);if(e&&e.startTimestamp>r)break}let e=c.reader.requestSliceRange(b,2,cn);if(ct(e)&&(e=yield e),!e)break;const i=b,s=pn(e);if(!s||!on.includes(s.id)&&s.id!==nn.Void){const e=yield Tn(c.reader,i,on,Math.min(null!=(o=u.elementEndPos)?o:1/0,i+Hn));if(e){b=e;continue}break}const a=s.id;let l=s.size;const m=e.filePos;if(a===nn.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){oe(a!==nn.Cluster);l=(yield bn(c.reader,m,ln,u.elementEndPos)).pos-m}const p=m+l;if(null===u.elementEndPos){let e=c.reader.requestSliceRange(p,2,cn);if(ct(e)&&(e=yield e),!e)break;if(fn(e)===nn.Segment){u.elementEndPos=p;break}}b=p}if(p&&(!h||h.elementStartPosY(this,null,function*(){var e,t,i,r,n;let s=null;("vp9"===this.internalTrack.info.codec||"av1"===this.internalTrack.info.codec||"prores"===this.internalTrack.info.codec||"avc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription||"hevc"===this.internalTrack.info.codec&&!this.internalTrack.info.codecDescription)&&(s=yield this.getFirstPacket({}));const a={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&&s?$t(s.data):null,hevcCodecInfo:"hevc"===this.internalTrack.info.codec&&s?ni(s.data):null,vp9CodecInfo:"vp9"===this.internalTrack.info.codec&&s?gi(s.data):null,av1CodecInfo:"av1"===this.internalTrack.info.codec&&s?yi(s.data):null,proresCodecInfo:"prores"===this.internalTrack.info.codec&&s?bi(s.data):null,proresFormat:this.internalTrack.info.proresFormat};if(!Se(this.internalTrack.info.colorSpace)){const n=ir(a);null!=(e=this.internalTrack.info.colorSpace).primaries||(e.primaries=n.primaries),null!=(t=this.internalTrack.info.colorSpace).transfer||(t.transfer=n.transfer),null!=(i=this.internalTrack.info.colorSpace).matrix||(i.matrix=n.matrix),null!=(r=this.internalTrack.info.colorSpace).fullRange||(r.fullRange=n.fullRange)}const o={codec:tr(a),codedWidth:this.internalTrack.info.width,codedHeight:this.internalTrack.info.height,description:null!=(n=this.internalTrack.info.codecDescription)?n:void 0,colorSpace:this.internalTrack.info.colorSpace};return this.internalTrack.info.width===this.internalTrack.info.squarePixelWidth&&this.internalTrack.info.height===this.internalTrack.info.squarePixelHeight||(o.displayAspectWidth=this.internalTrack.info.squarePixelWidth,o.displayAspectHeight=this.internalTrack.info.squarePixelHeight),o}))():null})}}class Xn extends jn{constructor(e){super(e),this.decoderConfigPromise=null,this.internalTrack=e}getType(){return"audio"}getCodec(){return this.internalTrack.info.codec}getNumberOfChannels(){return this.internalTrack.info.numberOfChannels}getSampleRate(){return this.internalTrack.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){var e;return this.internalTrack.info.codec?null!=(e=this.decoderConfigPromise)?e:this.decoderConfigPromise=(()=>Y(this,null,function*(){var e;if("dts"===this.internalTrack.info.codec&&!this.internalTrack.info.dtsFormat){const e=yield this.getFirstPacket({});this.internalTrack.info.dtsFormat=e&&Wi(e.data)}return{codec:rr({codec:this.internalTrack.info.codec,codecDescription:this.internalTrack.info.codecDescription,aacCodecInfo:this.internalTrack.info.aacCodecInfo,dtsFormat:this.internalTrack.info.dtsFormat}),numberOfChannels:this.internalTrack.info.numberOfChannels,sampleRate:this.internalTrack.info.sampleRate,description:null!=(e=this.internalTrack.info.codecDescription)?e:void 0}}))():null})}}const $n=(e,t,i,r=null)=>Y(null,null,function*(){const n=q(2,16);let s=t;for(;null===i||s=4;){const t=a.filePos,i=Cl(a),n=null!==e.fileSize?e.fileSize-s:null,o=fr(i,n);if(o.header&&(!r||o.header.sampleRate===r.sampleRate&&o.header.mpegVersionId===r.mpegVersionId&&o.header.layer===r.layer&&kr(o.header.channel)===kr(r.channel)))return{header:o.header,startPos:s};a.filePos=t+o.bytesAdvanced,s=a.filePos}}return null});class Gn extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.firstFrameHeaderPos=null,this.xingFrameHeader=null,this.xingFrameHeaderPos=null,this.loadedSamples=[],this.metadataTags=null,this.xingData=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();if(!this.firstFrameHeader&&this.xingFrameHeader&&(this.firstFrameHeader=this.xingFrameHeader,this.firstFrameHeaderPos=this.xingFrameHeaderPos),!this.firstFrameHeader)throw new Error("No valid MP3 frame found.");this.trackBackings=[new Qn(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}const e=yield $n(this.reader,this.lastLoadedPos,this.reader.fileSize,this.firstFrameHeader);if(!e)return void(this.lastSampleLoaded=!0);const t=e.header;this.lastLoadedPos=e.startPos+t.totalSize-1;const i=hr(t.mpegVersionId,t.channel);let r=this.reader.requestSlice(e.startPos+i,4);if(ct(r)&&(r=yield r),r){const n=Cl(r);if(n===ur||n===dr){if(this.xingFrameHeader||(this.xingFrameHeader=t,this.xingFrameHeaderPos=e.startPos),!this.xingData){let t=this.reader.requestSlice(e.startPos+i+4,12);if(ct(t)&&(t=yield t),t){const e=Tl(t,12),i=me(e),r=i.getUint32(0,!1);this.xingData={frameCount:r&pr.FrameCount?i.getUint32(4,!1):null,fileSize:r&pr.FileSize?i.getUint32(8,!1):null}}}return}}this.firstFrameHeader||(this.firstFrameHeader=t,this.firstFrameHeaderPos=e.startPos);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 Y(this,null,function*(){return"audio/mpeg"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=!0;let n=this.reader.requestSlice(i.filePos,r.size);if(ct(n)&&(n=yield n),!n)break;$l(n,r,this.metadataTags),e=i.filePos+r.size}if(!t&&null!==this.reader.fileSize&&this.reader.fileSize>=Wl){let e=this.reader.requestSlice(this.reader.fileSize-Wl,Wl);ct(e)&&(e=yield e),oe(e);"TAG"===Nl(e,3)&&jl(e,this.metadataTags)}return this.metadataTags}finally{e()}})}}class Qn{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.sampleRate/this.demuxer.firstFrameHeader.audioSamplesInFrame}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){const e=this.demuxer;if(oe(null!==e.firstFrameHeader),oe(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<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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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>>0&4294967295}const Zn=e=>{const t=me(e),i=t.getUint32(22,!0);t.setUint32(22,0,!0);let r=0;for(let n=0;n>>24^t])>>>0}return t.setUint32(22,i,!0),r},es=(e,t,i)=>{let r=0,n=null;if(e.length>0)if("vorbis"===t.codec){oe(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,i=3&e[0];let r;return r=0===i?1:1===i||2===i?2:63&e[1],{durationInSamples:Ti[t]*r}})(e).durationInSamples}return{durationInSamples:r,vorbisBlockSize:n}},ts=27,is=282,rs=e=>{const t=e.filePos;if(Bl(e)!==Yn)return null;e.skip(1);const i=vl(e),r=Al(e),n=Bl(e),s=Bl(e),a=Bl(e),o=vl(e),l=new Uint8Array(o);for(let d=0;de+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}},ns=(e,t)=>{for(;e.filePos>>8&255)===i||(t>>>16&255)===i||(t>>>24&255)===i){if(e.skip(-4),t===Yn)return!0;e.skip(1)}}return!1};class ss extends yr{constructor(e){super(e),this.metadataPromise=null,this.bitstreams=[],this.trackBackings=[],this.metadataTags={},this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=0;for(;;){let t=this.reader.requestSliceRange(e,ts,is);if(ct(t)&&(t=yield t),!t)break;const i=rs(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 as(t,this)))}}))()})}readVorbisMetadata(e,t){return Y(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=me(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:vi(n.data).modeBlockflags},Ii(r.data.subarray(7),this.metadataTags)})}readOpusMetadata(e,t){return Y(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=me(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=nr,t.codecInfo.opusInfo={preSkip:n.preSkip},Ii(r.data.subarray(8),this.metadataTags)})}readPacket(e,t){return Y(this,null,function*(){oe(te+t.length,0);if(0===o)return null;const l=new Uint8Array(o);let c=0;for(let e=0;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 Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}class as{constructor(e,t){this.bitstream=e,this.demuxer=t,this.encodedPacketToMetadata=new WeakMap,this.sequentialScanCache=[],this.sequentialScanMutex=new xe,this.internalSampleRate="opus"===e.codecInfo.codec?nr:e.sampleRate}getType(){return"audio"}getId(){return this.bitstream.serialNumber}getNumber(){const e=this.demuxer.trackBackings.findIndex(e=>e.bitstream===this.bitstream);return oe(-1!==e),e+1}getNumberOfChannels(){return this.bitstream.numberOfChannels}getSampleRate(){return this.bitstream.sampleRate}getTimeResolution(){return this.bitstream.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getCodec(){return this.bitstream.codecInfo.codec}getInternalCodecId(){return null}getDecoderConfig(){return Y(this,null,function*(){var e;return oe(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 We}getDisposition(){return V(H({},Ct),{primary:!1})}granulePositionToTimestampInSamples(e){return"opus"===this.bitstream.codecInfo.codec?(oe(this.bitstream.codecInfo.opusInfo),e-this.bitstream.codecInfo.opusInfo.preSkip):e}createEncodedPacketFromOggPacket(e,t,i){if(!e)return null;const{durationInSamples:r,vorbisBlockSize:n}=es(e.data,this.bitstream.codecInfo,t.vorbisLastBlocksize),s=new Tr(i.metadataOnly?br: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 Y(this,null,function*(){oe(this.bitstream.lastMetadataPacket);const t=yield this.demuxer.findNextPacketStart(this.bitstream.lastMetadataPacket);if(!t)return null;let i=0;"opus"===this.bitstream.codecInfo.codec&&(oe(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 Y(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 Y(this,null,function*(){var i,r;if(null===this.demuxer.reader.fileSize)return this.getPacketSequential(e,t);const n=He(e*this.internalSampleRate);if(0===n)return this.getFirstPacket(t);if(n<0)return null;oe(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.totalSizen?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,ts,is);ct(t)&&(t=yield t),oe(t);const i=rs(t);oe(i),u=i,u.serialNumber===this.bitstream.serialNumber&&d.push(u)}oe(-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:br,endPage:p,endSegmentIndex:g};if(yield this.demuxer.findNextPacketStart(e)){const e=ls(d,u,m);oe(e);const t=os(d,e.page,e.segmentIndex);t&&(u=t.page,m=t.segmentIndex)}else for(;;){const e=ls(d,u,m);if(!e)break;const t=os(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,y=null;for(;null!==u;){oe(null!==m);const e=yield this.demuxer.readPacket(u,m);if(!e)break;if(!(u.headerStartPos===s.startPage.headerStartPos&&mn||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 Y(this,null,function*(){const i=yield this.sequentialScanMutex.acquire();try{const i=He(e*this.internalSampleRate);e=i/this.internalSampleRate;const r=Re(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.timestampe)break;if(n=i,s++,100===s){s=0;const e=this.encodedPacketToMetadata.get(n);oe(e),this.sequentialScanCache.length>0&&oe(ce(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 os=(e,t,i)=>{let r=t,n=i;e:for(;;){for(n--;n>=0;n--){if(r.lacingValues[n]<255){n++;break e}}oe(-1===n);if(!(1&r.headerType)){n=0;break}const t=De(e,e=>e.headerStartPos{if(i>0)return{page:t,segmentIndex:i-1};const r=De(e,e=>e.headerStartPosY(this,null,function*(){var e,t;let i=this.reader.requestSlice(0,12);ct(i)&&(i=yield i),oe(i);const r=Nl(i,4),n="RIFX"!==r,s="RF64"===r,a=xl(i,n);let o=s?this.reader.fileSize:Math.min(a+8,null!=(e=this.reader.fileSize)?e:1/0);if("WAVE"!==Nl(i,4))throw new Error("Invalid WAVE file - wrong format");let l=0,c=null,u=i.filePos;for(;null===o||u=18&&357!==n){const e=wl(r,i),s=t-18;if(Math.min(s,e)>=22&&n===cs.EXTENSIBLE){r.skip(6);const e=Tl(r,16);n=e[0]|e[1]<<8}}if(n!==cs.MULAW&&n!==cs.ALAW||(l=8),n!==cs.PCM&&n!==cs.IEEE_FLOAT&&n!==cs.ALAW&&n!==cs.MULAW)throw new Error(`Unsupported WAVE codec (format tag ${n}). Only integer/float PCM, A-law, and \u03bc-law are supported.`);if(n===cs.PCM&&![8,16,24,32].includes(l))throw new Error(`Unsupported WAVE PCM bit depth (${l}). Only 8, 16, 24, and 32 bits are supported.`);if(n===cs.IEEE_FLOAT&&![32,64].includes(l))throw new Error(`Unsupported WAVE float bit depth (${l}). Only 32 and 64 bits are supported.`);this.audioInfo={format:n,numberOfChannels:s,sampleRate:a,sampleSizeInBytes:Math.ceil(l/8),blockSizeInBytes:o}})}parseListChunk(e,t,i){return Y(this,null,function*(){var r,n,s,a,o,l,c,u,d,h,f;let m=this.reader.requestSlice(e,t);if(ct(m)&&(m=yield m),!m)return;const p=Nl(m,4);if("INFO"!==p&&"INF0"!==p)return;let g=m.filePos;for(;g<=e+t-8;){m.filePos=g;const e=Nl(m,4),t=xl(m,i),p=Tl(m,t);let k=0;for(let i=0;i0&&(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 Y(this,null,function*(){let i=this.reader.requestSlice(e,t);if(ct(i)&&(i=yield i),!i)return;const r=Xl(i);if(r){const n=t-Hl;if(r.size=Math.min(r.size,n),r.size>0){const t=i.slice(e+Hl,r.size);$l(t,r,this.metadataTags)}}})}getCodec(){if(oe(this.audioInfo),this.audioInfo.format===cs.MULAW)return"ulaw";if(this.audioInfo.format===cs.ALAW)return"alaw";if(this.audioInfo.format===cs.PCM){if(1===this.audioInfo.sampleSizeInBytes)return"pcm-u8";if(2===this.audioInfo.sampleSizeInBytes)return"pcm-s16";if(3===this.audioInfo.sampleSizeInBytes)return"pcm-s24";if(4===this.audioInfo.sampleSizeInBytes)return"pcm-s32"}if(this.audioInfo.format===cs.IEEE_FLOAT){if(4===this.audioInfo.sampleSizeInBytes)return"pcm-f32";if(8===this.audioInfo.sampleSizeInBytes)return"pcm-f64"}oe(!1)}getMimeType(){return Y(this,null,function*(){return"audio/wav"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(this,null,function*(){return yield this.readMetadata(),this.metadataTags})}}const hs=2048;class fs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return this.demuxer.getCodec()}getInternalCodecId(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.format}getDecoderConfig(){return Y(this,null,function*(){const e=this.demuxer.getCodec();return e?(oe(this.demuxer.audioInfo),{codec:e,numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate}):null})}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(-1!==this.demuxer.dataSize),this.demuxer.dataSize/this.demuxer.audioInfo.blockSizeInBytes/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getDisposition(){return H({},Ct)}getPacketAtIndex(e,t){return Y(this,null,function*(){oe(e>=0),oe(this.demuxer.audioInfo);const i=e*hs*this.demuxer.audioInfo.blockSizeInBytes;if(i>=this.demuxer.dataSize)return null;const r=Math.min(hs*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(ct(e)&&(e=yield e),!e)return null}let n;if(t.metadataOnly)n=br;else{let e=this.demuxer.reader.requestSlice(this.demuxer.dataStart+i,r);ct(e)&&(e=yield e),oe(e),n=Tl(e,r)}const s=e*hs/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 Tr(n,"key",s,a,e,r)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getPacket(e,t){return Y(this,null,function*(){oe(this.demuxer.audioInfo);const i=Math.floor(Math.min(e*this.demuxer.audioInfo.sampleRate/hs,(this.demuxer.dataSize-1)/(hs*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;oe(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){oe(this.demuxer.audioInfo);const i=Math.round(e.timestamp*this.demuxer.audioInfo.sampleRate/hs);return this.getPacketAtIndex(i+1,t)}getKeyPacket(e,t){return this.getPacket(e,t)}getNextKeyPacket(e,t){return this.getNextPacket(e,t)}}const ms=e=>{const t=e.filePos,i=Tl(e,9),r=new Bt(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}},ps=1024;class gs extends yr{constructor(e){super(e),this.metadataPromise=null,this.firstFrameHeader=null,this.loadedSamples=[],this.metadataTags=null,this.trackBackings=[],this.readingMutex=new xe,this.lastSampleLoaded=!1,this.lastLoadedPos=0,this.nextTimestampInSamples=0,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){for(;!this.firstFrameHeader&&!this.lastSampleLoaded;)yield this.advanceReader();oe(this.firstFrameHeader),this.trackBackings=[new ks(this)]}))()})}advanceReader(){return Y(this,null,function*(){if(0===this.lastLoadedPos)for(;;){let e=this.reader.requestSlice(this.lastLoadedPos,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=Xl(e);if(!t)break;this.lastLoadedPos=e.filePos+t.size}let e=this.reader.requestSliceRange(this.lastLoadedPos,7,9);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const t=ms(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=Et[t.samplingFrequencyIndex];oe(void 0!==i);const r=ps/i,n={timestamp:this.nextTimestampInSamples/i,duration:r,dataStart:t.startPos,dataSize:t.frameLength};this.loadedSamples.push(n),this.nextTimestampInSamples+=ps,this.lastLoadedPos=t.startPos+t.frameLength})}getMimeType(){return Y(this,null,function*(){return"audio/aac"})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackings})}getMetadataTags(){return Y(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,Hl);if(ct(t)&&(t=yield t),!t)break;const i=Xl(t);if(!i)break;let r=this.reader.requestSlice(t.filePos,i.size);if(ct(r)&&(r=yield r),!r)break;$l(r,i,this.metadataTags),e=t.filePos+i.size}return this.metadataTags}finally{e()}})}}class ks{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getTimeResolution(){return this.getSampleRate()/ps}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getName(){return null}getLanguageCode(){return We}getCodec(){return"aac"}getInternalCodecId(){return oe(this.demuxer.firstFrameHeader),this.demuxer.firstFrameHeader.objectType}getNumberOfChannels(){oe(this.demuxer.firstFrameHeader);const e=_t[this.demuxer.firstFrameHeader.channelConfiguration];return oe(void 0!==e),e}getSampleRate(){oe(this.demuxer.firstFrameHeader);const e=Et[this.demuxer.firstFrameHeader.samplingFrequencyIndex];return oe(void 0!==e),e}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.firstFrameHeader),{codec:`mp4a.40.${this.demuxer.firstFrameHeader.objectType}`,numberOfChannels:this.getNumberOfChannels(),sampleRate:this.getSampleRate()}})}getPacketAtIndex(e,t){return Y(this,null,function*(){if(-1===e)return null;const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.dataStart,i.dataSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.dataSize)}return new Tr(r,"key",i.timestamp,i.duration,e,i.dataSize)})}getFirstPacket(e){return this.getPacketAtIndex(0,e)}getNextPacket(e,t){return Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{const i=_e(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 Y(this,null,function*(){const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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+1Y(this,null,function*(){var e;let t=0;for(;;){let e=this.reader.requestSlice(t,Hl);if(ct(e)&&(e=yield e),!e)return void(this.lastSampleLoaded=!0);const i=Xl(e);if(!i)break;let r=this.reader.requestSlice(e.filePos,i.size);ct(r)&&(r=yield r),oe(r),$l(r,i,this.metadataTags),t=e.filePos+i.size}for(t+=4;null===this.reader.fileSize||ts.end-6)return{num:a.num,blockSize:a.blockSize,sampleRate:a.sampleRate,size:s.end-e,isLastFrame:!0};if(255===vl(s)){const t=s.filePos;if(vl(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=Tl(e,4),n=new Bt(r);if(32764!==n.readBits(15))return null;if(null===this.blockingBit){oe(t);const e=n.readBits(1);this.blockingBit=e}else if(1===this.blockingBit){oe(!t);if(1!==n.readBits(1))return null}else{if(0!==this.blockingBit)throw new Error("Invalid blocking bit");oe(!t);if(0!==n.readBits(1))return null}const s=(e=>0===e?null:1===e?192:e>=2&&e<=5?144*q(2,e):6===e?"uncommon-u8":7===e?"uncommon-u16":e>=8&&e<=15?q(2,e):null)(n.readBits(4));if(!s)return null;oe(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 o=(e=>{let t=0;const i=new Bt(Tl(e,1));for(;1===i.readBits(1);)t++;if(0===t)return i.readBits(7);const r=[],n=t-1,s=new Bt(Tl(e,n)),a=8-t-1;for(let o=0;oe|t<"uncommon-u16"===t?Sl(e)+1:"uncommon-u8"===t?vl(e)+1:"number"===typeof t?t:(Oe(t),void oe(!1)))(e,s),c=((e,t)=>"uncommon-u16"===t?Sl(e):"uncommon-u16-10"===t?10*Sl(e):"uncommon-u8"===t?vl(e):"number"===typeof t?t:null)(e,a);if(null===c)return null;if(c!==this.audioInfo.sampleRate)return null;const u=e.filePos-i,d=vl(e);e.skip(-u),e.skip(-1);const h=(e=>{let t=0;for(const i of e){t^=i;for(let e=0;e<8;e++)0!==(128&t)?t=t<<1^7:t<<=1,t&=255}return t})(Tl(e,u));return d!==h?null:{num:o,blockSize:l,sampleRate:c}}advanceReader(){return Y(this,null,function*(){yield this.readMetadata(),oe(null!==this.lastLoadedPos),oe(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 bs{constructor(e){this.demuxer=e}getType(){return"audio"}getId(){return 1}getNumber(){return 1}getCodec(){return"flac"}getInternalCodecId(){return null}getNumberOfChannels(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.numberOfChannels}getSampleRate(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}getName(){return null}getLanguageCode(){return We}getTimeResolution(){return oe(this.demuxer.audioInfo),this.demuxer.audioInfo.sampleRate}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),0===this.demuxer.audioInfo.totalSamples?null:this.demuxer.audioInfo.totalSamples/this.demuxer.audioInfo.sampleRate})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}getDisposition(){return H({},Ct)}getDecoderConfig(){return Y(this,null,function*(){return oe(this.demuxer.audioInfo),{codec:"flac",numberOfChannels:this.demuxer.audioInfo.numberOfChannels,sampleRate:this.demuxer.audioInfo.sampleRate,description:this.demuxer.audioInfo.description}})}getPacket(e,t){return Y(this,null,function*(){if(oe(this.demuxer.audioInfo),e<0)return null;const i=yield this.demuxer.readingMutex.acquire();try{for(;;){const i=Re(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 Y(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 Y(this,null,function*(){const i=this.demuxer.loadedSamples[e];if(!i)return null;let r;if(t.metadataOnly)r=br;else{let e=this.demuxer.reader.requestSlice(i.byteOffset,i.byteSize);if(ct(e)&&(e=yield e),!e)return null;r=Tl(e,i.byteSize)}oe(this.demuxer.audioInfo);const n=i.blockOffset/this.demuxer.audioInfo.sampleRate,s=i.blockSize/this.demuxer.audioInfo.sampleRate;return new Tr(r,"key",n,s,e,i.byteSize)})}getFirstPacket(e){return Y(this,null,function*(){for(;0===this.demuxer.loadedSamples.length&&!this.demuxer.lastSampleLoaded;)yield this.demuxer.advanceReader();return this.getPacketAtIndex(0,e)})}}const Ts=9e4,vs=q(2,33),ws=188,Ss="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.",Ps=new Set([133,134,162]),Is=new Set;class xs extends yr{constructor(e){super(e),this.metadataPromise=null,this.elementaryStreams=[],this.trackBackingEntries=[],this.packetOffset=0,this.packetStride=-1,this.sectionEndPositions=[],this.seekChunkSize=5242880,this.minReferencePointByteDistance=-1,this.timestampWrapInfo=null,this.reader=e._reader}readMetadata(){return Y(this,null,function*(){var e;return null!=(e=this.metadataPromise)?e:this.metadataPromise=(()=>Y(this,null,function*(){let e=this.reader.requestSlice(0,205);ct(e)&&(e=yield e),oe(e);const t=Tl(e,205);if(71===t[0]&&71===t[188])this.packetOffset=0,this.packetStride=ws;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}if(s&&!this.elementaryStreams.some(t=>t.pid===e.pid)){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 Bt(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=Bs(this,t,!0);if(!i)throw new Error(`Couldn't read first PES packet for Elementary Stream with PID ${e.pid}`);if(e.firstSection=t,e.canBeTrustedWithKeyPackets=1===t.randomAccessIndicator,this.input._initInput){const i=(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 As(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=$t(r.suppliedPacket.data),!e.info.avcCodecInfo)continue;const t=e.info.avcCodecInfo.sequenceParameterSets[0];oe(t);const i=Jt(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[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=ni(r.suppliedPacket.data),!e.info.hevcCodecInfo)continue;const t=e.info.hevcCodecInfo.arrays.find(e=>e.nalUnitType===Lt.SPS_NUT).nalUnits[0];oe(t);const i=ri(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:ye[i.colourPrimaries],transfer:Te[i.transferCharacteristics],matrix:we[i.matrixCoefficients],fullRange:!!i.fullRangeFlag},e.info.reorderSize=i.maxDecFrameBuffering;break}throw new Error("Unhandled.")}e.info.decoderConfig={codec:tr({width:e.info.width,height:e.info.height,codec:e.info.codec,codecDescription:null,colorSpace:e.info.colorSpace,avcType:1,avcCodecInfo:e.info.avcCodecInfo,hevcCodecInfo:e.info.hevcCodecInfo,vp9CodecInfo:null,av1CodecInfo:null,proresFormat:null}),codedWidth:e.info.width,codedHeight:e.info.height,colorSpace:e.info.colorSpace},e.info.width===e.info.squarePixelWidth&&e.info.height===e.info.squarePixelHeight||(e.info.decoderConfig.displayAspectWidth=e.info.squarePixelWidth,e.info.decoderConfig.displayAspectHeight=e.info.squarePixelHeight),e.initialized=!0}else{if(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=yl.tempFromBytes(r.suppliedPacket.data),i=ms(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=_t[i.channelConfiguration],e.info.sampleRate=Et[i.samplingFrequencyIndex]}else if("mp3"===e.info.codec){const t=Cl(yl.tempFromBytes(r.suppliedPacket.data)),i=fr(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=kr(i.header.channel),e.info.sampleRate=i.header.sampleRate}else if("ac3"===e.info.codec){const t=Ci(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=xi[t.acmod]+t.lfeon,e.info.sampleRate=Mt[t.fscod]}else if("eac3"===e.info.codec){const t=_i(r.suppliedPacket.data);if(!t)throw new Error("Invalid E-AC-3 audio stream; could not read sync frame from first packet.");const i=Ri(t);if(null===i)throw new Error("Invalid E-AC-3 audio stream; reserved sample rate code found in first packet.");e.info.numberOfChannels=Fi(t),e.info.sampleRate=i}else{if("dts"!==e.info.codec)throw new Error("Unhandled.");{const t=qi(r.suppliedPacket.data);if(!t)throw new Error("Invalid DTS audio stream; could not read frame header from first packet.");e.info.numberOfChannels=t.numberOfChannels,e.info.sampleRate=t.sampleRate,t.core&&(e.info.dtsFormat=t.hasExtensions?"dtsh":"dtsc")}}e.info.decoderConfig={codec:rr({codec:e.info.codec,codecDescription:null,aacCodecInfo:e.info.aacCodecInfo,dtsFormat:e.info.dtsFormat}),numberOfChannels:e.info.numberOfChannels,sampleRate:e.info.sampleRate},e.initialized=!0}}}else{const e=new Bt(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),l=e.pos+8*n;let c=!1;for(;e.pos=4){const t=e.readBits(32);c||(c=1212435798===t||1212436562===t)}e.pos=r}for(e.pos=l;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,o=!1;for(;e.pos=4){const t=e.readBits(32);o||(o=1146376960===(4294967040&t))}e.pos=r}let l=null;const u=c&&Ps.has(t)?130:t;switch(u){case 27:case 36:l={type:"video",codec:27===t?"avc":"hevc",decoderConfig:null,avcCodecInfo:null,hevcCodecInfo:null,colorSpace:{primaries:null,transfer:null,matrix:null,fullRange:null},width:-1,height:-1,squarePixelWidth:-1,squarePixelHeight:-1,reorderSize:-1};break;case 3:case 4:case 15:case 129:case 135:case 130:case 138:{let e;e=3===u||4===u?"mp3":15===u?"aac":129===u?"ac3":135===u?"eac3":"dts",l={type:"audio",codec:e,decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}}break;case 6:a?l={type:"audio",codec:"eac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:s?l={type:"audio",codec:"ac3",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1}:o&&(l={type:"audio",codec:"dts",decoderConfig:null,aacCodecInfo:null,dtsFormat:null,numberOfChannels:-1,sampleRate:-1});break;default:Is.has(t)||(Pt._warn(`Note: MPEG-TS streams with stream_type 0x${t.toString(16)} are not currently supported.`),Is.add(t))}l&&this.elementaryStreams.push({demuxer:this,pid:i,streamType:t,initialized:!1,firstSection:null,canBeTrustedWithKeyPackets:!1,info:l,referencePesPackets:[]})}s=!0}else{const e=new Bt(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)a.initialized&&("video"===a.info.type?this.trackBackingEntries.push(new _s(a)):this.trackBackingEntries.push(new Rs(a)))}))()})}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),this.trackBackingEntries})}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(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 Y(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!==_e(this.sectionEndPositions,r,e=>e)){c=!1;break}}if(c){const e=Re(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 Y(this,null,function*(){let t=this.reader.requestSlice(e,4);if(ct(t)&&(t=yield t),!t)return null;if(71!==vl(t))throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const i=Sl(t);return{payloadUnitStartIndicator:i>>14&1,pid:8191&i,adaptationFieldControl:vl(t)>>4&3}})}readPacket(e){return Y(this,null,function*(){let t=this.reader.requestSlice(e,ws);if(ct(t)&&(t=yield t),!t)return null;const i=Tl(t,ws);if(71!==i[0])throw new Error("Invalid TS packet sync byte. Likely an internal bug, please report this file.");const r=(i[1]<<8)+i[2];return{payloadUnitStartIndicator:r>>14&1,pid:8191&r,adaptationFieldControl:i[3]>>4&3,body:i.subarray(4)}})}normalizeTimestamp(e){if(!this.timestampWrapInfo){const t=54e5;this.timestampWrapInfo={reference:e-t,offset:e>=vs-t?-vs:vs}}const{reference:t,offset:i}=this.timestampWrapInfo;return i<0&&e>=t||i>0&&e{if(t.payload.byteLength<3)return null;const r=new Bt(t.payload);if(1!==r.readBits(24))return null;const n=r.readBits(8);if(r.skipBits(16),188===n||190===n||191===n||240===n||241===n||255===n||242===n||248===n)return null;r.skipBits(8);const s=r.readBits(2);r.skipBits(14);let a=null;if(2===s||3===s)a=0,r.skipBits(4),a+=r.readBits(3)*(1<<30),r.skipBits(1),a+=32768*r.readBits(15),r.skipBits(1),a+=r.readBits(15),a=e.normalizeTimestamp(a);else if(i)throw new Error(Ss);return{sectionStartPos:t.startPos,sectionEndPos:t.endPos,pts:a,randomAccessIndicator:t.randomAccessIndicator}},Bs=(e,t,i)=>{oe(null!==t.endPos);const r=Cs(e,t,i);if(!r)return null;const n=new Bt(t.payload);n.skipBits(32);const s=n.readBits(16);n.skipBits(16);const a=n.readBits(8),o=n.pos+8*a;n.pos=o;const l=o/8;oe(Number.isInteger(l));const c=t.payload.subarray(l,s>0?6+s:t.payload.byteLength);return V(H({},r),{data:c})};class Es{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++,oe(r instanceof Es),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 We}getDisposition(){return V(H({},Ct),{primary:!1})}getTimeResolution(){return Ts}isRelativeToUnixEpoch(){return!1}getUnixTimeForTimestamp(){return null}getPairingMask(){return BigInt("1")}getBitrate(){return null}getAverageBitrate(){return null}getDurationFromMetadata(){return Y(this,null,function*(){return null})}getLiveRefreshInterval(){return Y(this,null,function*(){return null})}createEncodedPacket(e,t,i){let r;return r=this.allPacketsAreKeyPackets()||1===e.randomAccessIndicator?"key":"delta",new Tr(i.metadataOnly?br:e.data,r,e.pts/Ts,Math.max(t/Ts,0),e.sequenceNumber,e.data.byteLength)}getFirstPacket(e){return Y(this,null,function*(){const t=this.elementaryStream.firstSection;oe(t);const i=Bs(this.elementaryStream.demuxer,t,!0);oe(i);const r=new As(this.elementaryStream,i),n=new Ms(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 Y(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);oe(s);const a=Bs(n,s,!0);oe(a);const o=new As(this.elementaryStream,a);i=new Ms(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 Y(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 Y(this,null,function*(){var r,n,s,a,o,l;const c=He(e*Ts),u=this.elementaryStream.demuxer,{reader:d,seekChunkSize:h}=u,f=this.elementaryStream.pid,m=(e,t,i)=>Y(this,null,function*(){let r=e;for(;re.pts),T=-1!==b?y[b]:null;if(T&&c-T.pts<45e3)k=T.sectionStartPos;else{let e=0;if(null!==d.fileSize){const t=Math.ceil(d.fileSize/h);if(t>1){let i=0,r=t-1;for(e=i;i<=r;){const t=Math.floor((i+r)/2),n=Ke(t*h,u.packetStride)+g.sectionStartPos,s=n+h,a=yield m(n,s,!1);a?a.pesPacketHeader.pts<=c?(e=t,i=t+1):r=t-1:r=t-1}}}k=Ke(e*h,u.packetStride)+g.sectionStartPos}const v=yield m(k,null!=(r=d.fileSize)?r:1/0,!1);let w=null!=(n=null==v?void 0:v.pesPacketHeader)?n:null;w||(w=g);const S=this.getReorderSize(),P=(e,t)=>Y(this,null,function*(){var r,n;const s=yield u.readSection(e,!0);oe(s);const a=Bs(u,s,!0);oe(a);const o=new As(this.elementaryStream,a),l=new Ms(this,o);for(;;){if((null!=(n=null==(r=ce(l.presentationOrderPackets))?void 0:r.pts)?n:-1/0)>=c)break;if(!(yield l.readNextPacket()))break}const d=Ne(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();oe(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=w.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){if(e.pts>c)break e;w=e,Fs(this.elementaryStream,w);break}}}e+=u.packetStride}}e:for(let e=0;e=u.packetOffset;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,!1);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){w=e;break}}}e-=u.packetStride}}return P(w.sectionStartPos,e=>e.pts<=c)}{let e=k,t=null;const i=!this.elementaryStream.canBeTrustedWithKeyPackets;for(;;){let r=null;const n=e<=g.sectionStartPos;let k,y=null;if(n)k=g,y=p;else{const t=yield m(e,null!=(s=d.fileSize)?s:1/0,i);k=null!=(a=null==t?void 0:t.pesPacketHeader)?a:null,y=null!=(o=null==t?void 0:t.section)?o:null}let b=!1,T=0;e:for(;k&&!(null!==t&&k.sectionStartPos>=t);){if(k.pts<=c){let e;if(this.elementaryStream.canBeTrustedWithKeyPackets)e=1===k.randomAccessIndicator;else{oe(y);const t=Bs(u,y,!0);oe(t);const i=new As(this.elementaryStream,t);yield i.markNextPacket(),e=1===(null==(l=i.suppliedPacket)?void 0:l.randomAccessIndicator)}e&&(r=k)}if(k.pts>c&&(b=!0),b&&(T++,T>S))break;let e=k.sectionStartPos+u.packetStride;for(;;){const t=yield u.readPacketHeader(e);if(!t)break e;if(t.pid===f&&1===t.payloadUnitStartIndicator){const t=yield u.readSection(e,i);if(t){const e=Cs(u,t,!1);if(e&&null!==e.pts){k=e,y=t,Fs(this.elementaryStream,k);break}}}e+=u.packetStride}}if(r){let e=r;if(0===T)e:for(let r=0;r=u.packetOffset;){const r=yield u.readPacketHeader(t);if(!r)break e;if(r.pid===f&&1===r.payloadUnitStartIndicator){const r=yield u.readSection(t,i);if(r){const t=Cs(u,r,!1);if(t&&null!==t.pts){e=t;break}}}t-=u.packetStride}}const t=yield P(e.sectionStartPos,e=>e.pts<=c&&1===e.randomAccessIndicator);return oe(t),t}if(n)return null;t=e,e=Math.max(Ke(e-g.sectionStartPos-h,u.packetStride)+g.sectionStartPos,g.sectionStartPos)}}})}}class _s extends Es{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 Y(this,null,function*(){return this.elementaryStream.info.colorSpace})}canBeTransparent(){return Y(this,null,function*(){return!1})}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!1}getReorderSize(){return this.elementaryStream.info.reorderSize}}class Rs extends Es{getType(){return"audio"}getCodec(){return this.elementaryStream.info.codec}getNumberOfChannels(){return this.elementaryStream.info.numberOfChannels}getSampleRate(){return this.elementaryStream.info.sampleRate}getDecoderConfig(){return Y(this,null,function*(){return oe(this.elementaryStream.info.decoderConfig),this.elementaryStream.info.decoderConfig})}allPacketsAreKeyPackets(){return!0}getReorderSize(){return 0}}const Fs=(e,t)=>{const i=e.referencePesPackets,r=Re(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=e?e:this.bufferData(e-t).then(()=>Math.min(this.endPos-this.currentPos,e))}getCurrentPesPacket(){const e=this.pesPackets[this.currentPesPacketIndex];return oe(e),e}bufferData(e){return Y(this,null,function*(){const t=this.endPos+e;for(;this.endPos=c)break;u=t;const r=o+u;if(u+3>=c){this.seekTo(r);break}const d=l[u+1],h=l[u+2],f=l[u+3];let m=0;if(0===d&&0===h&&1===f?m=4:0===d&&1===h&&(m=3),0===m){u++;continue}const p=r;null!=n||(n=p);const g=u+m,k=g+i,y=6;if(k+("avc"===e?y:1)>c){this.seekTo(r);break}const b=l[g];let T,v,w;if("avc"===e)T=Ht(b),v=T===Nt.NON_IDR_SLICE||T===Nt.SLICE_DPA||T===Nt.IDR,w=T===Nt.SEI||T===Nt.SPS||T===Nt.PPS||T===Nt.AUD;else{T=ii(b);if(((1&b)<<5|l[g+1]>>3)>0){u+=m;continue}v=T<=Lt.RASL_R||T>=Lt.BLA_W_LP&&T<=21,w=T>=Lt.VPS_NUT&&T<=37||T===Lt.PREFIX_SEI_NUT||T>=41&&T<=44||T>=48&&T<=55}let S=!1;if(v){let t;if("avc"===e){const e=l.subarray(k,k+y),i=ue(new Bt(e));t=!s||i<=a,a=i}else t=l[k]>>7===1;t&&(s?S=!0:s=!0)}else w&&s&&(S=!0);if(S){const e=p-n;return this.seekTo(n),this.supplyPacket(e,0)}u+=m}if(rn){const e=this.endPos-n;return this.seekTo(n),this.supplyPacket(e,0)}}else{const n=r.info.codec,s=128;for(;;){let a=this.ensureBuffered(s);ct(a)&&(a=yield a);const o=this.currentPos;for(;this.currentPos-o>6,a=63&i[4];if(3===n||a>37){this.seekTo(e+1);continue}const o=Bi[3*a+n];oe(void 0!==o),this.seekTo(e),t=this.ensureBuffered(o),ct(t)&&(t=yield t);const l=Math.round(13824e4/r.info.sampleRate);return this.supplyPacket(t,l)}if("eac3"===n){if(11!==s)continue;this.skip(-1);const e=this.currentPos;let t=this.ensureBuffered(5);if(ct(t)&&(t=yield t),t<5)return;const i=this.readBytes(5);if(11!==i[0]||119!==i[1]){this.seekTo(e+1);continue}const n=2*(((7&i[2])<<8|i[3])+1),a=3===i[4]>>6?3:i[4]>>4&3,o=Ei[a];this.seekTo(e),t=this.ensureBuffered(n),ct(t)&&(t=yield t);const l=256*o,c=Math.round(l*Ts/r.info.sampleRate);return this.supplyPacket(t,c)}if("dts"===n){if(127!==s&&100!==s)continue;this.skip(-1);const n=this.currentPos;let a=this.ensureBuffered(18);if(ct(a)&&(a=yield a),a<18)return;const o=this.readBytes(18),l=Hi(o);let c=l?null:Vi(o);if(!l&&!c){this.seekTo(n+1);continue}if(c&&!c.asset){this.seekTo(n);const t=Math.min(c.frameSize,4096);let i=this.ensureBuffered(t);ct(i)&&(i=yield i),c=null!=(e=Vi(this.readBytes(i)))?e:c}let u=l?l.frameSize:c.frameSize;if(l){let e=4*Math.ceil(l.frameSize/4);for(;;){this.seekTo(n);const t=e+10;let i=this.ensureBuffered(t);if(ct(i)&&(i=yield i),i=0)}readNext(){return Y(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(oe(-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 Y(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 Y(this,null,function*(){const e=this.decodeOrderPackets[0];for(oe(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;ie.pts-t.pts),this.presentationOrderPackets.push(...this.reorderBuffer),this.reorderBuffer.length=0}}const Ds="application/vnd.apple.mpegurl",Ns="#EXT-X-STREAM-INF:",Os="#EXT-X-I-FRAME-STREAM-INF:",Ls="#EXT-X-MEDIA:",zs="#EXTINF:",Us="#EXT-X-MAP:",qs="#EXT-X-KEY:",Ws="#EXT-X-MEDIA-SEQUENCE:",Hs="#EXT-X-BYTERANGE:",Vs="#EXT-X-PROGRAM-DATE-TIME:",js="#EXT-X-TARGETDURATION:",Ks="#EXT-X-PLAYLIST-TYPE:",Xs=e=>0===e.length||e.startsWith("#")&&!e.startsWith("#EXT");class $s{constructor(e){this._attributes={};let t="",i="",r=!1,n=!1;for(let s=0;sY(this,null,function*(){const e=[];if(this.trackDeclarations){for(const t of this.trackDeclarations)if("video"===t.type){const i=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,t,i))}else if("audio"===t.type){const i=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(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=gt(e,e=>"video"===e.getType())+1;e.push(new Ys(this,{id:e.length+1,type:"video"},t))}else if("audio"===r.type){const t=gt(e,e=>"audio"===e.getType())+1;e.push(new Js(this,{id:e.length+1,type:"audio"},t))}}return e}))()})}getFirstTimestampForInput(e){return Y(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 Y(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 Qs{constructor(e,t,i){this.packetInfos=new WeakMap,this.hydrationPromise=null,this.firstInputTrack=null,this.firstSegment=null,this.segmentedInput=e,this.decl=t,this.number=i}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(this,null,function*(){var e,t;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.");let i=this.segmentedInput.firstSegment,r=null;for(;i;){const e=this.segmentedInput.getInputForSegment(i);if(r=null!=(t=(yield e.getTracks()).find(e=>e.type===this.decl.type&&e.number===this.number))?t:null,r)break;i=yield this.segmentedInput.getNextSegment(i,{})}if(!r)throw new Error("No matching track found in underlying media data.");this.firstInputTrack=r,this.firstSegment=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 Y(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 Y(this,null,function*(){return yield this.hydrate(),oe(this.segmentedInput.firstSegment),this.segmentedInput.firstSegment.unixEpochTimestamp===this.segmentedInput.firstSegment.timestamp})}getUnixTimeForTimestamp(e){return this.segmentedInput.getUnixTimeForTimestamp(e)}getBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getBitrate())}getAverageBitrate(){return this.delegate(()=>this.firstInputTrack._backing.getAverageBitrate())}getDurationFromMetadata(e){return this.segmentedInput.getDurationFromMetadata(e)}getLiveRefreshInterval(){return this.segmentedInput.getLiveRefreshInterval()}createAdjustedPacket(e,t,i){return Y(this,null,function*(){oe(e.sequenceNumber>=0),oe(this.segmentedInput.firstSegment);const r=yield this.segmentedInput.getMediaOffset(t,i.input),n=t.timestamp-this.segmentedInput.firstSegment.timestamp,s=e.clone({timestamp:je(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 Y(this,null,function*(){var t;yield this.hydrate(),oe(this.firstInputTrack),oe(this.firstSegment);let i=this.firstInputTrack,r=this.firstSegment;for(;;){if(i){const t=yield i._backing.getFirstPacket(e);if(t)return this.createAdjustedPacket(t,r,i)}if(r=yield this.segmentedInput.getNextSegment(r,{skipLiveWait:e.skipLiveWait}),!r)break;const n=this.segmentedInput.getInputForSegment(r);i=null!=(t=(yield n.getTracks()).find(e=>e.type===this.firstInputTrack.type&&e.number===this.firstInputTrack.number))?t:null}return null})}getNextPacket(e,t){return this._getNextInternal(e,t,!1)}getNextKeyPacket(e,t){return this._getNextInternal(e,t,!0)}_getNextInternal(e,t,i){return Y(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 Y(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 Ys extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getColorSpace())})}canBeTransparent(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.canBeTransparent())})}getDecoderConfig(){return Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}class Js extends Qs{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 Y(this,null,function*(){return this.delegate(()=>this.firstInputTrack._backing.getDecoderConfig())})}}ft();const Zs=1/0;"undefined"!==typeof FinalizationRegistry&&new FinalizationRegistry(e=>{e()});class ea extends vt{constructor(){super(),this._disposed=!1,this._refCount=0,this._usedForHls=!1,this._refFinalizationRegistry=null,this._sizePromise=null,this.onread=null,"undefined"!==typeof FinalizationRegistry&&(this._refFinalizationRegistry=new FinalizationRegistry(e=>{e._decrementRefCount()}))}getSizeOrNull(){return Y(this,null,function*(){var e;if(this._disposed)throw new gl;return null!=(e=this._sizePromise)?e:this._sizePromise=(()=>Y(this,null,function*(){let e=this._getFileSize();return void 0!==e||(yield this._read(0,1,0,Zs),e=this._getFileSize(),oe(void 0!==e)),e}))()})}getSize(){return Y(this,null,function*(){if(this._disposed)throw new gl;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 ga(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 ta(this)}_incrementRefCount(){this._refCount++}_decrementRefCount(){this._refCount--,0===this._refCount&&(this._dispose(),this._disposed=!0)}}class ta{constructor(e){var t;if(this._freed=!1,e._disposed)throw new Error("Cannot ref a disposed source.");e._incrementRefCount(),null==(t=e._refFinalizationRegistry)||t.register(this,e,this),this._source=e}get source(){if(!this._source)throw new Error("Can't get source; ref has already been freed.");return this._source}get freed(){return this._freed}free(){var e;if(this._freed)throw new Error("Illegal operation: double free on SourceRef.");const t=this.source;oe(t._refCount>0),t._decrementRefCount(),null==(e=t._refFinalizationRegistry)||e.unregister(this),this._freed=!0,this._source=null}[Symbol.dispose](){this.freed||this.free()}}class ia extends ea{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 ea||e instanceof ta))throw new TypeError("requestHandler must return or resolve to a Source or SourceRef.");const i=e instanceof ea?e.ref():e;return(t=i.source)._usedForHls||(t._usedForHls=this._usedForHls),i};return ct(t)?t.then(i):i(t)}}const ra=(e,t)=>e.path===t.path;class na extends ia{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 ea?e.ref():e;return this._root=t,this._rootRequest=null,t};ct(e)?this._rootRequest=e.then(t):(t(e),oe(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())}}const sa="undefined"!==typeof FinalizationRegistry?new FinalizationRegistry(e=>{e.cancel().catch(()=>{})}):null;class aa extends ea{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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.useStreamReader&&"boolean"!==typeof t.useStreamReader)throw new TypeError("options.useStreamReader, when provided, must be a boolean.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(),this._readers=new WeakMap,this._blob=e,this._options=t,this._orchestrator=new pa({maxCacheSize:null!=(i=t.maxCacheSize)?i:8*q(2,20),maxWorkerCount:4,runWorker:this._runWorker.bind(this),onIdleWorkerRemoved:e=>{const t=this._readers.get(e);t&&(this._readers.delete(e),null==sa||sa.unregister(e),t.cancel().catch(()=>{}))},prefetchProfile:ma.fileSystem,handleUnhandledError:t.handleUnhandledError}),this._orchestrator.fileSize=e.size}_getFileSize(){return this._orchestrator.fileSize}_read(e,t,i,r){return this._orchestrator.read(e,t,i,r)}_runWorker(e){return Y(this,null,function*(){oe(e.strictTarget);let t=this._readers.get(e);if(void 0===t){if("stream"in this._blob&&!it()&&!1!==this._options.useStreamReader){t=this._blob.slice(e.currentPos).stream().getReader(),null==sa||sa.register(e,t,e)}else t=null;this._readers.set(e,t)}for(;e.currentPos{if(t instanceof Error&&(t.message.includes("Failed to fetch")||t.message.includes("Load failed")||t.message.includes("NetworkError when attempting to fetch resource"))&&"undefined"!==typeof window){let e=null;try{"undefined"!==typeof window&&"undefined"!==typeof window.location&&(e=new URL(i instanceof Request?i.url:i,window.location.href).origin)}catch(r){}if(("undefined"===typeof navigator||"boolean"!==typeof navigator.onLine||navigator.onLine)&&null!==e&&e!==window.location.origin)return Pt._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(q(2,e-2),16)},ca=new Set;class ua extends ia{constructor(e,t={}){var i,r,n,s;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&&(!mt(t.maxCacheSize)||t.maxCacheSize<0))throw new TypeError("options.maxCacheSize, when provided, must be a non-negative number.");if(void 0!==t.parallelism&&(!Number.isInteger(t.parallelism)||t.parallelism<1))throw new TypeError("options.parallelism, when provided, must be a positive number.");if(void 0!==t.fetchFn&&"function"!==typeof t.fetchFn)throw new TypeError("options.fetchFn, when provided, must be a function.");if(void 0!==t.handleUnhandledError&&"function"!==typeof t.handleUnhandledError)throw new TypeError("options.handleUnhandledError, when provided, must be a function.");super(e instanceof Request?e.url:e instanceof URL?e.href:e,e=>new ua(e.path,this._options)),this._offset=0,this._length=null,this._fileSizeDetermined=!1,this._sequentialBacking=null,this._url=e,this._options=t,this._getRetryDelay=null!=(i=t.getRetryDelay)?i:la,this._requestInit=H({},t.requestInit);let a=null;if(null==(r=t.requestInit)?void 0:r.headers){const e=H({},Je(t.requestInit.headers)),i=Object.keys(e).find(e=>"range"===e.toLowerCase());void 0!==i&&(a=e[i],delete e[i],this._requestInit.headers=e)}if(e instanceof Request){const t=e.headers.get("Range");if(null!==t){null!=a||(a=t);const i=new Request(e);i.headers.delete("Range"),this._url=i}}if(null!==a){const e=ha(a);e&&(this._offset=e.offset,this._length=e.length)}this._orchestrator=new pa({maxCacheSize:null!=(n=t.maxCacheSize)?n:64*q(2,20),maxWorkerCount:null!=(s=t.parallelism)?s:2,runWorker:this._runWorker.bind(this),prefetchProfile:ma.network,handleUnhandledError:t.handleUnhandledError})}_getFileSize(){var e;if(!this._fileSizeDetermined)return null!==this._length?this._length:void 0;const t=this._sequentialBacking?this._sequentialBacking._endIndex:this._orchestrator.fileSize;return null===t?null!==this._length?this._length:null:qe(t-this._offset,0,null!=(e=this._length)?e:1/0)}_read(e,t,i,r){var n;if(null!==this._length&&t>this._length)return null;const s=this._offset,a=this._sequentialBacking?this._sequentialBacking._read(s+e,s+t):this._orchestrator.read(s+e,s+t,Math.max(s+i,s),s+Math.min(r,null!=(n=this._length)?n:1/0)),o=e=>e?(e.offset-=this._offset,e):null;return ct(a)?a.then(o):o(a)}_runWorker(e){return Y(this,null,function*(){for(var t;;){const r=new AbortController,n=yield Ze(null!=(t=this._options.fetchFn)?t:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${e.currentPos}-`},signal:r.signal}),this._getRetryDelay,()=>this._disposed);if(!n.ok)throw new Error(`Error fetching ${String(this._url)}: ${n.status} ${n.statusText}`);n.redirected&&(this.rootPath=n.url);e:if(null===this._orchestrator.fileSize&&(206===n.status||"basic"===n.type&&!n.headers.has("Content-Encoding"))){const t=n.headers.get("Content-Range");if(t){const e=/\/(\d+)/.exec(t);if(e){this._orchestrator.supplyFileSize(Number(e[1]));break e}}const i=n.headers.get("Content-Length");if(i){const t=206===n.status?e.currentPos:0;this._orchestrator.supplyFileSize(t+Number(i))}}if(this._fileSizeDetermined=!0,!n.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");if(206!==n.status){if(this._sequentialBacking)return void n.body.cancel();if(!this._usedForHls){const e=new URL(this._url instanceof Request?this._url.url:this._url,"undefined"!==typeof window?window.location.href:void 0);"null"===e.origin||e.pathname.endsWith(".m3u8")||e.pathname.endsWith(".m3u")||ca.has(e.origin)||(Pt._warn(`HTTP server (origin ${e.origin}) did not respond to a range request with 206 Partial Content, meaning the resource will now be streamed sequentially, with old data being evicted from the cache. Reads into evicted regions will throw. To enable efficient media file streaming across a network, please make sure your server supports range requests. Alternatively, set maxCacheSize to Infinity in the UrlSource options to keep the entire resource in memory.`),ca.add(e.origin))}return void this._transitionToSequentialMode(n.body)}const s=n.body.getReader();for(;;){if(e.currentPos>=e.targetPos||e.aborted)return r.abort(),void this._orchestrator.signalWorkerStoppedRunning(e);let t;try{t=yield s.read()}catch(i){if(this._disposed)throw i;const e=this._getRetryDelay(1,i,this._url);if(null!==e){Pt._error("Error while reading response stream. Attempting to resume.",i),yield Tt(1e3*e);break}throw i}if(e.aborted)continue;const{done:n,value:a}=t;if(n){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+a.length),this._orchestrator.supplyWorkerData(e,a)}}})}_transitionToSequentialMode(e){let t=e.getReader(),i=0,r=0;const n=new ReadableStream({pull:e=>Y(this,null,function*(){for(var n;;){let a;try{a=yield t.read()}catch(s){if(this._disposed)throw s;const e=this._getRetryDelay(1,s,this._url);if(null===e)throw s;Pt._error("Error while reading response stream. Attempting to resume.",s),yield Tt(1e3*e);const a=yield Ze(null!=(n=this._options.fetchFn)?n:fetch,this._url,Ye(this._requestInit,{headers:{Range:`bytes=${i}-`}}),this._getRetryDelay,()=>this._disposed);if(!a.ok)throw new Error(`Error fetching ${String(this._url)}: ${a.status} ${a.statusText}`);if(!a.body)throw new Error("Missing HTTP response body stream. The used fetch function must provide the response body as a ReadableStream.");t=a.body.getReader(),r=206===a.status?0:i;continue}if(a.done)return void e.close();let o=a.value;if(r>0){const e=Math.min(r,o.length);r-=e,o=o.subarray(e)}if(0!==o.length)return i+=o.length,void e.enqueue(o)}}),cancel:()=>t.cancel()}),s=new fa(n,{maxCacheSize:this._orchestrator.options.maxCacheSize,handleUnhandledError:this._options.handleUnhandledError});s._endIndex=this._orchestrator.fileSize,s._cacheMissErrorMessage="Attempted to read data from an already-evicted part of the cache. Because the HTTP server did not honor the range request, data can only be read sequentially, with old data being evicted from the cache. To fix this issue, either ensure your server responds to range requests with 206 Partial Content, or set maxCacheSize to Infinity in the UrlSource options. Note that the latter will store the entire file in the cache if needed, no matter how large.",s.on("read",({start:e,end:t})=>this._dispatchRead(e,t)),this._sequentialBacking=s;const a=new Set;for(const o of this._orchestrator.workers){for(const e of o.pendingSlices)a.add(e);o.aborted=!0,o.pendingSlices.length=0}for(const o of this._orchestrator.queuedReads)for(const e of o.pendingSlices)a.add(e);this._orchestrator.workers.length=0,this._orchestrator.queuedReads.length=0;for(const o of a){const e=s._read(o.start,o.start+o.bytes.length);ct(e)?e.then(e=>{e?(oe(e.offset===o.start),o.resolve(e.bytes)):o.resolve(null)},e=>o.reject(e)):(oe(null===e),o.resolve(null))}}_dispose(){this._orchestrator.dispose(),this._sequentialBacking&&(this._sequentialBacking._disposed=!0,this._sequentialBacking._dispose())}}const da=/^bytes=(\d+)-(\d*)$/,ha=e=>{const t=da.exec(e.trim());if(!t)return null;const i=Number(t[1]),r=""===t[2]?null:Number(t[2]);return null!==r&&rthis._endIndex)return null;this._maxRequestedIndex=Math.max(this._maxRequestedIndex,t);const i=Re(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=t)break;const r=Math.max(e,i.start);r>n&&this._throwDueToCacheMiss();const a=Math.min(t,i.end);rn&&this._throwDueToCacheMiss();const{promise:a,resolve:o,reject:l}=Ae();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)this._pendingSlices.forEach(t=>t.reject(e)),this._pendingSlices.length=0;else{if(!this._handleUnhandledError)throw e;this._handleUnhandledError(e)}})),a}_throwDueToCacheMiss(){throw new Error(this._cacheMissErrorMessage)}_pull(){return Y(this,null,function*(){for(null!=this._reader||(this._reader=this._stream.getReader());this._currentIndex0;){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;for(const t of this._pendingSlices)t.reject(new gl);this._pendingSlices.length=0,this._cache.length=0,null==(e=this._reader)||e.cancel()}}const ma={fileSystem:(e,t)=>{const i=q(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=q(2,16);e=Math.max(0,Math.floor((e-r)/r)*r);for(const n of i){const i=8*q(2,20),r=Math.max((n.startPos+n.targetPos)/2,n.targetPos-i);if(dt(e,t,r,n.targetPos)){const e=n.targetPos-n.startPos,r=Math.ceil((e+1)/i)*i,s=q(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+oa)}}};class pa{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;oe(!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);oe(a<=e&&t<=o);let l=null;const c=Re(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=Re(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=o)break;if(r.end<=a)continue;const n=Math.max(a,r.start),s=Math.min(o,r.end);if(oe(n<=s),m=h.length&&(l={bytes:h,view:me(h),offset:e}),0===p.length)return oe(l),l;const{promise:g,resolve:k,reject:y}=Ae(),b=[];for(const v of p){const i=Math.max(e,v.start),r=Math.min(t,v.end);i===v.start&&r===v.end?b.push(v):ie.hole.start),i=-1!==t?this.queuedReads[t]:null;for(i&&v.start<=i.hole.end?(i.hole.end=Math.max(i.hole.end,v.end),i.strictTarget&&(i.strictTarget=e),T&&i.pendingSlices.push(T)):(t++,i={hole:{start:v.start,end:v.end},strictTarget:e,pendingSlices:T?[T]:[],age:this.nextAge++},this.queuedReads.splice(t,0,i));t+1i.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?g.catch(e=>{if(!this.disposed){if(!this.options.handleUnhandledError)throw e;this.options.handleUnhandledError(e)}}):(oe(h),l=g.then(t=>t&&{bytes:t,view:me(t),offset:e})),l}checkHoleAgainstWorker(e,t,i){const r=q(2,17);if(dt(t.start-r,t.start,e.currentPos,e.targetPos)){e.targetPos=Math.max(e.targetPos,t.end);for(let t=0;t=this.options.maxWorkerCount){let e=null,t=null;for(let i=0;i{if(e.running=!1,e.pendingSlices.length>0)e.pendingSlices.forEach(e=>e.reject(t)),e.pendingSlices.length=0;else if(!e.aborted&&!this.disposed){if(!this.options.handleUnhandledError)throw t;this.options.handleUnhandledError(t)}}).finally(()=>{if(!e.running&&this.queuedReads.length>0){let e=0;for(let r=1;re.targetPos&&(e.targetPos=e.currentPos,this.checkQueuedReadsAgainstWorker(e));for(let a=0;at.start&&(t.start=s),t.end<=t.start&&(i.holes.splice(e,1),e--)}0===i.holes.length&&(i.resolve(i.bytes),e.pendingSlices.splice(a,1),a--)}for(let a=0;ae){r.resolve(null),t.pendingSlices.splice(i,1),i--;break}}}for(let t=0;t=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=e&&(r.resolve(null),i.pendingSlices.splice(t,1),t--)}}}}signalWorkerStoppedRunning(e){e.running=!1,e.aborted||(e.pendingSlices.length=0)}onWorkerFinished(e){var t,i;const r=this.workers.indexOf(e);oe(-1!==r),e.running=!1,this.workers.splice(r,1),null==(i=(t=this.options).onIdleWorkerRemoved)||i.call(t,e),null===this.fileSize&&this.supplyFileSize(e.currentPos);for(const n of e.pendingSlices)n.resolve(null)}insertIntoCache(e){if(0===this.options.maxCacheSize)return;let t=Re(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=me(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=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=me(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;ithis._length)return null;const n=this._baseSource._read(this._offset+e,this._offset+t,this._offset+i,this._offset+r),s=e=>e?(e.offset-=this._offset,e):null;return ct(n)?n.then(s):s(n)}_dispose(){var e;null==(e=this._ref)||e.free()}ref(){return null!=this._ref||(this._ref=this._baseSource.ref()),super.ref()}}var ka=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},ya=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 ba=/^0[xX][0-9a-fA-F]+$/,Ta=/^data:.*;base64,/i;class va extends Gs{constructor(e,t,i,r){super(e.input,t,i),this.segments=[],this.nextLines=null,this.currentUpdateSegmentsPromise=null,this.streamHasEnded=!1,this.lastSegmentUpdateTime=-1/0,this.refreshInterval=5,this.rootPath=t,this.demuxer=e,this.nextLines=r}runUpdateSegments(){var e;return null!=(e=this.currentUpdateSegmentsPromise)?e:this.currentUpdateSegmentsPromise=(()=>Y(this,null,function*(){try{const e=this.getRemainingWaitTimeMs();e>0&&(yield Tt(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 Y(this,null,function*(){var e,t,i,r,n,s,a,o;let l=this.nextLines;if(this.nextLines=null,!l){const e={stack:[],error:void 0,hasError:!1};try{const t=ka(e,yield this.demuxer.input._getSourceUncached({path:this.rootPath,isRoot:!1}),!1),i=new kl(t.source),r=yield i.requestEntireFile();oe(r),l=Ol(r,r.length,{ignore:Xs}),t.source instanceof ia&&(this.rootPath=t.source.rootPath)}catch(x){e.error=x,e.hasError=!0}finally{ya(e)}}const c=!1!==(null==(e=this.input._formatOptions.hls)?void 0:e.offsetTimestampsByDateTime);let u=!1,d=0,h=null,f=null,m=null,p=0,g=null,k=null,y=null,b=null,T=null,v=null,w=!1,S=null!=(t=ce(this.segments))?t:null;const P=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}},I=e=>{p=e,S&&(oe(null!==S.sequenceNumber),S.sequenceNumber0&&null!==v&&(d=p*v),w=!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(Us)){const t=new $s(e.slice(11)),i=t.get("uri");if(!i)throw new Error("Invalid #EXT-X-MAP tag; missing URI attribute.");const r=t.get("byterange");let a=null;if(null!==r&&(a=P(r)),a&&null===a.offset)throw new Error("Invalid #EXT-X-MAP tag; BYTERANGE attribute must have a specified offset.");if(!S){const e={path:pt(this.rootPath,i),offset:null!=(n=null==a?void 0:a.offset)?n:0,length:null!=(s=null==a?void 0:a.length)?s: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:d,unixEpochTimestamp:h,firstSegment:null,sequenceNumber:null,location:e,duration:0,encryption:m,initSegment:null,lastProgramDateTimeSeconds:T}}f=null,null===b?y=null:b=null}else if(e.startsWith(qs)){const t=new $s(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(!ba.test(r))throw new Error(`Unsupported IV format '${r}'.`);let e=r.slice(2);e=e.padStart(32,"0"),i=new Uint8Array(Er);for(let t=0;t=8&&112===i[4]&&115===i[5]&&115===i[6]&&104===i[7]){const e=me(i).getUint32(0);r=vr(i.subarray(8,Math.min(e,i.length)))}}m={method:i,psshBox:r}}}}else if(e.startsWith(Ws)){const t=e.slice(22),i=Number(t);if(!Number.isInteger(i)||i<0)throw new Error(`Invalid EXT-X-MEDIA-SEQUENCE value '${t}'.`);I(i)}else if(e.startsWith(Hs)){const t=P(e.slice(17));if(null===t.offset){if(null===y)throw new Error("Invalid M3U8 file; #EXT-X-BYTERANGE without offset requires a previous byte range.");t.offset=y}b=t,y=t.offset+t.length}else if(e.startsWith(Vs)){if(S)continue;const t=e.slice(25),i=Date.parse(t);if(!Number.isFinite(i))continue;const r=i/1e3;if(T===r)continue;if(null===T&&this.segments.length>0){const e=ce(this.segments),t=r-(e.timestamp+e.duration);for(const i of this.segments)i.unixEpochTimestamp=i.timestamp+t,c&&(i.timestamp=i.unixEpochTimestamp)}T=r,h=r,c&&(d=r)}else if("#EXT-X-DISCONTINUITY"===e)g=null;else if(e.startsWith(js)){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,v=i}else{if("#EXT-X-ENDLIST"===e){this.streamHasEnded=!0;break}if(e.startsWith(Ks)){"vod"===e.slice(21).toLowerCase()&&(this.streamHasEnded=!0)}}}else{if("#EXTM3U"!==e)throw new Error("Invalid M3U8 file; expected first line to be #EXTM3U.");u=!0}}if(!u)throw new Error("Invalid M3U8 file; no #EXTM3U header.")})}getFirstSegment(){return Y(this,null,function*(){var e;return 0===this.segments.length&&(yield this.runUpdateSegments()),null!=(e=this.segments[0])?e:null})}getSegmentAt(e,t){return Y(this,null,function*(){0===this.segments.length&&(yield this.runUpdateSegments());let i=!!t.skipLiveWait&&this.getRemainingWaitTimeMs()>0;for(;;){const r=Re(this.segments,e,e=>e.timestamp);if(-1===r)return null;if(r0;for(;;){if(re.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=V(H({},this.input._formatOptions),{isobmff:V(H({},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=>wr(e,i))||(t=[...t,i]),this.input._formatOptions.isobmff.resolveKeyId(V(H({},e),{psshBoxes:t}))})})}),o=new ml({source:new na(r.location.path,e=>Y(this,null,function*(){var t,i;oe(e.isRoot);const n=V(H({},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;oe(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 o=((e,t,i)=>{let r=!1,n=0;const s=q(2,16),a=new Lr;return new ReadableStream({pull:o=>Y(null,null,function*(){r||(a.init(yield t()),r=!0);const l=s+16;let c=e.requestSliceRange(n,0,l);if(ct(c)&&(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=Tl(c,d),f=new Uint8Array(d);for(let e=0;e16)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 kl(t.source),()=>Y(this,null,function*(){const t={stack:[],error:void 0,hasError:!1};try{const i=ka(t,yield this.input._getSourceCached({path:e.keyUri,isRoot:!1},fl),!1),r=new kl(i.source),n=yield r.requestSlice(0,Er);if(!n)throw new Error("Invalid AES-128 key; expected at least 16 bytes of data.");return{key:Tl(n,Er),iv:e.iv}}catch(i){t.error=i,t.hasError=!0}finally{ya(t)}}),()=>{t.free()});s=new fa(o).ref()}else oe(!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 qa)),initInput:null!=s?s:void 0,formatOptions:a});o._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:o,age:this.nextInputCacheAge++});if(this.inputCache.length>4){const e=kt(this.inputCache,e=>e.age);oe(-1!==e),this.inputCache.splice(e,1)}return o}getLiveRefreshInterval(){return Y(this,null,function*(){return 0===this.getRemainingWaitTimeMs()&&(yield this.runUpdateSegments()),this.streamHasEnded?null:this.refreshInterval})}}class wa extends yr{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=(()=>Y(this,null,function*(){oe(this.input._rootSource instanceof ia);const e=yield this.input._reader.requestEntireFile();oe(e);const t=Ol(e,e.length,{ignore:Xs}),{rootPath:i}=this.input._rootSource,r=[],n=[];for(let u=1;u"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((e,t)=>Y(this,null,function*(){var r,o,l,c;const u=[],d=e.attributes.get("codecs");let h;if(d)h=d.split(",").map(e=>e.trim());else{const t=this.getSegmentedInputForPath(e.fullPath),i=yield t.getTrackBackings(),r=yield Promise.all(i.map(e=>Y(this,null,function*(){return{track:e,codec:yield e.getCodec()}})));h=yield Promise.all(r.filter(e=>null!==e.codec).map(e=>e.track.getDecoderConfig().then(e=>e.codec)))}const f=e.attributes.get("video"),m=e.attributes.get("audio"),p=h.some(e=>Ki.includes(or(e))),g=h.some(e=>$i.includes(or(e)));if(null!==f&&!p){if(!s.includes(f))throw new Error(`Invalid M3U8 file; variant stream references video group "${f}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===f&&"video"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}if(null!==m&&!g){if(!a.includes(m))throw new Error(`Invalid M3U8 file; variant stream references audio group "${m}" which is not defined in any #EXT-X-MEDIA tags.`);const e=n.find(e=>{const t=e.attributes.get("group-id"),i=e.attributes.get("type");return t===m&&"audio"===i.toLowerCase()});e:if(e){const t=e.attributes.get("uri");if(null===t)break e;const r=pt(i,t),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});oe(null!==a),h.push(a)}}h=[...new Set(h)];let k=null,y=null;const b=e.attributes.getAsNumber("bandwidth");oe(null!==b);const T=e.attributes.getAsNumber("average-bandwidth"),v=e.attributes.get("name");for(const i of h){const d=or(i);if(null!==d)if(Ki.includes(d)){if(null!==k)throw new Error("Unsupported M3U8 file; multiple video codecs found in the CODECS attribute of a variant stream.");k=i;const a=e.attributes.get("video");if(null===a){const i=e.attributes.get("resolution");let r=null,n=null;if(i){const e=i.match(/^(\d+)x(\d+)$/);e&&(r=Number(e[1]),n=Number(e[2]))}u.push({id:-1,demuxer:this,backingTrack:null,default:!0,autoselect:!0,languageCode:We,lineNumber:e.lineNumber,fullPath:e.fullPath,fullCodecString:k,pairingMask:BigInt("1")<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 i of n){const n=i.attributes.get("group-id"),s=i.attributes.get("type");if(n!==r||"audio"!==s.toLowerCase())continue;const a=null!=(l=i.attributes.get("channels"))?l:e.attributes.get("channels"),o=null!==a?Number(a.split("/")[0]):null;u.push({id:-1,demuxer:this,backingTrack:null,default:xa(i.attributes),autoselect:xa(i.attributes)||Ca(i.attributes),languageCode:Ba(i.attributes.get("language")),lineNumber:i.lineNumber,fullPath:null!=(c=i.fullPath)?c:e.fullPath,fullCodecString:y,pairingMask:BigInt("1")<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===We&&(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 Pa(u)):this.trackBackings.push(new Ia(u));this.internalTracks=l}))()}getTrackBackings(){return Y(this,null,function*(){return yield this.readMetadata(),oe(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 va(this,e,i,null),this.segmentedInputs.push(t),t}getMetadataTags(){return Y(this,null,function*(){return{}})}getMimeType(){return Y(this,null,function*(){return Ds})}dispose(){if(this.segmentedInputs){for(const e of this.segmentedInputs)e.dispose();this.segmentedInputs.length=0}}}class Sa{constructor(e){this.internalTrack=e,this.hydrationPromise=null}hydrate(){var e;return null!=(e=this.hydrationPromise)?e:this.hydrationPromise=(()=>Y(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 Pa){for(const r of i)if((yield r.getCodec())===this.getCodec()){t=r;break}}else{oe(this instanceof Ia);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 V(H({},Ct),{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(){oe(this.internalTrack.demuxer.internalTracks);const e=this.internalTrack.info.type;let t=0;for(const i of this.internalTrack.demuxer.internalTracks)if(i.info.type===e&&t++,i===this.internalTrack)break;return t}getTimeResolution(){return this.delegate(()=>this.internalTrack.backingTrack.getTimeResolution())}isRelativeToUnixEpoch(){return this.delegate(()=>this.internalTrack.backingTrack.isRelativeToUnixEpoch())}getUnixTimeForTimestamp(e){return this.delegate(()=>this.internalTrack.backingTrack.getUnixTimeForTimestamp(e))}getBitrate(){return this.internalTrack.peakBitrate}getAverageBitrate(){return this.internalTrack.averageBitrate}getDurationFromMetadata(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getDurationFromMetadata(e)})}getLiveRefreshInterval(){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getLiveRefreshInterval()})}getHasOnlyKeyPackets(){return this.internalTrack.hasOnlyKeyPackets||null}getFirstPacket(e){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getFirstPacket(e)})}getPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getPacket(e,t)})}getKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getKeyPacket(e,t)})}getNextPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextPacket(e,t)})}getNextKeyPacket(e,t){return Y(this,null,function*(){return yield this.hydrate(),this.internalTrack.backingTrack.getNextKeyPacket(e,t)})}}class Pa extends Sa{constructor(e){super(e)}get backingVideoTrack(){return this.internalTrack.backingTrack}getType(){return"video"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getColorSpace()})}canBeTransparent(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.canBeTransparent()})}getMetadataCodecParameterString(){return this.backingVideoTrack?null:this.internalTrack.fullCodecString}getDecoderConfig(){return Y(this,null,function*(){return yield this.hydrate(),this.backingVideoTrack.getDecoderConfig()})}}class Ia extends Sa{constructor(e){super(e)}get backingAudioTrack(){return this.internalTrack.backingTrack}getType(){return"audio"}getCodec(){return or(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 Y(this,null,function*(){return yield this.hydrate(),this.backingAudioTrack.getDecoderConfig()})}}const xa=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}".`)},Ca=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}".`)},Ba=e=>{if(null===e)return We;const t=e.split("-")[0];return t||We};class Ea{constructor(){this._isIsobmff=!1}}class _a extends Ea{constructor(){super(...arguments),this._isIsobmff=!0}_getMajorBrand(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return null;t.skip(4);const i=Nl(t,4);return"ftyp"!==i&&"styp"!==i?null:Nl(t,4)})}_createDemuxer(e){return new zr(e)}}class Ra extends _a{_canReadInput(e){return Y(this,null,function*(){const t=yield this._getMajorBrand(e);if(null!==t)return"qt "!==t;let i=0;for(let r=0;r<10;r++){let t=e._reader.requestSlice(i,8);if(ct(t)&&(t=yield t),!t)return!1;let r=Cl(t),n=8;if(1===r){let t=e._reader.requestSlice(i+8,8);if(ct(t)&&(t=yield t),!t)return!1;r=Rl(t),n=16}if(r8)return!1;if(hn(i,r)!==nn.EBML)return!1;const n=mn(i);if("number"!==typeof n)return!1;let s=e._reader.requestSlice(i.filePos,n);if(ct(s)&&(s=yield s),!s)return!1;const a=i.filePos;for(;s.filePos<=a+n-2;){const e=pn(s);if(!e)break;const{id:i,size:r}=e,n=s.filePos;if(void 0===r)return!1;switch(i){case nn.EBMLVersion:if(1!==hn(s,r))return!1;break;case nn.EBMLReadVersion:if(1!==hn(s,r))return!1;break;case nn.DocType:if(gn(s,r)!==t)return!1;break;case nn.DocTypeVersion:if(hn(s,r)>4)return!1}s.filePos=n+r}return!0})}_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"matroska")}_createDemuxer(e){return new Vn(e)}get name(){return"Matroska"}get mimeType(){return"video/x-matroska"}}class Ma extends Aa{_canReadInput(e){return this.isSupportedEBMLOfDocType(e,"webm")}get name(){return"WebM"}get mimeType(){return"video/webm"}}class Da extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}const i=yield $n(e._reader,t,t+4096);if(!i)return!1;const r=i.header,n=hr(r.mpegVersionId,r.channel);let s=e._reader.requestSlice(i.startPos+n,4);if(ct(s)&&(s=yield s),!s)return!1;const a=Cl(s);if(a===ur||a===dr)return!0;t=i.startPos+i.header.totalSize;const o=yield $n(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 Gn(e)}get name(){return"MP3"}get mimeType(){return"audio/mpeg"}}class Na extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,12);if(ct(t)&&(t=yield t),!t)return!1;const i=Nl(t,4);if("RIFF"!==i&&"RIFX"!==i&&"RF64"!==i)return!1;t.skip(4);return"WAVE"===Nl(t,4)})}_createDemuxer(e){return new ds(e)}get name(){return"WAVE"}get mimeType(){return"audio/wav"}}class Oa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,4);return ct(t)&&(t=yield t),!!t&&"OggS"===Nl(t,4)})}_createDemuxer(e){return new ss(e)}get name(){return"Ogg"}get mimeType(){return"application/ogg"}}class La extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSlice(t,4);return ct(i)&&(i=yield i),!!i&&"fLaC"===Nl(i,4)})}get name(){return"FLAC"}get mimeType(){return"audio/flac"}_createDemuxer(e){return new ys(e)}}class za extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=0;for(;;){let i=e._reader.requestSlice(t,Hl);if(ct(i)&&(i=yield i),!i)break;const r=Xl(i);if(!r)break;t=i.filePos+r.size}let i=e._reader.requestSliceRange(t,7,9);if(ct(i)&&(i=yield i),!i)return!1;const r=ms(i);if(!r)return!1;if(t+=r.frameLength,i=e._reader.requestSliceRange(t,7,9),ct(i)&&(i=yield i),!i)return!1;const n=ms(i);return!!n&&(r.objectType===n.objectType&&r.samplingFrequencyIndex===n.samplingFrequencyIndex&&r.channelConfiguration===n.channelConfiguration)})}_createDemuxer(e){return new gs(e)}get name(){return"ADTS"}get mimeType(){return"audio/aac"}}class Ua extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,205);if(ct(t)&&(t=yield t),!t)return!1;const i=Tl(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 xs(e)}get name(){return"MPEG Transport Stream"}get mimeType(){return"video/MP2T"}}class qa extends Ea{_canReadInput(e){return Y(this,null,function*(){let t=e._reader.requestSlice(0,7);if(ct(t)&&(t=yield t),!t)return!1;if(!("#EXTM3U"===Nl(t,7)))return!1;if(!(e._rootSource instanceof ia))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 wa(e)}get name(){return"HTTP Live Streaming (HLS)"}get mimeType(){return Ds}}const Wa=new Ra,Ha=new Fa,Va=new Aa,ja=new Ma,Ka=new Da,Xa=new Na,$a=new Oa,Ga=new za,Qa=new La,Ya=new Ua,Ja=new qa,Za=[Ja,Wa,Ha,Va,ja,Xa,$a,Qa,Ka,Ga,Ya],eo=[Ja,Wa,Ha,Ka,Ga,Ya];var to=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});ft();let io=-1/0,ro=-1/0,no=null;"undefined"!==typeof FinalizationRegistry&&(no=new FinalizationRegistry(e=>{const t=performance.now();"video"===e.type?(t-io>=1e3&&(Pt._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."),io=t),"undefined"!==typeof VideoFrame&&e.data instanceof VideoFrame&&e.data.close()):(t-ro>=1e3&&(Pt._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."),ro=t),"undefined"!==typeof AudioData&&e.data instanceof AudioData&&e.data.close())}));class so{constructor(){this._referenceCount=0,this._lastAllocationBuffer=null}}const ao=["I420","I420P10","I420P12","I420A","I420AP10","I420AP12","I422","I422P10","I422P12","I422A","I422AP10","I422AP12","I444","I444P10","I444P12","I444A","I444AP10","I444AP12","NV12","RGBA","RGBX","BGRA","BGRX"],oo=new Set(ao);class lo{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(Qe*this.timestamp)}get microsecondDuration(){return Math.trunc(Qe*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,y,b,T,v,w,S,P,I,x,C,B,E,_,R,F;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||!oo.has(t.format))throw new TypeError("init.format must be one of: "+ao.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&&bt(t.visibleRect,"init.visibleRect"),void 0!==t.displayWidth&&(!Number.isInteger(t.displayWidth)||t.displayWidth<=0))throw new TypeError("init.displayWidth, when provided, must be a positive integer.");if(void 0!==t.displayHeight&&(!Number.isInteger(t.displayHeight)||t.displayHeight<=0))throw new TypeError("init.displayHeight, when provided, must be a positive integer.");if(void 0!==t.displayWidth!==(void 0!==t.displayHeight))throw new TypeError("init.displayWidth and init.displayHeight must be either both provided or both omitted.");this.format=t.format,this.rotation=null!=(i=t.rotation)?i:0,this.timestamp=t.timestamp,this.duration=null!=(r=t.duration)?r:0;const m=null!=(n=t.layout)?n:bo(t.format,t.codedWidth,t.codedHeight);let p=null!=(s=t.colorSpace)?s:null;null===p&&(p="RGBA"===this.format||"RGBX"===this.format||"BGRA"===this.format||"BGRX"===this.format?{primaries:"bt709",transfer:"iec61966-2-1",matrix:"rgb",fullRange:!0}:{primaries:"bt709",transfer:"bt709",matrix:"bt709",fullRange:!1}),this.visibleRect={left:null!=(o=null==(a=t.visibleRect)?void 0:a.left)?o:0,top:null!=(c=null==(l=t.visibleRect)?void 0:l.top)?c:0,width:null!=(d=null==(u=t.visibleRect)?void 0:u.width)?d:t.codedWidth,height:null!=(f=null==(h=t.visibleRect)?void 0:h.height)?f:t.codedHeight},void 0!==t.displayWidth?(this.squarePixelWidth=this.rotation%180===0?t.displayWidth:t.displayHeight,this.squarePixelHeight=this.rotation%180===0?t.displayHeight:t.displayWidth):(this.squarePixelWidth=this.visibleRect.width,this.squarePixelHeight=this.visibleRect.height),this._data=t._doNotCopy?fe(e):fe(e).slice(),this._layout=m,this.colorSpace=new mo(p)}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)&&bt(t.visibleRect,"init.visibleRect"),this._data=e,this._layout=null,this.format=e.format,this.visibleRect={left:null!=(p=null==(m=e.visibleRect)?void 0:m.x)?p:0,top:null!=(k=null==(g=e.visibleRect)?void 0:g.y)?k:0,width:null!=(b=null==(y=e.visibleRect)?void 0:y.width)?b:e.codedWidth,height:null!=(v=null==(T=e.visibleRect)?void 0:T.height)?v:e.codedHeight},this.rotation=null!=(w=null==t?void 0:t.rotation)?w:0,this.squarePixelWidth=e.displayWidth,this.squarePixelHeight=e.displayHeight,this.timestamp=null!=(S=null==t?void 0:t.timestamp)?S:e.timestamp/1e6,this.duration=null!=(I=null==t?void 0:t.duration)?I:(null!=(P=e.duration)?P:0)/1e6,this.colorSpace=new mo(e.colorSpace)}else if("undefined"!==typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!==typeof SVGImageElement&&e instanceof SVGImageElement||"undefined"!==typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!==typeof HTMLVideoElement&&e instanceof HTMLVideoElement||"undefined"!==typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!==typeof OffscreenCanvas&&e instanceof OffscreenCanvas){if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(void 0!==t.visibleRect&&bt(t.visibleRect,"init.visibleRect"),"undefined"!==typeof VideoFrame)return new lo(new VideoFrame(e,{timestamp:Math.trunc(t.timestamp*Qe),duration:Math.trunc((null!=(x=t.duration)?x:0)*Qe)||void 0,visibleRect:t.visibleRect&&{x:t.visibleRect.left,y:t.visibleRect.top,width:t.visibleRect.width,height:t.visibleRect.height}}),t);let i=0,r=0;if("naturalWidth"in e?(i=e.naturalWidth,r=e.naturalHeight):"videoWidth"in e?(i=e.videoWidth,r=e.videoHeight):"width"in e&&(i=Number(e.width),r=Number(e.height)),!i||!r)throw new TypeError("Could not determine dimensions.");const n=null!=(C=t.visibleRect)?C:{left:0,top:0,width:i,height:r},s=new OffscreenCanvas(n.width,n.height),a=s.getContext("2d",{alpha:nt(),willReadFrequently:!0});if(!a)throw new Error("OffscreenCanvas must have support for the '2d' context in order to create a VideoSample from this data.");a.drawImage(e,-n.left,-n.top),this._data=s,this._layout=null,this.format="RGBX",this.visibleRect={left:0,top:0,width:n.width,height:n.height},this.squarePixelWidth=n.width,this.squarePixelHeight=n.height,this.rotation=null!=(B=t.rotation)?B:0,this.timestamp=t.timestamp,this.duration=null!=(E=t.duration)?E:0,this.colorSpace=new mo({matrix:"rgb",primaries:"bt709",transfer:"iec61966-2-1",fullRange:!0})}else{if(!(e instanceof so))throw new TypeError("Invalid data type: Must be a BufferSource, CanvasImageSource, or VideoSampleResource.");if(!t||"object"!==typeof t)throw new TypeError("init must be an object.");if(void 0!==t.rotation&&![0,90,180,270].includes(t.rotation))throw new TypeError("init.rotation, when provided, must be 0, 90, 180, or 270.");if(!Number.isFinite(t.timestamp))throw new TypeError("init.timestamp must be a number.");if(void 0!==t.duration&&(!Number.isFinite(t.duration)||t.duration<0))throw new TypeError("init.duration, when provided, must be a non-negative number.");if(this._data=e,e._referenceCount++,this.format=e.getFormat(),null!==this.format&&!ao.includes(this.format))throw new TypeError("getFormat() must return a VideoSamplePixelFormat or null.");if(this.visibleRect={left:0,top:0,width:e.getCodedWidth(),height:e.getCodedHeight()},!Number.isInteger(this.visibleRect.width)||this.visibleRect.width<=0)throw new TypeError("getCodedWidth() must return a positive integer.");if(!Number.isInteger(this.visibleRect.height)||this.visibleRect.height<=0)throw new TypeError("getCodedHeight() must return a positive integer.");if(this.squarePixelWidth=e.getSquarePixelWidth(),!Number.isInteger(this.squarePixelWidth)||this.squarePixelWidth<=0)throw new TypeError("getSquarePixelWidth() must return a positive integer.");if(this.squarePixelHeight=e.getSquarePixelHeight(),!Number.isInteger(this.squarePixelHeight)||this.squarePixelHeight<=0)throw new TypeError("getSquarePixelHeight() must return a positive integer.");this.rotation=null!=(_=t.rotation)?_:0,this.timestamp=t.timestamp,this.duration=null!=(R=t.duration)?R:0,this.colorSpace=e.getColorSpace()}this.encodeOptions=null!=(F=null==t?void 0:t.encodeOptions)?F:{},this.pixelAspectRatio=yt({num:this.squarePixelWidth*this.codedHeight,den:this.squarePixelHeight*this.codedWidth}),null==no||no.register(this,{type:"video",data:this._data},this)}clone(){if(this._closed)throw new Error("VideoSample is closed.");return oe(null!==this._data),this._data instanceof so?new lo(this._data,{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):po(this._data)?new lo(this._data.clone(),{timestamp:this.timestamp,duration:this.duration,rotation:this.rotation,encodeOptions:this.encodeOptions}):this._data instanceof Uint8Array?(oe(this._layout),new lo(this._data,{format:this.format,layout:this._layout,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions,_doNotCopy:!0})):new lo(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.timestamp,duration:this.duration,colorSpace:this.colorSpace,rotation:this.rotation,visibleRect:this.visibleRect,displayWidth:this.displayWidth,displayHeight:this.displayHeight,encodeOptions:this.encodeOptions})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof so?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):po(this._data)?this._data.close():this._data=null,this._closed=!0)}allocationSize(e={}){var t;if(yo(e),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(t=e.format)?t:this.format))throw new Error("Cannot get allocation size when format is null.");if(po(this._data))return this._data.allocationSize(e);return vo(this,e).allocationSize}copyTo(e){return Y(this,arguments,function*(e,t={}){var i,r;if(!Ie(e))throw new TypeError("destination must be an ArrayBuffer or an ArrayBuffer view.");if(yo(t),this._closed)throw new Error("VideoSample is closed.");if(null==(null!=(i=t.format)?i:this.format))throw new Error("Cannot copy video sample data when format is null.");if(oe(null!==this._data),po(this._data))return this._data.copyTo(e,t);if(t.format&&!["RGBA","RGBX","BGRA","BGRX"].includes(this.format)&&["RGBA","RGBX","BGRA","BGRX"].includes(t.format)){if(!(this._data instanceof so)){if("undefined"===typeof VideoFrame)throw new Error("For this sample, converting from a non-RGB to an RGB format requires VideoFrame to be defined.");const i=this.toVideoFrame(),r=yield i.copyTo(e,t);return i.close(),r}{const i={stack:[],error:void 0,hasError:!1};try{const n=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}(i,yield this._data.toRgbSample({timestamp:this.timestamp,duration:this.duration,rotation:this.rotation},null!=(r=t.colorSpace)?r:"srgb"),!1);if(!(n instanceof lo))throw new TypeError("toRgbSample() must return a VideoSample.");if(!["RGBA","RGBX","BGRA","BGRX"].includes(n.format))throw new Error(`Sample returned by toRgbSample was expected to have an RGB format, got '${n.format}' instead.`);return yield n.copyTo(e,t)}catch(u){i.error=u,i.hasError=!0}finally{to(i)}}}const n=vo(this,t);oe(this.format);const s=fe(e);if(s.byteLength!(e.data instanceof Uint8Array)||!Number.isInteger(e.stride)||e.stride<0))throw new TypeError('getDataPlanes() must return an array of objects with a Uint8Array "data" property and a non-negative integer "stride" property.');o=e}else if(this._data instanceof Uint8Array)oe(this._layout),oe(this._layout.length===a.length),o=this._layout.map((e,t)=>{const i=Math.ceil(this.codedHeight/a[t].heightDivisor);return{data:this._data.subarray(e.offset,e.offset+e.stride*i),stride:e.stride}});else{const e=this._data.getContext("2d");oe(e);const t=e.getImageData(0,0,this.codedWidth,this.codedHeight);o=[{data:fe(t.data),stride:4*this.codedWidth}]}const l=[],c=a.length;for(let d=0;di.byteLength)throw new Error("Source buffer OOB read.");if(a+c>s.byteLength)throw new Error("Destination buffer OOB write.");const n=i.subarray(r,r+c);s.set(n,a),r+=t,a+=e.destinationStride}l.push(u)}if(void 0!==t.format){const e=this.format.startsWith("RGB")!==t.format.startsWith("RGB"),i=this.format.includes("X")&&t.format.includes("A");if(e||i)for(let t=0;te+t.data.byteLength,0),i=new Uint8Array(t);let r=0;const n=[];for(const s of e)i.set(s.data,r),n.push(r),r+=s.data.byteLength;return new VideoFrame(i,{format:this.format,layout:e.map((e,t)=>({offset:n[t],stride:e.stride})),codedWidth:this.codedWidth,codedHeight:this.codedHeight,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})}return po(this._data)?new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0}):this._data instanceof Uint8Array?(oe(this._layout),new VideoFrame(this._data,{format:this.format,codedWidth:this.codedWidth,codedHeight:this.codedHeight,layout:this._layout,timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0,colorSpace:this.colorSpace,visibleRect:this.visibleRect,displayWidth:this.squarePixelWidth,displayHeight:this.squarePixelHeight})):new VideoFrame(this._data,{timestamp:this.microsecondTimestamp,duration:this.microsecondDuration||void 0})}draw(e,t,i,r,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&&ko(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=t.crop;T&&(T=go(T,m,p));const{sx:v,sy:w,sWidth:S,sHeight:P}=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 I=f%180===0?1:y/b;e.translate(d/2,h/2),e.rotate(f*Math.PI/180),e.scale(1/I,I),e.translate(-d/2,-h/2),e.drawImage(this.toCanvasImageSource(),v,w,S,P,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}}_drawWithFitAndMipmapping(e,t,i){const r=e.width,n=e.height,[s,a]=i.rotation%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth],o=i.crop?i.crop.width:s,l=i.crop?i.crop.height:a;let c=0;2*r0?fo(u,d):{canvas:e,context:t,isNew:i.targetIsFresh};f.imageSmoothingQuality="high",i.fillBlack?(f.fillStyle="black",f.fillRect(0,0,u,d)):m||f.clearRect(0,0,u,d),this.drawWithFit(f,{fit:i.fit,rotation:i.rotation,crop:i.crop}),f.globalCompositeOperation="copy";for(let p=c;p>1;p--){const e=r*q(2,p),t=n*q(2,p);f.drawImage(h,0,0,e,t,0,0,e/2,t/2)}f.globalCompositeOperation="source-over",c>0&&(t.imageSmoothingQuality="high",t.globalCompositeOperation="copy",t.drawImage(h,0,0,2*r,2*n,0,0,r,n),t.globalCompositeOperation="source-over")}toCanvasImageSource(){if(this._closed)throw new Error("VideoSample is closed.");if(oe(null!==this._data),this._data instanceof so||this._data instanceof Uint8Array){const e=this.toVideoFrame();return queueMicrotask(()=>e.close()),e}return this._data}transform(e){return Y(this,null,function*(){var t,i,r,n,s;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.width&&(!Number.isInteger(e.width)||e.width<=0))throw new TypeError("options.width, when provided, must be a positive integer.");if(void 0!==e.height&&(!Number.isInteger(e.height)||e.height<=0))throw new TypeError("options.height, when provided, must be a positive integer.");if(void 0!==e.roundDimensionsTo&&(!Number.isInteger(e.roundDimensionsTo)||e.roundDimensionsTo<=0))throw new TypeError("options.roundDimensionsTo, when provided, must be a positive integer.");if(void 0!==e.fit&&!["fill","contain","cover"].includes(e.fit))throw new TypeError('options.fit, when provided, must be one of "fill", "contain", or "cover".');if(void 0!==e.width&&void 0!==e.height&&void 0===e.fit)throw new TypeError("When both options.width and options.height are provided, options.fit must also be provided.");if(void 0!==e.rotate&&![0,90,180,270].includes(e.rotate))throw new TypeError("options.rotate, when provided, must be 0, 90, 180 or 270.");if(void 0!==e.crop&&ko(e.crop,"options."),void 0!==e.alpha&&!["keep","discard"].includes(e.alpha))throw new TypeError("options.alpha, when provided, must be 'keep' or 'discard'.");const a=le(this.rotation+(null!=(t=e.rotate)?t:0)),[o,l]=a%180===0?[this.squarePixelWidth,this.squarePixelHeight]:[this.squarePixelHeight,this.squarePixelWidth];let c=e.crop;c&&(c=go(c,o,l));const u=c?c.width:o,d=c?c.height:l,h=u/d;let f,m;void 0!==e.width&&void 0===e.height?(f=e.width,m=f/h):void 0===e.width&&void 0!==e.height?(m=e.height,f=m*h):void 0!==e.width&&void 0!==e.height?(f=e.width,m=e.height):(f=u,m=d),f=Ve(f,null!=(i=e.roundDimensionsTo)?i:1),m=Ve(m,null!=(r=e.roundDimensionsTo)?r:1);const p={width:f,height:m,fit:null!=(n=e.fit)?n:"fill",rotation:a,crop:null!=c?c:{left:0,top:0,width:o,height:l},alpha:null!=(s=e.alpha)?s:"keep"};for(const e of co){let t=e(this,p);if(ct(t)&&(t=yield t),null!==t)return t}const{canvas:g,context:k,isNew:y}=fo(p.width,p.height);return this._drawWithFitAndMipmapping(g,k,{fit:p.fit,rotation:p.rotation,crop:p.crop,targetIsFresh:y,fillBlack:"discard"===p.alpha}),new lo(g,{timestamp:this.timestamp,duration:this.duration,rotation:0})})}setRotation(e){if(![0,90,180,270].includes(e))throw new TypeError("newRotation must be 0, 90, 180, or 270.");this.rotation=e}setTimestamp(e){if(!Number.isFinite(e))throw new TypeError("newTimestamp must be a number.");this.timestamp=e}setDuration(e){if(!Number.isFinite(e)||e<0)throw new TypeError("newDuration must be a non-negative number.");this.duration=e}setEncodeOptions(e){if(!e||"object"!==typeof e)throw new TypeError("newEncodeOptions must be an object.");this.encodeOptions=e}[Symbol.dispose](){this.close()}}const co=[],uo=[];let ho=0;const fo=(e,t)=>{for(const n of uo)if(n.canvas.width===e&&n.canvas.height===t)return n.age=ho++,{canvas:n.canvas,context:n.context,isNew:!1};let i;if("undefined"!==typeof OffscreenCanvas)i=new OffscreenCanvas(e,t);else{if("undefined"===typeof window||"undefined"===typeof document)throw new Error("Cannot transform VideoSamples in this environment. Either run in an environment with OffscreenCanvas or HTMLCanvasElement, or supply a custom VideoSample transformer using registerVideoSampleTransformer().");i=document.createElement("canvas"),i.width=e,i.height=t}const r=i.getContext("2d",{alpha:!0,willReadFrequently:!1});if(!r)throw new Error("The '2d' canvas context is required to transform VideoSamples. Register a custom transformer using registerVideoSampleTransformer to work around this limitation.");return uo.length>=3&&uo.splice(kt(uo,e=>e.age),1),uo.push({canvas:i,context:r,age:ho++}),{canvas:i,context:r,isNew:!0}};class mo{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(ke);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(be);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(ve);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 po=e=>"undefined"!==typeof VideoFrame&&e instanceof VideoFrame,go=(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 oe(s>=0),oe(a>=0),{left:r,top:n,width:s,height:a}},ko=(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.")},yo=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.")}},bo=(e,t,i)=>{const r=To(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},To=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:Oe(e),oe(!1)}},vo=(e,t)=>{const i={left:0,top:0,width:e.codedWidth,height:e.codedHeight},r=t.rect,n=wo(i,r,e.codedWidth,e.codedHeight,e.format),s=t.layout;let a;if(t.format&&t.format!==e.format){if(!["RGBA","RGBX","BGRA","BGRX"].includes(t.format))throw new Error("NotSupportedError: Invalid destination format.");a=t.format}else a=e.format;return Po(n,a,s)},wo=(e,t,i,r,n)=>{const s=H({},e);if(void 0!==t){if(0===t.width||0===t.height)throw new TypeError("visibleRect dimensions cannot be zero.");if((t.x||0)+(t.width||0)>i)throw new TypeError("visibleRect exceeds codedWidth.");if((t.y||0)+(t.height||0)>r)throw new TypeError("visibleRect exceeds codedHeight.");s.x=t.x||0,s.y=t.y||0,s.width=t.width||0,s.height=t.height||0}if(!So(n,s))throw new TypeError("visibleRect alignment is invalid for the format.");return s},So=(e,t)=>{if(null===e)return!0;const i=To(e);for(let r=0;r{const r=To(t),n=r.length;if(void 0!==i&&i.length!==n)throw new TypeError(`Layout must have ${n} planes.`);let s=0;const a=[],o=[];for(let l=0;l4294967295)throw new TypeError("Allocation size exceeds limit.");o.push(h),s=Math.max(s,h);for(let e=0;e 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/(Bo(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*Bo(this.format);if(i.byteLength=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=Bo(r),o=Eo(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(!Ie(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&&!Io.has(t.format))throw new TypeError("Invalid format.");if(void 0!==t.frameOffset&&(!Number.isInteger(t.frameOffset)||t.frameOffset<0))throw new TypeError("frameOffset must be a non-negative integer.");if(void 0!==t.frameCount&&(!Number.isInteger(t.frameCount)||t.frameCount<0))throw new TypeError("frameCount must be a non-negative integer.");if(this._closed)throw new Error("AudioSample is closed.");const{format:i,frameCount:r,frameOffset:n}=t;let{planeIndex:s}=t,a=this.format;const o=null!=i?i:this.format;if(!o)throw new Error("Destination format not determined");const l=this.numberOfFrames,c=this.numberOfChannels,u=null!=n?n:0;if(u>=l)throw new RangeError("frameOffset out of range");const d=void 0!==r?r:l-u;if(d>l-u)throw new RangeError("frameCount out of range");const h=Bo(o),f=Eo(o);if(f&&s>=c)throw new RangeError("planeIndex out of range");if(!f&&0!==s)throw new RangeError("planeIndex out of range");const m=(f?d:d*c)*h;if(e.byteLength2&&o!==a)return void Ao(this._data,p,a,o,c,s,u,d);try{return void this._data.copyTo(e,{planeIndex:s,frameOffset:u,frameCount:d,format:o})}catch(w){if("f32-planar"===o)throw w;a="f32-planar"}}const k=_o(a),y=Bo(a),b=Eo(a);let T;if(this._data instanceof xo){const e=e=>{const t=this._data.getDataPlane(e);if(!(t instanceof Uint8Array))throw new TypeError("getDataPlane() must return a Uint8Array.");const i=l*y*(b?1:c);if(t.byteLength!==i)throw new TypeError(`Data plane ${e} has invalid size. Expected exactly ${i} bytes, got ${t.byteLength} bytes.`);return t};if(b)if(f)T=e(s),s=0;else{T=new Uint8Array(l*y*c);for(let t=0;tthis.numberOfFrames)throw new RangeError("startFrame out of range.");if(t>this.numberOfFrames)throw new RangeError("endFrame out of range.");if(t0)for(let r=0;r0&&this.copyTo(n,{planeIndex:0,format:this.format,frameOffset:e,frameCount:i});return new Co({data:n,format:this.format,sampleRate:this.sampleRate,numberOfChannels:this.numberOfChannels,timestamp:this.timestamp+e/this.sampleRate})}close(){this._closed||(null==no||no.unregister(this),this._data instanceof xo?(this._data._referenceCount--,0===this._data._referenceCount&&this._data.close()):Fo(this._data)?this._data.close():this._data=new Uint8Array(0),this._closed=!0)}toAudioData(){if(this._closed)throw new Error("AudioSample is closed.");return this._data instanceof xo?this._createAudioDataFromData():Fo(this._data)?this._data.timestamp===this.microsecondTimestamp?this._data.clone():this._createAudioDataFromData():new AudioData({format:this.format,sampleRate:this.sampleRate,numberOfFrames:this.numberOfFrames,numberOfChannels:this.numberOfChannels,timestamp:this.microsecondTimestamp,data:this._data.buffer instanceof ArrayBuffer?this._data.buffer:this._data.slice()})}_createAudioDataFromData(){if(Eo(this.format)){const e=this.allocationSize({planeIndex:0,format:this.format}),t=new ArrayBuffer(e*this.numberOfChannels);for(let i=0;i0;){const n=Math.min(s,o),l=new Float32Array(i*n);for(let t=0;t0;){const n=Math.min(s,o),c=new Float32Array(i*n);for(let t=0;t{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")}},Eo=e=>{switch(e){case"u8-planar":case"s16-planar":case"s32-planar":case"f32-planar":return!0;default:return!1}},_o=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)}},Ro=e=>{switch(e){case"u8":case"u8-planar":return(e,t,i)=>e.setUint8(t,qe(127.5*(i+1),0,255));case"s16":case"s16-planar":return(e,t,i)=>e.setInt16(t,qe(Math.round(32767*i),-32768,32767),!0);case"s32":case"s32-planar":return(e,t,i)=>e.setInt32(t,qe(Math.round(2147483647*i),-2147483648,2147483647),!0);case"f32":case"f32-planar":return(e,t,i)=>e.setFloat32(t,i,!0)}},Fo=e=>"undefined"!==typeof AudioData&&e instanceof AudioData,Ao=(e,t,i,r,n,s,a,o)=>{const l=_o(i),c=Ro(r),u=Bo(i),d=Bo(r),h=Eo(i);if(Eo(r))if(h){const r=new ArrayBuffer(o*u),n=me(r);e.copyTo(r,{planeIndex:s,frameOffset:a,frameCount:o,format:i});for(let e=0;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.")},Oo=e=>{if(!mt(e))throw new TypeError("timestamp must be a number.")},Lo=(e,t,i)=>i.verifyKeyPackets?t.then(t=>Y(null,null,function*(){if(!t||"delta"===t.type)return t;const i=yield e.determinePacketType(t);return i&&(t.type=i),t})):t;class zo{constructor(e){if(!(e instanceof el))throw new TypeError("track must be an InputTrack.");this._track=e}getFirstPacket(){return Y(this,arguments,function*(e={}){if(No(e),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getFirstPacket(e),e)})}getFirstKeyPacket(){return Y(this,arguments,function*(e={}){No(e);const t=yield this.getFirstPacket(e);return t?"key"===t.type?t:this.getNextKeyPacket(t,e):null})}getPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getPacket(e,t),t)})}getNextPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;return Lo(this._track,this._track._backing.getNextPacket(e,t),t)})}getKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(Oo(e),No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getKeyPacket(e,t);const i=yield this._track._backing.getKeyPacket(e,t);if(!i)return i;oe("key"===i.type);return"delta"===(yield this._track.determinePacketType(i))?this.getKeyPacket(i.timestamp-1/(yield this._track.getTimeResolution()),t):i})}getNextKeyPacket(e){return Y(this,arguments,function*(e,t={}){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");if(No(t),this._track.input._disposed)throw new gl;if(!t.verifyKeyPackets)return this._track._backing.getNextKeyPacket(e,t);const i=yield this._track._backing.getNextKeyPacket(e,t);if(!i)return i;oe("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 Tr))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 Tr))throw new TypeError("endPacket must be an EncodedPacket.");if(No(i),this._track.input._disposed)throw new gl;const r=[];let{promise:n,resolve:s}=Ae(),{promise:a,resolve:o}=Ae(),l=!1,c=!1,u=null,d=!1;const h=[],f=()=>Math.max(2,h.length);(()=>Y(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}=Ae()),yield a):(r.push(u),s(),({promise:n,resolve:s}=Ae()),u=yield this.getNextPacket(u,i));l=!0,s()}))().catch(e=>{d||(u=e,d=!0,s())});const m=this._track;return{next(){return Y(this,null,function*(){for(;;){if(m.input._disposed)throw new gl;if(c)return{value:void 0,done:!0};if(d)throw u;if(r.length>0){const e=r.shift(),t=performance.now();for(h.push(t);h.length>0&&t-h[0]>=1e3;)h.shift();return o(),{value:e,done:!1}}if(l)return{value:void 0,done:!0};yield n}})},return(){return Y(this,null,function*(){return c=!0,o(),s(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}class Uo{constructor(e,t){this.onSample=e,this.onError=t}}class qo{mediaSamplesInRange(e=-1/0,t=1/0,i){Oo(e),Oo(t);const r=[];let n=!1,s=null,{promise:a,resolve:o}=Ae(),{promise:l,resolve:c}=Ae(),u=!1,d=!1,h=!1,f=null,m=null,p=!1;const g=V(H({},i),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){var i;f=yield this._createDecoder(i=>{c(),i.timestamp>=t&&(d=!0),d?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}=Ae())))},e=>{p||(m=e,p=!0,o())});const k=this._createPacketSink(),y=null!=(i=yield k.getKeyPacket(e,g))?i:yield k.getFirstKeyPacket(g);let b=y;const T=k.packets(null!=y?y:void 0,void 0,g);for(yield T.next();b&&!d&&!this._track.input._disposed;){const e=Wo(r.length);if(r.length+f.getDecodeQueueSize()>e){({promise:l,resolve:c}=Ae()),yield l;continue}f.decode(b);const t=yield T.next();if(t.done)break;b=t.value}yield T.return(),h||this._track.input._disposed||(yield f.flush()),!n&&s&&r.push(s),u=!0,o()}))().catch(e=>{p||(m=e,p=!0,o())}).finally(()=>{null==f||f.close()});const k=this._track,y=()=>{null==s||s.close();for(const e of r)e.close()};return{next(){return Y(this,null,function*(){for(;;){if(k.input._disposed)throw h=!0,d=!0,y(),new gl;if(h)return{value:void 0,done:!0};if(p)throw h=!0,d=!0,y(),m;if(r.length>0){const e=r.shift();return c(),{value:e,done:!1}}if(u)return{value:void 0,done:!0};yield a}})},return(){return Y(this,null,function*(){return h=!0,d=!0,c(),o(),y(),{value:void 0,done:!0}})},throw(e){return Y(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 Z(this,null,function*(){Symbol.iterator in e?yield*ee(e[Symbol.iterator]()):yield*ee(e[Symbol.asyncIterator]())})}(e),r=[],n=[];let{promise:s,resolve:a}=Ae(),{promise:o,resolve:l}=Ae(),c=!1,u=!1,d=null,h=null,f=!1;const m=e=>{n.push(e),a(),({promise:s,resolve:a}=Ae())},p=V(H({},t),{verifyKeyPackets:!0,metadataOnly:!1});(()=>Y(this,null,function*(){d=yield this._createDecoder(e=>{if(l(),u)return void e.close();let t=0;for(;r.length>0&&e.timestamp-r[0]>-1e-10;)t++,r.shift();if(t>0)for(let i=0;i{f||(h=e,f=!0,a())});const e=this._createPacketSink();let t=null,s=null,g=-1;const k=()=>Y(this,null,function*(){oe(s),oe(d);let t=s;for(d.decode(t);t.sequenceNumberi&&!u;)({promise:o,resolve:l}=Ae()),yield o;if(u)break;const r=yield e.getNextPacket(t,p);oe(r),d.decode(r),t=r}g=-1}),y=()=>Y(this,null,function*(){oe(d),yield d.flush();for(let e=0;e{f||(h=e,f=!0,a())}).finally(()=>{null==d||d.close()});const g=this._track,k=()=>{for(const e of n)null==e||e.close()};return{next(){return Y(this,null,function*(){for(;;){if(g.input._disposed)throw u=!0,k(),new gl;if(u)return{value:void 0,done:!0};if(f)throw u=!0,k(),h;if(n.length>0){const e=n.shift();return oe(void 0!==e),l(),{value:e,done:!1}}if(c)return{value:void 0,done:!0};yield s}})},return(){return Y(this,null,function*(){return u=!0,l(),a(),k(),{value:void 0,done:!0}})},throw(e){return Y(this,null,function*(){throw e})},[Symbol.asyncIterator](){return this}}}}const Wo=e=>0===e?40:8;class Ho extends Uo{constructor(e,t,i,r,n,s){var a,o,l,c,u,d,h,f;super(e,t),this.codec=i,this.decoderConfig=r,this.rotation=n,this.timeResolution=s,this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.inputTimestamps=[],this.sampleQueue=[],this.currentPacketIndex=0,this.raslSkipped=!1,this.alphaDecoder=null,this.alphaHadKeyframe=!1,this.colorQueue=[],this.alphaQueue=[],this.merger=null,this.decodedAlphaChunkCount=0,this.alphaDecoderQueueSize=0,this.nullAlphaFrameQueue=[],this.currentAlphaPacketIndex=0,this.alphaRaslSkipped=!1,this.finalSamples=[],this.mergeAlphaPromises=[];const m=Mo.find(e=>e.supports(i,r));if(m)this.customDecoder=new m,this.customDecoder.codec=i,this.customDecoder.config=r,this.customDecoder.onSample=e=>{if(!(e instanceof lo))throw new TypeError("The argument passed to onSample must be a VideoSample.");this.finalizeAndEmitSample(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=e=>{if(this.alphaQueue.length>0){const t=this.alphaQueue.shift();oe(void 0!==t),this.mergeAlpha(e,t)}else this.colorQueue.push(e)};if(at()){if("avc"===i&&this.decoderConfig.description){const e=Qt(fe(this.decoderConfig.description));if(e&&e.sequenceParameterSets.length>0){const t=Jt(e.sequenceParameterSets[0]);t&&(0===t.frameMbsOnlyFlag&&(this.decoderConfig=V(H({},this.decoderConfig),{hardwareAcceleration:"prefer-software"})),0!==t.maxDecFrameBuffering&&1!==t.bitstreamRestrictionFlag&&(e.sequenceParameterSets[0]=ei(t),this.decoderConfig=V(H({},this.decoderConfig),{description:Gt(e)})))}}Se(this.decoderConfig.colorSpace)||(this.decoderConfig=V(H({},this.decoderConfig),{colorSpace:{primaries:null!=(o=null==(a=this.decoderConfig.colorSpace)?void 0:a.primaries)?o:"bt709",matrix:null!=(c=null==(l=this.decoderConfig.colorSpace)?void 0:l.matrix)?c:"bt709",transfer:null!=(d=null==(u=this.decoderConfig.colorSpace)?void 0:u.transfer)?d:"bt709",fullRange:null!=(f=null==(h=this.decoderConfig.colorSpace)?void 0:h.fullRange)&&f}}))}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:(oe(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)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--);else{if(oe(this.decoder),it()||Fe(this.inputTimestamps,e.timestamp,e=>e),at()&&0===this.currentPacketIndex)if("avc"===this.codec){const t=[];let i=!1;for(const n of Wt(e.data,this.decoderConfig)){const r=Ht(e.data[n.offset]);if(i||(i=r>=1&&r<=5),r===Nt.AUD){if(i)break;t.length=0}r>=20&&r<=31||t.push(e.data.subarray(n.offset,n.offset+n.length))}if(!this.decoderConfig.description)for(let e=0;e{if(t.description){const i=3&fe(t.description)[4];return Xt(e,i+1)}return Kt(e)})(t,this.decoderConfig);e=new Tr(r,e.type,e.timestamp,e.duration)}else if("hevc"===this.codec){const t=mi(e.data,this.decoderConfig);t&&(e=new Tr(t,e.type,e.timestamp,e.duration))}this.decoder.decode(e.toEncodedVideoChunk()),this.decodeAlphaData(e)}this.currentPacketIndex++}decodeAlphaData(e){if(!e.sideData.alpha)return void this.pushNullAlphaFrame();if(this.merger||(this.merger=new jo),!this.alphaDecoder){const e=e=>{if(this.colorQueue.length>0){const t=this.colorQueue.shift();oe(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();oe(void 0!==e),this.mergeAlpha(e,null)}else this.alphaQueue.push(null);this.alphaDecoderQueueSize--},t=new Error("Decoding error").stack;this.alphaDecoder=new VideoDecoder({output:t=>{try{e(t)}catch(i){this.onError(i)}},error:e=>{e.stack=t,this.onError(e)}}),this.alphaDecoder.configure(this.decoderConfig)}const t=wi(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 ti(e,this.decoderConfig)){const i=ii(e[t.offset]);if(i===Lt.RASL_N||i===Lt.RASL_R)return!0}return!1}sampleHandler(e){if(it()){if(this.sampleQueue.length>0&&e.timestamp>=ce(this.sampleQueue).timestamp){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}Fe(this.sampleQueue,e,e=>e.timestamp)}else{const t=this.inputTimestamps.shift();oe(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){return Y(this,null,function*(){const i=Ae();this.mergeAlphaPromises.push(i.promise);const r={sample:null};this.finalSamples.push(r);try{if(t){oe(this.merger);const i=yield this.merger.merge(e,t);r.sample=new lo(i)}else r.sample=new lo(e);for(;this.finalSamples.length>0&&null!==this.finalSamples[0].sample;){const e=this.finalSamples.shift();this.sampleHandler(e.sample)}}catch(n){Me(this.finalSamples,r),this.onError(n)}finally{Me(this.mergeAlphaPromises,i.promise),i.resolve()}})}flush(){return Y(this,null,function*(){var e;if(this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield Promise.all([this.decoder.flush(),null==(e=this.alphaDecoder)?void 0:e.flush()]),yield Promise.all(this.mergeAlphaPromises),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),it()){for(const e of this.sampleQueue)this.finalizeAndEmitSample(e);this.sampleQueue.length=0}this.currentPacketIndex=0,this.raslSkipped=!1})}close(){var e;this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close(),this.alphaDecoder&&"closed"!==this.alphaDecoder.state&&this.alphaDecoder.close(),this.colorQueue.forEach(e=>e.close()),this.colorQueue.length=0,this.alphaQueue.forEach(e=>null==e?void 0:e.close()),this.alphaQueue.length=0,null==(e=this.merger)||e.close());for(const t of this.sampleQueue)t.close();this.sampleQueue.length=0}}let Vo=null;class jo{constructor(){this.workers=[],this.nextWorkerIndex=0,this.pendingRequests=new Map,this.nextRequestId=0}merge(e,t){if(0===this.workers.length){if(!Vo){const e=new Blob([`(${Ko.toString()})()`],{type:"application/javascript"});Vo=URL.createObjectURL(e)}const e=qe(navigator.hardwareConcurrency,1,4);for(let t=0;t{const t=e.data,i=this.pendingRequests.get(t.id);i&&(this.pendingRequests.delete(t.id),"error"in t?i.reject(new Error(t.error)):i.resolve(t.frame))}),e.addEventListener("error",e=>{const t=new Error(e.message||"Color/alpha merge worker error.");for(const i of this.pendingRequests.values())i.reject(t);this.pendingRequests.clear()}),this.workers.push(e)}}const i=this.nextRequestId++,r=Ae();this.pendingRequests.set(i,r);const n=this.workers[this.nextWorkerIndex];return this.nextWorkerIndex=(this.nextWorkerIndex+1)%this.workers.length,n.postMessage({id:i,color:e,alpha:t},{transfer:[e,t]}),r.promise}close(){for(const t of this.workers)t.terminate();this.workers.length=0;const e=new Error("Color/alpha merger closed.");for(const t of this.pendingRequests.values())t.reject(e);this.pendingRequests.clear()}}const Ko=()=>{let e=null,t=null,i=Promise.resolve();self.addEventListener("message",e=>{const{id:t,color:n,alpha:s}=e.data;i=i.then(()=>Y(null,null,function*(){try{const e=yield r(n,s);self.postMessage({id:t,frame:e},{transfer:[e]})}catch(e){self.postMessage({id:t,error:e.message})}finally{n.close(),s.close()}}))});const r=(e,t)=>Y(null,null,function*(){const i=e.format,r=t.format;if(!i||!r)throw new Error("CPU color/alpha merging requires a known VideoFrame format.");const o=i.includes("P10"),l=i.includes("P12"),c=r.includes("P10"),u=r.includes("P12");if(c!==o||u!==l)throw new Error(`CPU color/alpha merging requires the alpha frame to have the same bit depth as the color frame (color: '${i}', alpha: '${r}').`);if("RGBX"===i||"RGBA"===i||"BGRX"===i||"BGRA"===i)return yield n(e,t,i);if("I420"===i||"I420P10"===i||"I420P12"===i||"I422"===i||"I422P10"===i||"I422P12"===i||"I444"===i||"I444P10"===i||"I444P12"===i)return yield s(e,t,i);if("NV12"===i)return yield a(e,t);throw new Error(`CPU color/alpha merging does not support format '${i}'.`)}),n=(e,t,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=new Uint8Array(4*d);yield e.copyTo(h);const f=yield o(t,c,u,1);for(let e=0,t=3;eY(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=i.includes("P10"),h=i.includes("P12"),f=d||h?2:1;let m,p;i.startsWith("I420")?(m=Math.ceil(c/2),p=Math.ceil(u/2)):i.startsWith("I422")?(m=Math.ceil(c/2),p=u):(m=c,p=u);const g=c*u,k=g*f,y=m*p*f,b=new Uint8Array(k+2*y+g*f);yield e.copyTo(b);const T=yield o(t,c,u,f),v=k+2*y;b.set(T,v);const w={format:i.slice(0,4)+"A"+i.slice(4),codedWidth:c,codedHeight:u,timestamp:e.timestamp,duration:null!=(l=e.duration)?l:void 0,transfer:[b.buffer]};return new VideoFrame(b,w)}),a=(e,i)=>Y(null,null,function*(){var r,n,s,a,l;const c=null!=(n=null==(r=e.visibleRect)?void 0:r.width)?n:e.codedWidth,u=null!=(a=null==(s=e.visibleRect)?void 0:s.height)?a:e.codedHeight,d=c*u,h=Math.ceil(c/2)*Math.ceil(u/2),f=e.allocationSize();t&&t.byteLength===f||(t=new Uint8Array(f)),yield e.copyTo(t);const m=new Uint8Array(d+2*h+d);m.set(t.subarray(0,d),0);const p=d,g=d+h,k=d;for(let e=0;eY(null,null,function*(){const s=t.allocationSize();e&&e.byteLength===s||(e=new Uint8Array(s)),yield t.copyTo(e);const a=t.format;if("RGBA"===a||"BGRA"===a||"RGBX"===a||"BGRX"===a){const t="RGBA"===a||"RGBX"===a?0:2,n=i*r;for(let i=0;i{if(!e||"object"!==typeof e)throw new TypeError("decoderOptions must be an object.");if(void 0!==e.hardwareAcceleration&&!["no-preference","prefer-hardware","prefer-software"].includes(e.hardwareAcceleration))throw new TypeError("decoderOptions.hardwareAcceleration, when provided, must be 'no-preference', 'prefer-hardware' or 'prefer-software'.");if(void 0!==e.optimizeForLatency&&"boolean"!==typeof e.optimizeForLatency)throw new TypeError("decoderOptions.optimizeForLatency, when provided, must be a boolean.")};class $o extends qo{constructor(e,t={}){if(!(e instanceof rl))throw new TypeError("videoTrack must be an InputVideoTrack.");Xo(t),super(),this._track=e,this._decoderOptions=t}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof VideoDecoder)throw new Error(ot("VideoDecoder"));throw new Error("This video track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getRotation();let n=yield this._track.getDecoderConfig();const s=yield this._track.getTimeResolution();return oe(i&&n),n=V(H({},n),{hardwareAcceleration:this._decoderOptions.hardwareAcceleration,optimizeForLatency:this._decoderOptions.optimizeForLatency}),new Ho(e,t,i,n,r,s)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Go{constructor(e,t={}){var i,r,n;if(this._rotation=0,this._initPromise=null,this._nextCanvasIndex=0,!(e instanceof rl))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&&ko(t.crop,"options."),void 0!==t.poolSize&&("number"!==typeof t.poolSize||!Number.isInteger(t.poolSize)||t.poolSize<0))throw new TypeError("poolSize must be a non-negative integer.");void 0!==t.decoderOptions&&Xo(t.decoderOptions),this._videoTrack=e,this._alpha=null!=(i=t.alpha)&&i,this._options=t,this._fit=null!=(r=t.fit)?r:"fill",this._videoSampleSink=new $o(e,t.decoderOptions),this._canvasPool=Array.from({length:null!=(n=t.poolSize)?n:0},()=>null)}_ensureInit(){var e;return null!=(e=this._initPromise)?e:this._initPromise=(()=>Y(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=go(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||nt()});oe(s),e._drawWithFitAndMipmapping(r,s,{fit:this._fit,rotation:this._rotation,crop:this._crop,targetIsFresh:n,fillBlack:!this._alpha&&nt()});const a={canvas:r,timestamp:e.timestamp,duration:e.duration};return e.close(),a}getCanvas(e,t){return Y(this,null,function*(){Oo(e),yield this._ensureInit();const i=yield this._videoSampleSink.getSample(e,t);return i&&this._videoSampleToWrappedCanvas(i)})}canvases(e,t,i){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samples(e,t,i),e=>this._videoSampleToWrappedCanvas(e)))})}canvasesAtTimestamps(e,t){return Z(this,null,function*(){yield new J(this._ensureInit()),yield*ee(Ue(this._videoSampleSink.samplesAtTimestamps(e,t),e=>e&&this._videoSampleToWrappedCanvas(e)))})}}class Qo extends Uo{constructor(e,t,i,r){super(e,t),this.decoder=null,this.customDecoder=null,this.customDecoderCallSerializer=new et,this.customDecoderQueueSize=0,this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0;const n=t=>{let i=t.timestamp;null!==this.expectedFirstTimestamp&&null===this.currentTimestamp&&(this.timestampOffset=this.expectedFirstTimestamp-i),i+=this.timestampOffset,(null===this.currentTimestamp||Math.abs(i-this.currentTimestamp)>=t.duration)&&(this.currentTimestamp=i);const n=this.currentTimestamp;if(this.currentTimestamp+=t.duration,0===t.numberOfFrames)return void t.close();const s=r.sampleRate;t.setTimestamp(Math.round(n*s)/s),e(t)},s=Do.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 Co))throw new TypeError("The argument passed to onSample must be an AudioSample.");n(e)},this.customDecoder.onError=e=>{t(e)},this.customDecoderCallSerializer.call(()=>this.customDecoder.init()).catch(e=>t(e));else{const e=new Error("Decoding error").stack;this.decoder=new AudioDecoder({output:e=>{try{n(new Co(e))}catch(t){this.onError(t)}},error:t=>{t.stack=e,this.onError(t)}}),this.decoder.configure(r)}}getDecodeQueueSize(){return this.customDecoder?this.customDecoderQueueSize:(oe(this.decoder),this.decoder.decodeQueueSize)}decode(e){this.customDecoder?(this.customDecoderQueueSize++,this.customDecoderCallSerializer.call(()=>this.customDecoder.decode(e)).catch(e=>this.onError(e)).finally(()=>this.customDecoderQueueSize--)):(oe(this.decoder),null!=this.expectedFirstTimestamp||(this.expectedFirstTimestamp=e.timestamp),this.decoder.decode(e.toEncodedAudioChunk()))}flush(){return Y(this,null,function*(){this.customDecoder?yield this.customDecoderCallSerializer.call(()=>this.customDecoder.flush()):(oe(this.decoder),yield this.decoder.flush()),this.currentTimestamp=null,this.expectedFirstTimestamp=null,this.timestampOffset=0})}close(){this.customDecoder?this.customDecoderCallSerializer.call(()=>this.customDecoder.close()):(oe(this.decoder),"closed"!==this.decoder.state&&this.decoder.close())}}class Yo extends Uo{constructor(e,t,i){super(e,t),this.decoderConfig=i,this.currentTimestamp=null,oe(Xi.includes(i.codec)),this.codec=i.codec;const{dataType:r,sampleSize:n,littleEndian:s}=ar(this.codec);switch(this.inputSampleSize=n,n){case 1:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint8(t)-q(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<(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<e.getUint16(t,s)-q(2,15):"signed"===r?this.readInputValue=(e,t)=>e.getInt16(t,s):oe(!1);break;case 3:"unsigned"===r?this.readInputValue=(e,t)=>Le(e,t,s)-q(2,23):"signed"===r?this.readInputValue=(e,t)=>((e,t,i)=>Le(e,t,i)<<8>>8)(e,t,s):oe(!1);break;case 4:"unsigned"===r?this.readInputValue=(e,t)=>e.getUint32(t,s)-q(2,31):"signed"===r?this.readInputValue=(e,t)=>e.getInt32(t,s):"float"===r?this.readInputValue=(e,t)=>e.getFloat32(t,s):oe(!1);break;case 8:"float"===r?this.readInputValue=(e,t)=>e.getFloat64(t,s):oe(!1);break;default:Oe(n),oe(!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+q(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:Oe(n),oe(!1)}}getDecodeQueueSize(){return 0}decode(e){const t=me(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=a)&&(this.currentTimestamp=e.timestamp);const o=this.currentTimestamp;this.currentTimestamp+=a;const l=new Co({format:this.outputFormat,data:n,numberOfChannels:this.decoderConfig.numberOfChannels,sampleRate:this.decoderConfig.sampleRate,numberOfFrames:i,timestamp:o});this.onSample(l)}flush(){return Y(this,null,function*(){})}close(){}}class Jo extends qo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");super(),this._track=e}_createDecoder(e,t){return Y(this,null,function*(){if(!(yield this._track.canDecode())){if("undefined"===typeof AudioDecoder)throw new Error(ot("AudioDecoder"));throw new Error("This audio track cannot be decoded in this environment. Make sure to check decodability before using a track.")}const i=yield this._track.getCodec(),r=yield this._track.getDecoderConfig();return oe(i&&r),Xi.includes(r.codec)?new Yo(e,t,r):new Qo(e,t,i,r)})}_createPacketSink(){return new zo(this._track)}getSample(e){return Y(this,arguments,function*(e,t={}){Oo(e);try{for(var i,r,n,s=te(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,t,i={}){return this.mediaSamplesInRange(e,t,i)}samplesAtTimestamps(e,t={}){return this.mediaSamplesAtTimestamps(e,t)}}class Zo{constructor(e){if(!(e instanceof nl))throw new TypeError("audioTrack must be an InputAudioTrack.");this._audioSampleSink=new Jo(e)}_audioSampleToWrappedArrayBuffer(e){const t={buffer:e.toAudioBuffer(),timestamp:e.timestamp,duration:e.duration};return e.close(),t}getBuffer(e,t){return Y(this,null,function*(){Oo(e);const i=yield this._audioSampleSink.getSample(e,t);return i&&this._audioSampleToWrappedArrayBuffer(i)})}buffers(e,t,i){return Ue(this._audioSampleSink.samples(e,t,i),e=>this._audioSampleToWrappedArrayBuffer(e))}buffersAtTimestamps(e,t){return Ue(this._audioSampleSink.samplesAtTimestamps(e,t),e=>e&&this._audioSampleToWrappedArrayBuffer(e))}}class el{constructor(e,t){this.input=e,this._backing=t}isVideoTrack(){return this instanceof rl}isAudioTrack(){return this instanceof nl}get id(){return this._backing.getId()}get number(){return this._backing.getNumber()}getInternalCodecId(){return Y(this,null,function*(){return this._backing.getInternalCodecId()})}get internalCodecId(){return tl(this._backing.getInternalCodecId(),"internalCodecId","getInternalCodecId")}getLanguageCode(){return Y(this,null,function*(){return this._backing.getLanguageCode()})}get languageCode(){return tl(this._backing.getLanguageCode(),"languageCode","getLanguageCode")}getName(){return Y(this,null,function*(){return this._backing.getName()})}get name(){return tl(this._backing.getName(),"name","getName")}getTimeResolution(){return Y(this,null,function*(){return this._backing.getTimeResolution()})}get timeResolution(){return tl(this._backing.getTimeResolution(),"timeResolution","getTimeResolution")}isRelativeToUnixEpoch(){return Y(this,null,function*(){return this._backing.isRelativeToUnixEpoch()})}getUnixTimeForTimestamp(e){return Y(this,null,function*(){return this._backing.getUnixTimeForTimestamp(e)})}hasUnixTimeMapping(){return Y(this,null,function*(){return null!==(yield this._backing.getUnixTimeForTimestamp(yield this.getFirstTimestamp()))})}getDisposition(){return Y(this,null,function*(){return this._backing.getDisposition()})}get disposition(){return tl(this._backing.getDisposition(),"disposition","getDisposition")}getBitrate(){return Y(this,null,function*(){return this._backing.getBitrate()})}getAverageBitrate(){return Y(this,null,function*(){return this._backing.getAverageBitrate()})}getFirstTimestamp(){return Y(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 Y(this,null,function*(){var t,i;const r=yield this._backing.getPacket(1/0,H({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 je(n,yield this.getTimeResolution())})}getDurationFromMetadata(){return Y(this,arguments,function*(e={}){return this._backing.getDurationFromMetadata(e)})}computePacketStats(e=1/0,t){return Y(this,null,function*(){const i=new zo(this);let r=1/0,n=-1/0,s=0,a=0;try{for(var o,l,c,u=te(i.packets(void 0,void 0,H({metadataOnly:!0},t)));o=!(l=yield u.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){c=[l]}finally{try{o&&(l=u.return)&&(yield l.call(u))}finally{if(c)throw c[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 Y(this,null,function*(){return null!==(yield this._backing.getLiveRefreshInterval())})}getLiveRefreshInterval(){return Y(this,null,function*(){return this._backing.getLiveRefreshInterval()})}canBePairedWith(e){if(!(e instanceof el))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 Y(this,null,function*(){return this.input.getTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableVideoTracks(e){return Y(this,null,function*(){return this.input.getVideoTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPairableAudioTracks(e){return Y(this,null,function*(){return this.input.getAudioTracks(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableVideoTrack(e){return Y(this,null,function*(){return this.input.getPrimaryVideoTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}getPrimaryPairableAudioTrack(e){return Y(this,null,function*(){return this.input.getPrimaryAudioTrack(ll({filter:e=>e.canBePairedWith(this)},e))})}hasPairableTrack(e){return Y(this,null,function*(){e&&(e=il(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=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isVideoTrack()&&(!e||(yield e(t)))}))}hasPairableAudioTrack(e){return e&&(e=il(e)),this.hasPairableTrack(t=>Y(this,null,function*(){return t.isAudioTrack()&&(!e||(yield e(t)))}))}}const tl=(e,t,i)=>{if(ct(e))throw new Error(`'${t}' is deprecated and not available synchronously for this track. Use the preferred '${i}()' instead.`);return e},il=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 ct(r)?r.then(i):i(r)}:void 0};class rl extends el{constructor(e,t){super(e,t),this._pixelAspectRatioCache=null,this._backing=t}get type(){return"video"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(this,null,function*(){var e,t,i;return null!=(i=yield null==(t=(e=this._backing).getHasOnlyKeyPackets)?void 0:t.call(e))?i:"prores"===(yield this._backing.getCodec())})}getCodedWidth(){return Y(this,null,function*(){return this._backing.getCodedWidth()})}get codedWidth(){return tl(this._backing.getCodedWidth(),"codedWidth","getCodedWidth")}getCodedHeight(){return Y(this,null,function*(){return this._backing.getCodedHeight()})}get codedHeight(){return tl(this._backing.getCodedHeight(),"codedHeight","getCodedHeight")}getRotation(){return Y(this,null,function*(){return this._backing.getRotation()})}get rotation(){return tl(this._backing.getRotation(),"rotation","getRotation")}getSquarePixelWidth(){return Y(this,null,function*(){return this._backing.getSquarePixelWidth()})}get squarePixelWidth(){return tl(this._backing.getSquarePixelWidth(),"squarePixelWidth","getSquarePixelWidth")}getSquarePixelHeight(){return Y(this,null,function*(){return this._backing.getSquarePixelHeight()})}get squarePixelHeight(){return tl(this._backing.getSquarePixelHeight(),"squarePixelHeight","getSquarePixelHeight")}getPixelAspectRatio(){return Y(this,null,function*(){var e;return null!=(e=this._pixelAspectRatioCache)?e:this._pixelAspectRatioCache=yt({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=yt({num:tl(this._backing.getSquarePixelWidth(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedHeight(),"pixelAspectRatio","getPixelAspectRatio"),den:tl(this._backing.getSquarePixelHeight(),"pixelAspectRatio","getPixelAspectRatio")*tl(this._backing.getCodedWidth(),"pixelAspectRatio","getPixelAspectRatio")})}getDisplayWidth(){return Y(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=tl(i,"displayWidth","getDisplayWidth");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayWidth","getDisplayWidth")%180===0?this._backing.getSquarePixelWidth():this._backing.getSquarePixelHeight();return tl(r,"displayWidth","getDisplayWidth")}getDisplayHeight(){return Y(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=tl(i,"displayHeight","getDisplayHeight");if(null!==e)return e}const r=tl(this._backing.getRotation(),"displayHeight","getDisplayHeight")%180===0?this._backing.getSquarePixelHeight():this._backing.getSquarePixelWidth();return tl(r,"displayHeight","getDisplayHeight")}getColorSpace(){return Y(this,null,function*(){return this._backing.getColorSpace()})}hasHighDynamicRange(){return Y(this,null,function*(){const e=yield this._backing.getColorSpace();return"bt2020"===e.primaries||"smpte432"===e.primaries||"pq"===e.transfer||"hlg"===e.transfer||"bt2020-ncl"===e.matrix})}canBeTransparent(){return Y(this,null,function*(){return this._backing.canBeTransparent()})}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Mo.some(i=>i.supports(t,e)))return!0;if("undefined"===typeof VideoDecoder)return!1;return!0===(yield VideoDecoder.isConfigSupported(e)).supported}catch(e){return Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))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 oe(i),wi(t,i,e.data)})}computeFrameRateMetrics(){return Y(this,arguments,function*(e={}){var t,i;if(!e||"object"!==typeof e)throw new TypeError("options must be an object.");if(void 0!==e.targetPacketCount&&(!mt(e.targetPacketCount)||e.targetPacketCount<0))throw new TypeError("options.targetPacketCount must be a non-negative number.");const r=yield this.getTimeResolution(),n=null!=(t=e.targetPacketCount)?t:256,s=new zo(this),a=[];let o=-1/0,l=0;try{for(var c,u,d,h=te(s.packets(void 0,void 0,{metadataOnly:!0}));c=!(u=yield h.next()).done;c=!1){const e=u.value;if(a.length>=n&&e.timestamp>=o)break;a.push(e.timestamp),o=Math.max(o,e.timestamp),l++}}catch(u){d=[u]}finally{try{c&&(u=h.return)&&(yield u.call(h))}finally{if(d)throw d[0]}}const f=new Float64Array(a.length);for(let R=0;Re-t),I=S-1>>1,x=S>>1;let C=0,B=0,E=0;for(const R of P)if(E+=b.get(R),0===C&&E>I&&(C=R),E>x){B=R;break}const _=(k/C+k/B)/2;return{underlyingFrameRate:g,bestGuessFrameRate:null!==g?g:hl(_),minFrameRate:k/v,maxFrameRate:k/T,averageFrameRate:k*S/w,medianFrameRate:_,frameRateIsConstant:null!==g&&1===T&&1===v,probedPacketCount:l}})}}class nl extends el{constructor(e,t){super(e,t),this._backing=t}get type(){return"audio"}getCodec(){return Y(this,null,function*(){return this._backing.getCodec()})}get codec(){return tl(this._backing.getCodec(),"codec","getCodec")}hasOnlyKeyPackets(){return Y(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 Y(this,null,function*(){return this._backing.getNumberOfChannels()})}get numberOfChannels(){return tl(this._backing.getNumberOfChannels(),"numberOfChannels","getNumberOfChannels")}getSampleRate(){return Y(this,null,function*(){return this._backing.getSampleRate()})}get sampleRate(){return tl(this._backing.getSampleRate(),"sampleRate","getSampleRate")}getDecoderConfig(){return Y(this,null,function*(){return this._backing.getDecoderConfig()})}getCodecParameterString(){return Y(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 Y(this,null,function*(){try{const e=yield this._backing.getDecoderConfig();if(!e)return!1;const t=yield this._backing.getCodec();if(oe(null!==t),Do.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 Pt._error("Error during decodability check:",e),!1}})}determinePacketType(e){return Y(this,null,function*(){if(!(e instanceof Tr))throw new TypeError("packet must be an EncodedPacket.");return null===(yield this.getCodec())?null:"key"})}}const sl=e=>-(null!=e?e:-1/0),al=e=>-e,ol=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 ct(r)?r.then(i):i(r)}:void 0,sortBy:e.sortBy?t=>{const i=e=>{if("number"!==typeof e&&(!Array.isArray(e)||!e.every(e=>"number"===typeof e)))throw new TypeError("query.sortBy must return or resolve to a number or an array of numbers.");return e},r=e.sortBy(t);return ct(r)?r.then(i):i(r)}:void 0}},ll=(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 ct(s)?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 ct(o)||ct(l)?Promise.all([o,l]).then(([e,t])=>c(e,t)):c(o,l)}:void 0}),cl=(e,t)=>Y(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=>ct(e))){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=>ct(e))?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;oe.track)}),ul=(e,t)=>{const i=1e6,r=1+1e-9,n=[12,15,20,24e3/1001,24,25,3e4/1001,30,48,50,6e4/1001,60,100,12e4/1001,120,144,240];if(e.length<2)return null;const s=new Float64Array(e.length-1);for(let v=1;v0))return null;s[v-1]=t}const a=s.slice();a.sort();let o=a[Math.floor(.05*a.length)];for(let v=0;v<6;v++){let e=0,t=0;for(const n of s){const i=Math.max(1,Math.round(n/o));Math.abs(n-i*o)>=r||(e+=n,t+=i)}if(0===t)return null;const i=e/t;if(Math.abs(i-o)<=1e-12*Math.max(1,o)){o=i;break}o=i}let l=0,c=0,u=0;for(const v of s){const e=Math.max(1,Math.round(v/o));Math.abs(v-e*o)>=r||(l++,c+=v,u+=e)}if(l/s.length<.98)return null;o=c/u;const d=1/Math.min(u,1e3),h=Math.max(Number.EPSILON,o-d),f=o+d,m=t/f,p=t/h,g=t/o;let k=null,y=1/0;for(const v of n){if(vp)continue;const e=Math.abs(v/g-1);e{for(let r=1;r<=i;r++){const i=Math.floor(e*r)+1;if(i/r{const t=[24/1.001,30/1.001,60/1.001,120/1.001],i=[12,15,20,24,25,30,48,50,60,100,120,144,240];for(const s of t)if(Math.abs(s/e-1)<=5e-4)return s;let r=e,n=1/0;for(const s of i){const t=Math.abs(s/e-1);t<=.025&&t!(e instanceof Ea)))throw new TypeError("options.formats must be an array of InputFormat.");if(!(e.source instanceof ea||e.source instanceof ta))throw new TypeError("options.source must be a Source or SourceRef.");if(e.source instanceof ea&&e.source._disposed)throw new TypeError("options.source must not be a disposed Source.");if(void 0!==e.initInput&&!(e.initInput instanceof ml))throw new TypeError("options.initInput, when provided, must be an Input.");void 0!==e.formatOptions&&((e,t)=>{if(!e||"object"!==typeof e)throw new TypeError(`${t}, when provided, must be an object.`);if(void 0!==e.isobmff){if(!e.isobmff||"object"!==typeof e.isobmff)throw new TypeError(`${t}.isobmff, when provided, must be an object.`);if(void 0!==e.isobmff.resolveKeyId&&"function"!==typeof e.isobmff.resolveKeyId)throw new TypeError(`${t}.isobmff.resolveKeyId, when provided, must be a function.`)}if(void 0!==e.hls){if(!e.hls||"object"!==typeof e.hls)throw new TypeError(`${t}.hls, when provided, must be an object.`);if(void 0!==e.hls.offsetTimestampsByDateTime&&"boolean"!==typeof e.hls.offsetTimestampsByDateTime)throw new TypeError(`${t}.hls.offsetTimestampsByDateTime, when provided, must be a boolean.`)}})(e.formatOptions,"formatOptions"),this._formats=e.formats,this._initInput=null!=(t=e.initInput)?t:null,this._formatOptions=null!=(i=e.formatOptions)?i:{},e.source instanceof ea?this._rootRef=e.source.ref():this._rootRef=e.source,this._sourceRefs.push(this._rootRef)}get _rootSource(){return this._rootRef.source}_getSourceUncached(e){return Y(this,null,function*(){oe(this._rootSource instanceof ia);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&&ra(i.request,e));if(i)return i.age++,Promise.resolve(i.sourceRef.source.ref());const r=this._sourceCachePromises.find(i=>i.cacheGroup===t&&ra(i.request,e));if(r)return r.promise.then(e=>e.sourceRef.source.ref());const n=(()=>Y(this,null,function*(){const i=yield this._getSourceUncached(e);if(gt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount)>=4){const e=kt(this._sourceCache,e=>e.cacheGroup===t&&1===e.sourceRef.source._refCount?e.age:1/0);oe(-1!==e);const i=this._sourceCache[e];this._sourceCache.splice(e,1),i.sourceRef.free(),Me(this._sourceRefs,i.sourceRef)}this._sourceRefs.push(i);const r=this._sourceCachePromises.findIndex(t=>t.request===e);oe(-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=(()=>Y(this,null,function*(){var e;this._reader=new kl(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 pl}))()}get source(){return this._rootSource}getFormat(){return Y(this,null,function*(){return yield this._getDemuxer(),oe(this._format),this._format})}canRead(){return Y(this,null,function*(){try{return yield this._getDemuxer(),!0}catch(e){if(e instanceof pl)return!1;throw e}})}getFirstTimestamp(e){return Y(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._backing.getFirstPacket({metadataOnly:!0}))),r=Math.min(...i.map(e=>{var t;return null!=(t=null==e?void 0:e.timestamp)?t:1/0}));return r===1/0?0:r})}computeDuration(e,t){return Y(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 Y(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 Y(this,null,function*(){e&&(e=ol(e));const t=(yield this._getTrackBackings()).map(e=>this._wrapBackingAsTrack(e));return cl(t,e)})}getVideoTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isVideoTrack());return cl(t,e)})}getAudioTracks(e){return Y(this,null,function*(){e&&(e=ol(e));const t=(yield this.getTracks()).filter(e=>e.isAudioTrack());return cl(t,e)})}getPrimaryVideoTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=ll(e,{sortBy:e=>Y(null,null,function*(){return[al((yield e.getDisposition()).default),al(yield e.hasPairableAudioTrack()),al(!(yield e.hasOnlyKeyPackets())),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getVideoTracks(i))[0])?t:null})}getPrimaryAudioTrack(e){return Y(this,null,function*(){var t;e&&(e=ol(e));const i=yield this.getPrimaryVideoTrack(),r=ll(e,{sortBy:e=>Y(this,null,function*(){return[al(!i||e.canBePairedWith(i)),al((yield e.getDisposition()).default),sl(yield e.getBitrate())]})});return null!=(t=(yield this.getAudioTracks(r))[0])?t:null})}_getTrackBackings(){return Y(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 rl(this,e):new nl(this,e);return this._backingToTrack.set(e,i),i}getMimeType(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMimeType()})}getMetadataTags(){return Y(this,null,function*(){return(yield this._getDemuxer()).getMetadataTags()})}dispose(){if(!this._disposed){this._disposed=!0;for(const e of this._sourceRefs)e.free();this._sourceRefs.length=0,this._demuxerPromise&&this._demuxerPromise.then(e=>e.dispose()).catch(()=>{})}}[Symbol.dispose](){this.dispose()}}class pl extends Error{constructor(e="Input has an unsupported or unrecognizable format."){super(e),this.name="UnsupportedInputFormatError"}}class gl extends Error{constructor(e="Input has been disposed."){super(e),this.name="InputDisposedError"}}class kl{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 gl;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 yl(t,me(t),0,e,e)}const i=e+t,r=this.source._read(e,i,0,Zs);return ct(r)?r.then(t=>t?new yl(t.bytes,t.view,t.offset,e,i):null):r?new yl(r.bytes,r.view,r.offset,e,i):null}requestSliceRange(e,t,i){if(this.source._disposed)throw new gl;if(e<0)return null;if(null!==this.fileSizeNonStrict)return this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i));{const r=this.requestSlice(e,i),n=r=>r||(oe(null!==this.fileSizeNonStrict),this.requestSlice(e,qe(this.fileSizeNonStrict-e,t,i)));return ct(r)?r.then(n):n(r)}}requestEntireFile(){if(null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);return(()=>Y(this,null,function*(){const e=[];let t=0;for(;;){if(1===e.length&&null!==this.fileSizeNonStrict)return this.requestSlice(0,this.fileSizeNonStrict);let i=this.requestSliceRange(t,0,1024);if(ct(i)&&(i=yield i),!i||0===i.length)break;const r=Tl(i,i.length);e.push(r),t+=i.length}const i=new Uint8Array(t);let r=0;for(const n of e)i.set(n,r),r+=n.length;return new yl(i,me(i),0,0,t)}))()}}class yl{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 yl(e,me(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(ethis.end)throw new RangeError("Slicing outside of original slice.");return new yl(this.bytes,this.view,this.offset,e,e+t)}}const bl=(e,t)=>{if(e.filePose.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.`)},Tl=(e,t)=>{bl(e,t);const i=e.bytes.subarray(e.bufferPos,e.bufferPos+t);return e.bufferPos+=t,i},vl=e=>(bl(e,1),e.view.getUint8(e.bufferPos++)),wl=(e,t)=>{bl(e,2);const i=e.view.getUint16(e.bufferPos,t);return e.bufferPos+=2,i},Sl=e=>{bl(e,2);const t=e.view.getUint16(e.bufferPos,!1);return e.bufferPos+=2,t},Pl=e=>{bl(e,3);const t=Le(e.view,e.bufferPos,!1);return e.bufferPos+=3,t},Il=e=>{bl(e,2);const t=e.view.getInt16(e.bufferPos,!1);return e.bufferPos+=2,t},xl=(e,t)=>{bl(e,4);const i=e.view.getUint32(e.bufferPos,t);return e.bufferPos+=4,i},Cl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!1);return e.bufferPos+=4,t},Bl=e=>{bl(e,4);const t=e.view.getUint32(e.bufferPos,!0);return e.bufferPos+=4,t},El=e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!1);return e.bufferPos+=4,t},_l=(e,t)=>{let i,r;return t?(i=xl(e,!0),r=xl(e,!0)):(r=xl(e,!1),i=xl(e,!1)),4294967296*r+i},Rl=e=>4294967296*Cl(e)+Cl(e),Fl=e=>4294967296*El(e)+Cl(e),Al=e=>{const t=Bl(e),i=(e=>{bl(e,4);const t=e.view.getInt32(e.bufferPos,!0);return e.bufferPos+=4,t})(e);return 4294967296*i+t},Ml=e=>{bl(e,4);const t=e.view.getFloat32(e.bufferPos,!1);return e.bufferPos+=4,t},Dl=e=>{bl(e,8);const t=e.view.getFloat64(e.bufferPos,!1);return e.bufferPos+=8,t},Nl=(e,t)=>{bl(e,t);let i="";for(let r=0;rpe.decode(Tl(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 Ll,zl,Ul,ql;(zl=Ll||(Ll={}))[zl.Unsynchronisation=128]="Unsynchronisation",zl[zl.ExtendedHeader=64]="ExtendedHeader",zl[zl.ExperimentalIndicator=32]="ExperimentalIndicator",zl[zl.Footer=16]="Footer",(ql=Ul||(Ul={}))[ql.ISO_8859_1=0]="ISO_8859_1",ql[ql.UTF_16_WITH_BOM=1]="UTF_16_WITH_BOM",ql[ql.UTF_16_BE_NO_BOM=2]="UTF_16_BE_NO_BOM",ql[ql.UTF_8=3]="UTF_8";const Wl=128,Hl=10,Vl=["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"],jl=(e,t)=>{var i;const r=e.filePos;null!=t.raw||(t.raw={}),null!=(i=t.raw).TAG||(i.TAG=Tl(e,Wl-3)),e.filePos=r;const n=Kl(e,30);n&&(null!=t.title||(t.title=n));const s=Kl(e,30);s&&(null!=t.artist||(t.artist=s));const a=Kl(e,30);a&&(null!=t.album||(t.album=a));const o=Kl(e,4),l=Number.parseInt(o,10);Number.isInteger(l)&&l>0&&(null!=t.date||(t.date=new Date(String(l))));const c=Tl(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=Kl(e,28),e.skip(2)}else e.skip(-30),u=Kl(e,30);u&&(null!=t.comment||(t.comment=u));const d=vl(e);d{const i=Tl(e,t),r=ut(i.indexOf(0),i.length),n=i.subarray(0,r);let s="";for(let a=0;a{const t=e.filePos,i=Nl(e,3),r=vl(e),n=vl(e),s=vl(e),a=Cl(e);if("ID3"!==i||255===r||255===n||0!==(2155905152&a))return e.filePos=t,null;let o=mr(a);return s&Ll.Footer&&(o+=Hl),{majorVersion:r,revision:n,flags:s,size:o}},$l=(e,t,i)=>{var r,n,s,a,o,l;if(![2,3,4].includes(t.majorVersion))return void Pt._warn(`Unsupported ID3v2 major version: ${t.majorVersion}`);const c=t.flags&Ll.Footer?t.size-Hl:t.size,u=Tl(e,c),d=new Gl(t,u);if(t.flags&Ll.Unsynchronisation&&3===t.majorVersion&&d.ununsynchronizeAll(),t.flags&Ll.ExtendedHeader){const e=d.readU32();3===t.majorVersion?d.pos+=e:d.pos+=e-4}for(;d.pos<=d.bytes.length-d.frameHeaderSize();){const e=d.readId3V2Frame();if(!e)break;const c=d.pos,u=d.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&Ll.Unsynchronisation)),h)Pt._warn(`Skipping encrypted ID3v2 frame ${e.id}`),d.pos=u;else if(f)Pt._warn(`Skipping compressed ID3v2 frame ${e.id}`),d.pos=u;else{if(m&&d.ununsynchronizeRegion(d.pos,u),null!=i.raw||(i.raw={}),"TXXX"===e.id){const e=null!=(n=(r=i.raw).TXXX)?n:r.TXXX={},t=d.readId3V2TextEncoding(),s=d.readId3V2Text(t,u),a=d.readId3V2Text(t,u);null!=e[s]||(e[s]=a)}else"T"===e.id[0]?null!=(s=i.raw)[a=e.id]||(s[a]=d.readId3V2EncodingAndText(u)):null!=(o=i.raw)[l=e.id]||(o[l]=d.readBytes(e.size));switch(d.pos=c,e.id){case"TIT2":case"TT2":null!=i.title||(i.title=d.readId3V2EncodingAndText(u));break;case"TIT3":case"TT3":null!=i.description||(i.description=d.readId3V2EncodingAndText(u));break;case"TPE1":case"TP1":null!=i.artist||(i.artist=d.readId3V2EncodingAndText(u));break;case"TALB":case"TAL":null!=i.album||(i.album=d.readId3V2EncodingAndText(u));break;case"TPE2":case"TP2":null!=i.albumArtist||(i.albumArtist=d.readId3V2EncodingAndText(u));break;case"TRCK":case"TRK":{const e=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u).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=d.readId3V2EncodingAndText(u);let t=/^\((\d+)\)/.exec(e);if(t){const e=Number.parseInt(t[1]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}if(t=/^\d+$/.exec(e),t){const e=Number.parseInt(t[0]);if(void 0!==Vl[e]){null!=i.genre||(i.genre=Vl[e]);break}}null!=i.genre||(i.genre=e)}break;case"TDRC":case"TDAT":{const e=d.readId3V2EncodingAndText(u),t=new Date(e);Number.isNaN(t.getTime())||null!=i.date||(i.date=t)}break;case"TYER":case"TYE":{const e=d.readId3V2EncodingAndText(u),t=Number.parseInt(e,10);Number.isInteger(t)&&(null!=i.date||(i.date=new Date(String(t))))}break;case"USLT":case"ULT":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.lyrics||(i.lyrics=d.readId3V2Text(e,u))}break;case"COMM":case"COM":{const e=d.readU8();d.pos+=3,d.readId3V2Text(e,u),null!=i.comment||(i.comment=d.readId3V2Text(e,u))}break;case"APIC":case"PIC":{const e=d.readId3V2TextEncoding();let r;if(2===t.majorVersion){const e=d.readAscii(3);r="PNG"===e?"image/png":"JPG"===e?"image/jpeg":"image/*"}else r=d.readId3V2Text(e,u);const n=d.readU8(),s=d.readId3V2Text(e,u).trimEnd(),a=u-d.pos;if(a>=0){const e=d.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:d.pos+=e.size}d.pos=u}}};class Gl{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{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:mr(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 Ul.ISO_8859_1:{let e="";for(let t=0;t0===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=ut(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=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}case Ul.UTF_16_BE_NO_BOM:{const e=new TextDecoder("utf-16be"),t=ut(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 Ul.UTF_8:{const e=ut(r.findIndex(e=>0===e),r.length);return this.pos=i+Math.min(e+1,r.length),pe.decode(r.subarray(0,e))}}}readId3V2EncodingAndText(e){if(this.pos>=e)return"";const t=this.readId3V2TextEncoding();return this.readId3V2Text(t,e)}}class Ql{constructor(e){this.host=e,this.closed=!1,this.resumes=new WeakMap}ensure(e){if(this.closed)return null;if(this.host.audioContext)return this.host.audioContext;const t=window.AudioContext||window.webkitAudioContext;let i;try{i=new t({sampleRate:e})}catch(n){i=new t}if(this.closed)return i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null;let r=null;try{r=i.createGain(),r.connect(i.destination);const e=this.host.muted?0:this.host.volume;return r.gain.value=e*e,this.closed?(r.disconnect(),i.close().catch(e=>console.warn("MediaBunny obsolete context cleanup:",e)),null):(this.host.audioContext=i,this.host.gainNode=r,i)}catch(s){try{null==r||r.disconnect()}catch(a){console.warn("MediaBunny gain setup cleanup:",a)}throw i.close().catch(e=>console.warn("MediaBunny context setup cleanup:",e)),s}}updateGain(){if(!this.host.gainNode)return;const e=this.host.muted?0:this.host.volume;this.host.gainNode.gain.value=e*e}resume(e){const t=this.resumes.get(e);if(t)return t;const i=e.resume();this.resumes.set(e,i);const r=()=>{this.resumes.get(e)===i&&this.resumes.delete(e)};return i.then(r,r),i}destroy(){if(this.closed)return;this.closed=!0;const{audioContext:e,gainNode:t}=this.host;this.host.audioContext=null,this.host.gainNode=null;try{null==t||t.disconnect()}finally{e&&e.close().catch(e=>console.warn("MediaBunny context close error:",e))}}}class Yl{constructor(e){this.host=e}release(e,t){this.host.queuedNodes.delete(e),e.onended=null;let i,r=!1;try{t&&e.stop()}catch(n){r=!0,i=n}try{e.disconnect()}catch(n){r||(r=!0,i=n)}if(r)throw i}stop(){const e=[];for(const i of[...this.host.queuedNodes])try{this.release(i,!0)}catch(t){e.push(t)}if(e.length)throw e[0]}schedule({buffer:e,timestamp:t}){const i=this.host.audioContext,r=this.host.gainNode;if(!i||!r)return;const n=function(e,t,i,r){const n=e.audioContextStartTime+(t-e.playbackTimeAtStart)/e.playbackRate,s=(n+i/e.playbackRate-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;return{startAt:Math.max(n,r),offset:n=e.duration)return;const s=i.createBufferSource();this.host.queuedNodes.add(s);try{s.buffer=e,s.connect(r),s.playbackRate.value=this.host.playbackRate,s.onended=()=>{if(this.host.queuedNodes.has(s))try{this.release(s,!1)}catch(e){console.warn("MediaBunny ended node cleanup:",e)}},null===n.offset?s.start(n.startAt):s.start(n.startAt,n.offset),this.host.latestScheduledEndTime=Math.max(this.host.latestScheduledEndTime,n.endMediaTime)}catch(a){try{this.release(s,!0)}catch(o){console.warn("MediaBunny audio node cleanup:",o)}throw a}}}const Jl=Symbol("cancelled");class Zl{constructor(){this.cancelled=!1,this.waits=new Set,this.timers=new Map}wait(e){return new Promise((t,i)=>{const r=()=>t(Jl);this.cancelled?r():this.waits.add(r),e.then(e=>{this.waits.delete(r),t(e)},e=>{this.waits.delete(r),i(e)})})}delay(e){return this.cancelled?Promise.resolve(!1):new Promise(t=>{const i=setTimeout(()=>{this.timers.delete(i),t(!this.cancelled)},e);this.timers.set(i,t)})}cancel(){if(!this.cancelled){this.cancelled=!0;for(const e of this.waits)e();this.waits.clear();for(const[e,t]of this.timers)clearTimeout(e),t(!1);this.timers.clear()}}}function ec(e,t,i){for(const r of i){if(!t())return;e.emit(r)}}class tc{constructor(e,t,i){this.host=e,this.contexts=t,this.nodes=i,this.task=null,this.closing=new WeakMap}stopIterator(){return Y(this,null,function*(){const e=this.host.audioIterator;if(this.host.audioIterator=null,!e)return;let t=this.closing.get(e);t||(t=Promise.resolve().then(()=>e.return()).then(()=>{}),this.closing.set(e,t)),yield t})}cancel(){var e;null==(e=this.task)||e.cancel(),this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e))}run(e){return Y(this,null,function*(){if(this.host.asyncId!==e)return;this.cancel();const t=this.host.audioSink,i=this.host.audioContext;if(!t||!i||this.host.paused||this.host.asyncId!==e)return;const r=new Zl;this.task=r;let n=null;const s=()=>!r.cancelled&&this.task===r&&this.host.asyncId===e&&!this.host.paused&&this.host.audioContext===i&&(!n||this.host.audioIterator===n);try{for(n=t.buffers(this.host.currentTime),this.host.audioIterator=n;s();){const e=[];let t=!1;for(let i=0;i<16;i++){const i=yield r.wait(n.next());if(i===Jl||!s())return;if(i.done){t=!0;break}e.push(i.value)}if(e.length&&"suspended"===i.state){if((yield r.wait(this.contexts.resume(i)))===Jl||!s())return;ec(this.host.events,s,["canplay","playing"])}for(const i of e){if(!s())return;this.nodes.schedule(i)}if(t)return;if(!(yield r.delay(0))||!s())return;for(;this.host.latestScheduledEndTime-this.host.currentTime>1;)if(!(yield r.delay(50))||!s())return}}catch(a){if(s())throw a}finally{r.cancel(),this.task===r&&(this.task=null,this.stopIterator().catch(e=>console.warn("MediaBunny audio iterator cleanup:",e)))}})}}class ic{constructor(e,d){X(this,u),X(this,t,!1),X(this,i,0),X(this,r),X(this,n),X(this,s),X(this,a,null),X(this,o,null),X(this,l,null),X(this,c),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,$(this,r,new Ql(this)),$(this,n,new Yl(this)),$(this,s,new tc(this,K(this,r),K(this,n))),$(this,c,d)}get currentTime(){return(e=this).paused||!e.audioContext?e.playbackTimeAtStart:(e.audioContext.currentTime-e.audioContextStartTime)*e.playbackRate+e.playbackTimeAtStart;var e}ensureAudioContext(e){K(this,r).ensure(e)}updateGain(){K(this,r).updateGain()}stopQueuedNodes(){K(this,n).stop()}stopIterator(){return Y(this,null,function*(){yield K(this,s).stopIterator()})}handleNoAudioTrack(){K(this,t)||(this.audioSink=null,this.ensureAudioContext())}cancelPending(){Q(this,i)._++;try{this.pause()}finally{$(this,l,null),this.input=null,this.audioSink=null}}load(e,r){return Y(this,null,function*(){if(K(this,t))return;this.cancelPending();const n=K(this,i);this.playbackTimeAtStart=0,this.audioContextStartTime=0,this.latestScheduledEndTime=0;const s=Promise.resolve().then(()=>G(this,u,d).call(this,e,n,r));$(this,l,s);try{yield s}finally{K(this,l)===s&&$(this,l,null)}})}runIterator(e){return Y(this,null,function*(){K(this,t)||(yield K(this,s).run(e))})}play(){return Y(this,null,function*(){if(K(this,t))return;if(K(this,o))return K(this,o);if(!this.paused)return;const e=new Zl;$(this,a,e);const r=K(this,i),n=G(this,u,f).call(this,e,r);$(this,o,n);try{yield n}finally{K(this,a)===e&&($(this,a,null),$(this,o,null))}})}pause(){var e;this.paused||(this.playbackTimeAtStart=this.currentTime),this.paused=!0,this.asyncId++,null==(e=K(this,a))||e.cancel(),$(this,a,null),$(this,o,null),K(this,s).cancel(),this.stopQueuedNodes()}seek(e){return Y(this,null,function*(){var i,r;if(K(this,t))return;const n=!this.paused;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=Math.max(0,e),this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.latestScheduledEndTime=this.playbackTimeAtStart;const a=++this.asyncId;n&&G(this,u,h).call(this,a)})}setVolume(e,t){this.volume=e,this.muted=t,this.updateGain()}setPlaybackRate(e){var i,r;if(K(this,t)||e===this.playbackRate)return;const n=this.currentTime;K(this,s).cancel(),this.stopQueuedNodes(),this.playbackTimeAtStart=n,this.audioContextStartTime=null!=(r=null==(i=this.audioContext)?void 0:i.currentTime)?r:0,this.playbackRate=e,this.latestScheduledEndTime=n;const a=++this.asyncId;this.paused||G(this,u,h).call(this,a)}destroy(){if(K(this,t))return;$(this,t,!0),Q(this,i)._++;const e=[];for(const t of[()=>this.pause(),()=>K(this,r).destroy()])try{t()}catch(n){e.push(n)}if(this.input=null,this.audioSink=null,$(this,l,null),e.length)throw e[0]}}t=new WeakMap,i=new WeakMap,r=new WeakMap,n=new WeakMap,s=new WeakMap,a=new WeakMap,o=new WeakMap,l=new WeakMap,c=new WeakMap,u=new WeakSet,d=function(e,r,n){return Y(this,arguments,function*({input:e,audioTrack:r,duration:n},s,a){const o=()=>!K(this,t)&&K(this,i)===s;if(o()){this.input=e,this.duration=n;try{const e=r&&null!==r.codec&&(yield r.canDecode());if(!o())return;if(e){if(this.ensureAudioContext(r.sampleRate),!o())return;this.audioSink=new Zo(r)}else this.handleNoAudioTrack();o()&&(null==a||a())}catch(l){if(o())throw l}}})},h=function(e){this.runIterator(e).catch(i=>{if(!K(this,t)&&e===this.asyncId){try{this.pause()}catch(r){console.warn("MediaBunny audio failure cleanup:",r)}try{K(this,c)?K(this,c).call(this,i):this.events.emit("error",i)}catch(r){console.warn("MediaBunny audio error listener:",r)}}})},f=function(e,n){return Y(this,null,function*(){const s=()=>!K(this,t)&&!e.cancelled&&K(this,i)===n;try{const t=K(this,r).ensure();if(!t||!s())return;if("suspended"===t.state){if((yield e.wait(K(this,r).resume(t)))===Jl||!s())return}if(K(this,l)){if((yield e.wait(K(this,l)))===Jl||!s())return}this.audioContextStartTime=t.currentTime,this.latestScheduledEndTime=this.playbackTimeAtStart,this.paused=!1,G(this,u,h).call(this,++this.asyncId)}catch(a){if(s())throw a}})};const rc=new WeakMap;function nc(e,t,i){return Y(this,null,function*(){var r;const{input:n,loadSeq:s}=e;if(!(null==(r=e.media)?void 0:r.isHls)||!n||e.destroyed)return;const a={};rc.set(e,a);const o=()=>!e.destroyed&&e.loadSeq===s&&e.input===n&&rc.get(e)===a;for(;o();){const r=e.media;if(!(null==r?void 0:r.isHls))return;let s;try{s=yield i(n,r,t,o)}catch(l){if(!o())return;if(e.media===r)throw l;continue}if(!o())return;if(e.media===r){if(s)try{yield e.replaceTracks(s)}catch(l){if(o())throw l}return}}})}function sc(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getVideoTracks();if(!r())return null;const a="auto"===i?yield e.getPrimaryVideoTrack():null!=(n=s.find(e=>e.id===i))?n:t.videoTrack;if(!r()||!a)return null;let o=t.audioTrack,l=t.audioMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableAudioTrack(),l="auto"),{videoTrack:a,audioTrack:o,videoMode:"auto"===i?"auto":"manual",audioMode:l}})}function ac(e,t,i,r){return Y(this,null,function*(){var n;const s=yield e.getAudioTracks();if(!r())return null;const a="auto"===i?t.videoTrack?yield t.videoTrack.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack():null!=(n=s.find(e=>e.id===i))?n:t.audioTrack;if(!r()||!a)return null;let o=t.videoTrack,l=t.videoMode;return o&&a.canBePairedWith(o)||(o=yield a.getPrimaryPairableVideoTrack(),l="auto"),{videoTrack:o,audioTrack:a,videoMode:l,audioMode:"auto"===i?"auto":"manual"}})}function oc(e){return Y(this,null,function*(){var t,i;return null!=(i=null!=(t=yield e.getAverageBitrate())?t:yield e.getBitrate())?i:0})}const lc=/\.m3u8(?:$|[?#])/i;function cc(e){return"string"===typeof e&&lc.test(e)}function uc(e){const t=function(e){return"string"===typeof e?new ua(e):e instanceof Blob?new aa(e):"undefined"!==typeof ReadableStream&&e instanceof ReadableStream?new fa(e):null!=e?e:null}(e);return t?new ml({source:t,formats:cc(e)?eo:Za}):null}class dc{constructor(){this.active=!0,this.input=null,this.timers=new Set,this.controller="undefined"===typeof AbortController?void 0:new AbortController,this.cancellation=new Promise(e=>{this.resolveCancellation=e})}get signal(){var e;return null==(e=this.controller)?void 0:e.signal}own(e){this.active?this.input=e:e.dispose()}defer(e){if(!this.active)return;const t=setTimeout(()=>{this.timers.delete(t),this.active&&e()},0);this.timers.add(t)}wait(e,t){return Y(this,null,function*(){try{yield Promise.race([e,this.cancellation,t>0?this.timeout(t):new Promise(()=>{})])}finally{void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0)}})}timeout(e){return new Promise((t,i)=>{this.deadline=setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){const e=this.input;this.input=null,null==e||e.dispose()}cancel(){var e;if(this.active){this.active=!1;for(const e of this.timers)clearTimeout(e);this.timers.clear(),void 0!==this.deadline&&(clearTimeout(this.deadline),this.deadline=void 0),this.resolveCancellation(),null==(e=this.controller)||e.abort(),this.disposeInput()}}}function hc(e){return Y(this,arguments,function*({input:e,videoTrack:t,audioTrack:i}){const r=[t,i].filter(e=>null!==e),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 fc(){let e,t;return{promise:new Promise((i,r)=>{e=i,t=r}),resolve:e,reject:t}}class mc{constructor(e){this.host=e,this.wanted=!1,this.playing=null,this.seeking=null}operation(){return V(H({},fc()),{source:this.host.loadSeq,complete:fc()})}current(e,t){return!this.host.destroyed&&e.source===this.host.loadSeq&&this[t]===e}cancelPlay(){const e=this.playing;this.playing=null,null==e||e.resolve()}invalidate(){this.cancelPlay(),this.wanted=!1;const e=this.seeking;this.seeking=null,null==e||e.complete.resolve(),null==e||e.resolve(),this.host.seeking=!1}ended(){this.wanted=!1,this.cancelPlay()}stop(){this.host.paused||(this.host.paused=!0,this.stopEngines(),this.host.events.emit("pause"))}stopEngines(){const e=[];for(const i of[()=>this.host.audio.pause(),()=>this.host.video.stop()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}pause(){this.wanted=!1,this.cancelPlay(),this.stop()}play(){if(this.host.destroyed)return Promise.resolve();if(this.wanted=!0,this.playing)return this.playing.promise;if(this.host.ended)return this.seek(0,!0);if(!this.host.paused&&!this.seeking)return Promise.resolve();const e=this.operation();return this.playing=e,this.runPlay(e).then(e.resolve,e.reject),e.promise}runPlay(e){return Y(this,null,function*(){const t=()=>this.current(e,"playing")&&this.wanted;try{for(;this.seeking;)if(yield this.seeking.complete.promise,!t())return;if(!t())return;if(this.host.paused=!1,yield this.host.audio.play(),!t())return void(this.wanted&&!this.host.destroyed||this.host.audio.pause());this.host.video.start(this.host.audio),ec(this.host.events,t,["play","playing"])}catch(i){if(!t())return;this.wanted=!1,this.host.paused=!0;try{this.stopEngines()}catch(r){console.warn("MediaBunny play cleanup error:",r)}throw i}finally{this.playing===e&&(this.playing=null)}})}seek(e,t){return this.position(t=>Y(this,null,function*(){const i=this.host.audio.seek(e),r=t()?this.host.video.seek(e):Promise.resolve();yield Promise.all([i,r])}),["seeked"],!1,t)}replace(e,t){return this.position(i=>Y(this,null,function*(){e.duration=yield hc(e),i()&&(this.host.media=e,yield Promise.all([this.host.video.load(e),this.host.audio.load(e)]),i()&&(yield Promise.all([this.host.video.seek(t),this.host.audio.seek(t)]),i()&&(this.host.readyState=4,this.host.networkState=1)))}),["loadedmetadata","durationchange","progress","loadeddata","canplay","canplaythrough","seeked"],!0)}position(e,t,i,r){if(this.host.destroyed)return Promise.resolve();this.wanted=null!=r?r:this.seeking?this.wanted:!this.host.paused,this.cancelPlay();const n=this.seeking,s=this.operation();return this.seeking=s,null==n||n.complete.resolve(),null==n||n.resolve(),this.runPosition(s,e,t,i).then(s.resolve,s.reject),s.promise}runPosition(e,t,i,r){return Y(this,null,function*(){const n=()=>this.current(e,"seeking");let s=!1;try{if(r&&this.stop(),!n())return;if(this.host.ended=!1,this.host.seeking=!0,ec(this.host.events,n,["seeking","waiting"]),!n())return;if(r||this.stop(),!n())return;if(yield t(n),!n())return;if(this.host.seeking=!1,e.complete.resolve(),ec(this.host.events,n,i),!n())return;this.seeking=null,s=this.wanted}catch(a){if(!n())return;throw this.host.seeking=!1,this.wanted=!1,this.cancelPlay(),this.host.reportError(a),a}finally{e.complete.resolve(),this.seeking===e&&(this.seeking=null)}s&&(yield this.play())})}}const pc=new WeakMap,gc=new WeakMap;function kc(e){const t=gc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.next()).then(e=>{var t;return null!=(t=e.value)?t:null});gc.set(e,i);const r=()=>{gc.get(e)===i&&gc.delete(e)};return i.then(r,r),i}function yc(e,t,i,r,n){const s=i?Math.max(.06,r/Math.max(1,n)):0;return i&&e{if(this.image===n&&t()){this.cancel();try{i(n)}catch(e){r(e)}}},n.onerror=()=>{this.image===n&&this.cancel()},n.src=e}}class Tc{constructor(e,t,i,r){this.host=e,this.ready=t,this.draw=i,this.failure=r,this.stopped=!1,this.closed=!1,this.scheduled=null,this.fetching=null}current(e){return!this.closed&&!this.stopped&&this.host.asyncId===e}update(e){return Y(this,null,function*(){var t;const i=this.host.videoIterator;if(!i||!this.ready()||!this.current(e)||this.host.isFetching)return;const r={};this.fetching=r,this.host.isFetching=!0;const n=()=>this.current(e)&&this.host.videoIterator===i;try{for(;n();){const e=yield kc(i);if(!n()||!e)return;const r=null==(t=this.host.audioClock)?void 0:t.currentTime;if(void 0===r)return;const s=yc(e.timestamp,r,this.host.dropLateFrames,this.host.avSyncTolerance,this.host.playbackRate);if("skip"!==s){if("draw"!==s)return void(this.host.nextFrame=e);this.draw(e)}}}catch(s){if(n())throw s}finally{this.fetching===r&&(this.fetching=null,this.host.isFetching=!1)}})}request(e){this.update(e).catch(t=>{this.current(e)&&(this.stop(),this.report(t))})}report(e){try{this.failure(e)}catch(t){console.warn("MediaBunny video error listener:",t)}}cancelFrame(){null!==this.scheduled&&(cancelAnimationFrame(this.scheduled),this.scheduled=null)}schedule(e){if(!this.current(e))return;this.cancelFrame();const t=requestAnimationFrame(()=>{if(this.scheduled===t&&this.current(e)){this.scheduled=null;try{this.render()}catch(i){this.stop(),this.report(i)}}});this.scheduled=t,this.host.rafId=t}render(){const e=this.host.asyncId,t=()=>this.current(e);if(!t()||!this.host.audioClock)return;const i=this.host.audioClock.currentTime,r=Date.now();if(r-this.host.lastTimeUpdate>=this.host.timeupdateInterval){if(this.host.events.emit("timeupdate"),!t())return;this.host.lastTimeUpdate=r}if(this.ready()){if(Number.isFinite(this.host.duration)&&i>=this.host.duration){this.stop(),this.host.stalled=!1;const e=this.host.asyncId;return void ec(this.host.events,()=>!this.closed&&this.host.asyncId===e,["ended","pause","canplay"])}if(this.host.nextFrame&&this.host.nextFrame.timestamp<=i){if(this.draw(this.host.nextFrame),this.host.nextFrame=null,this.request(e),this.host.stalled){if(ec(this.host.events,t,["canplay","playing"]),!t())return;this.host.stalled=!1}}else this.host.nextFrame||(this.request(e),Number.isFinite(this.host.duration)&&i!K(this,T),e=>G(this,P,E).call(this,e,!0),e=>G(this,P,C).call(this,e)))}preflight(e,t,i){return Y(this,null,function*(){return function(e,t,i,r,n=()=>!0){return Y(this,null,function*(){if((null==r?void 0:r.aborted)||!n())return!1;if(!t||"string"!==typeof e||cc(e))return!0;try{const t=yield fetch(e,r?{method:"HEAD",signal:r}:{method:"HEAD"});if((null==r?void 0:r.aborted)||!n())return!1;const s=t.headers.get("accept-ranges");return!(!s||"none"===s)||(i.emit("error",new Event("RangeNotSupported")),!1)}catch(s){return!((null==r?void 0:r.aborted)||!n())&&(console.warn("Preflight check failed:",s),!0)}})}(e,this.preflightRange,this.events,t,i)})}drawPoster(){if(K(this,b)||!this.poster||this.posterDrawn)return;const e=K(this,m);K(this,v).draw(this.poster,()=>G(this,P,I).call(this,e),e=>{this.clear(),this.canvas.width=e.naturalWidth||this.canvas.width,this.canvas.height=e.naturalHeight||this.canvas.height,G(this,P,x).call(this).drawImage(e,0,0,this.canvas.width,this.canvas.height),this.posterDrawn=!0},e=>G(this,P,C).call(this,e))}stopIterator(){return Y(this,null,function*(){const e=this.videoIterator;this.videoIterator=null,this.nextFrame=null,yield function(e){if(!e)return Promise.resolve();const t=pc.get(e);if(t)return t;const i=Promise.resolve().then(()=>e.return()).then(()=>{});return pc.set(e,i),i}(e)})}clear(){G(this,P,x).call(this).clearRect(0,0,this.canvas.width,this.canvas.height)}cancelPending(){Q(this,m)._++,Q(this,p)._++,this.stop(),G(this,P,B).call(this),K(this,v).cancel(),$(this,T,!1),$(this,g,null),$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null}load(e,t){return Y(this,null,function*(){if(K(this,b))return;this.cancelPending();const i=K(this,m),r=K(this,p);$(this,T,!0);const n=Promise.resolve().then(()=>G(this,P,_).call(this,e,i,r,t));$(this,g,n);try{yield n}finally{K(this,g)===n&&$(this,g,null)}})}handleNoVideoTrack(){K(this,b)||(this.videoSink=null,this.width=0,this.height=0,this.canvas.width=0,this.canvas.height=0,this.clear(),this.drawPoster())}resetIterator(e){return Y(this,null,function*(){if(K(this,b))return;const t=K(this,m),i=++Q(this,p)._,r=K(this,g);this.stop(),K(this,v).cancel(),$(this,T,!0);try{r&&(yield r),yield G(this,P,R).call(this,e,t,i)}catch(n){if(G(this,P,I).call(this,t)&&K(this,p)===i)throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})}updateNextFrame(e){return Y(this,null,function*(){yield K(this,w).update(e)})}render(){K(this,w).render()}start(e){K(this,w).start(e)}stop(){K(this,w).stop()}seek(e){return Y(this,null,function*(){yield this.resetIterator(e)})}setPlaybackRate(e){this.playbackRate=Math.max(.1,Number(e)||1)}destroy(){K(this,b)||($(this,b,!0),Q(this,m)._++,K(this,w).destroy(),K(this,v).cancel(),G(this,P,B).call(this),this.posterDrawn=!1,$(this,k,null),$(this,y,null),this.videoSink=null,this.input=null,this.audioClock=null)}}m=new WeakMap,p=new WeakMap,g=new WeakMap,k=new WeakMap,y=new WeakMap,b=new WeakMap,T=new WeakMap,v=new WeakMap,w=new WeakMap,S=new WeakMap,P=new WeakSet,I=function(e){return!K(this,b)&&K(this,m)===e},x=function(){if(!this.ctx)throw new Error("Canvas 2D context is unavailable.");return this.ctx},C=function(e){K(this,b)||(G(this,P,B).call(this),K(this,S)?K(this,S).call(this,e):this.events.emit("error",e))},B=function(){this.stopIterator().catch(e=>console.warn("MediaBunny iterator cleanup error:",e))},E=function(e,t){K(this,v).cancel(),t&&this.clear(),G(this,P,x).call(this).drawImage(e.canvas,0,0)},_=function(e,t,i,r){return Y(this,null,function*(){if(G(this,P,I).call(this,t))try{this.clear(),this.posterDrawn=!1;const{input:n,videoTrack:s,duration:a}=e;if(this.input=n,this.duration=a,!s)return this.handleNoVideoTrack(),void(null==r||r());const o=null!==s.codec&&(yield s.canDecode());if(!G(this,P,I).call(this,t))return;if(!o)return this.handleNoVideoTrack(),void(null==r||r());const l=yield s.canBeTransparent();if(!G(this,P,I).call(this,t))return;$(this,k,()=>new Go(s,{poolSize:2,fit:"contain",alpha:l})),this.videoSink=K(this,k).call(this),this.width=s.displayWidth,this.height=s.displayHeight,this.canvas.width=this.width,this.canvas.height=this.height,null==r||r(),G(this,P,I).call(this,t)&&(yield G(this,P,R).call(this,0,t,i))}catch(n){if(G(this,P,I).call(this,t))throw G(this,P,B).call(this),n}finally{G(this,P,I).call(this,t)&&K(this,p)===i&&$(this,T,!1)}})},R=function(e,t,i){return Y(this,null,function*(){if(!G(this,P,I).call(this,t)||K(this,p)!==i)return;G(this,P,B).call(this),K(this,k)&&this.videoSink===K(this,y)&&(this.videoSink=K(this,k).call(this));const r=this.videoSink;if(!r||!G(this,P,I).call(this,t))return;$(this,y,r);const n=r.canvases(e);this.videoIterator=n;const s=()=>G(this,P,I).call(this,t)&&K(this,p)===i&&this.videoIterator===n,a=yield kc(n);if(!s())return;const o=yield kc(n);s()&&(this.nextFrame=o,a?G(this,P,E).call(this,a,!1):this.drawPoster())})};class wc{constructor({canvas:e,ctx:t,events:i,option:r={}}){var n,s,a,o,l;X(this,F),this.events=i,this.option=r,this.audio=new ic(i,e=>{try{this.pause()}catch(t){console.warn("MediaBunny audio coordinator cleanup:",t)}this.reportError(e)}),this.video=new vc({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,onError:e=>{try{this.pause()}catch(t){console.warn("MediaBunny video failure cleanup:",t)}this.reportError(e)}}),this.paused=!0,this.ended=!1,this.readyState=0,this.networkState=0,this.error=null,this.seeking=!1,this.loadSeq=0,this.input=null,this.media=null,this.loadSession=null,this.destroyed=!1,$(this,F,new mc(this)),i.addEventListener("ended",()=>{this.destroyed||(this.ended=!0,this.paused=!0,K(this,F).ended(),this.audio.pause())})}load(e){return Y(this,null,function*(){var t,i;if(this.destroyed)return;const r=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),null==(t=this.loadSession)||t.cancel(),r!==this.loadSeq||this.destroyed)return;if(this.pause(),r!==this.loadSeq||this.destroyed)return;this.disposeInput();const n=new dc;this.loadSession=n,this.ended=!1,this.error=null,this.networkState=2,this.readyState=0,n.defer(()=>this.events.emit("waiting")),n.defer(()=>this.events.emit("loadstart"));const s=Number.isFinite(this.option.loadTimeout)&&null!=(i=this.option.loadTimeout)?i:0;try{yield n.wait(this.performLoad(e,r,n),s)}catch(a){if(r!==this.loadSeq)return;const e=++this.loadSeq;if(K(this,F).invalidate(),this.video.cancelPending(),this.audio.cancelPending(),n.cancel(),e!==this.loadSeq||this.destroyed)return;this.disposeInput(),this.reportError(a)}})}performLoad(e,t){return Y(this,arguments,function*(e,t,i=this.loadSession){const r=()=>!this.destroyed&&t===this.loadSeq;if(!i||!(yield this.video.preflight(e,i.signal,r))||!r())return;const n=uc(e);if(!n)return this.video.handleNoVideoTrack(),void(r()&&this.audio.handleNoAudioTrack());i.own(n);const s=yield function(e,t){return Y(this,null,function*(){const i=yield e.getPrimaryVideoTrack(),r=i?yield i.getPrimaryPairableAudioTrack():yield e.getPrimaryAudioTrack(),n=yield hc({input:e,videoTrack:i,audioTrack:r}),s=i||r,a=cc(t);return{input:e,videoTrack:i,audioTrack:r,duration:n,isLive:!Number.isFinite(n)&&Boolean(s&&(yield s.isLive())),isHls:a,videoMode:a?"auto":"manual",audioMode:a?"auto":"manual"}})}(n,e);if(!r())return;if(!s.videoTrack&&!s.audioTrack)throw this.video.handleNoVideoTrack(),this.video.duration=Number.NaN,this.audio.duration=Number.NaN,new Error("Input has no audio or video tracks.");this.input=n,this.media=s;const a=function(e,t){let i=!1,r=!1,n=!1;function s(s){t()&&!n&&("video"===s?i=!0:r=!0,i&&r&&(n=!0,e()))}return{video:()=>s("video"),audio:()=>s("audio")}}(()=>{this.readyState=1,ec(this.events,r,["loadedmetadata","durationchange","progress"])},r);try{const e=this.video.load(s,a.video),t=r()?this.audio.load(s,a.audio):Promise.resolve();if(yield Promise.all([e,t]),!r())return;this.readyState=4,this.networkState=1,ec(this.events,r,["loadeddata","canplay","canplaythrough","progress"])}catch(o){if(!r())return;throw console.error("MediaBunny load error:",o),o}})}createTimeout(e){return new Promise((t,i)=>{setTimeout(()=>i(new Error("Load timeout")),e)})}disposeInput(){var e;null==(e=this.loadSession)||e.disposeInput(),this.input=null,this.media=null}replaceTracks(e){return Y(this,null,function*(){if(this.media&&!this.destroyed)return K(this,F).replace(H(H({},this.media),e),this.currentTime)})}selectHlsQuality(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,sc)}(this,e)})}selectHlsAudio(e){return Y(this,null,function*(){return function(e,t){return nc(e,t,ac)}(this,e)})}getHlsState(){return Y(this,null,function*(){const e=this.media,t=this.loadSeq;if(this.destroyed)return null;try{const i=yield function(e){return Y(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)=>Y(null,null,function*(){return{id:e.id,track:e,index:t,name:yield e.getName(),height:yield e.getDisplayHeight(),bitrate:yield oc(e)}}))),Promise.all(a.map((e,t)=>Y(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 oc(e)}})))]);return{levels:o,audios:l,currentLevel:e.videoTrack&&null!=(t=o.find(t=>{var i;return t.id===(null==(i=e.videoTrack)?void 0:i.id)}))?t:null,currentAudio:e.audioTrack&&null!=(i=l.find(t=>{var i;return t.id===(null==(i=e.audioTrack)?void 0:i.id)}))?i:null,videoMode:null!=(r=e.videoMode)?r:"auto",audioMode:null!=(n=e.audioMode)?n:"auto"}})}(e);return this.destroyed||this.loadSeq!==t||this.media!==e?null:i}catch(i){if(this.destroyed||this.loadSeq!==t||this.media!==e)return null;throw i}})}play(){return Y(this,null,function*(){return K(this,F).play()})}pause(){K(this,F).pause()}seek(e){return Y(this,null,function*(){return K(this,F).seek(e)})}setVolume(e,t){this.audio.setVolume(e,t)}setPlaybackRate(e){this.audio.setPlaybackRate(e),this.video.setPlaybackRate(e)}reportError(e){if(this.destroyed)return;const t=e&&"object"===typeof e?Reflect.get(e,"message"):void 0;this.error={code:4,message:"string"===typeof t?t:String(e)},this.networkState=3,this.events.emit("error")}destroy(){if(this.destroyed)return;this.destroyed=!0,this.loadSeq++,K(this,F).invalidate();const e=[];for(const i of[()=>{var e;return null==(e=this.loadSession)?void 0:e.cancel()},()=>this.pause(),()=>this.disposeInput(),()=>this.audio.destroy(),()=>this.video.destroy()])try{i()}catch(t){e.push(t)}if(e.length)throw e[0]}get currentTime(){return this.audio.currentTime}get duration(){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}}F=new WeakMap;const Sc=new WeakMap;function Pc(e){let t=Sc.get(e);return t||(t={closed:!1,frames:new Set},Sc.set(e,t)),t}class Ic{constructor({art:e,canvas:t,ctx:i,option:r}){var n,s;this.art=e,this.canvas=t,this.option=r,this.events=new ae,this.engine=new wc({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){Promise.resolve(this.engine.seek(Number(e)||0)).catch(()=>{})}get duration(){return this.engine.duration}get buffered(){return this.createTimeRanges(0,this.engine.duration)}get played(){return this.createTimeRanges(0,this.engine.currentTime)}get seekable(){return this.createTimeRanges(0,this.engine.duration)}createTimeRanges(e,t){return function(e,t,i){return!e||Number.isNaN(e)||i<=0?{length:0,start:()=>0,end:()=>0}:{length:1,start:()=>t,end:()=>i}}(this.engine.duration,e,t)}get paused(){return this.engine.paused}get playing(){return!this.engine.paused&&!this.engine.ended}get ended(){return this.engine.ended}get seeking(){return this.engine.seeking}get readyState(){return this.engine.readyState}get networkState(){return this.engine.networkState}get error(){return this.engine.error}get playbackRate(){return this._playbackRate}set playbackRate(e){const t=Number(e);Number.isNaN(t)||t<=0||(this._playbackRate=t,this.engine.setPlaybackRate(t),this.events.emit("ratechange"))}get volume(){return this._volume}set volume(e){var t;this._volume=(t=e,Math.max(0,Math.min(1,Number(t)||0))),this._muted=!1,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}get muted(){return this._muted}set muted(e){this._muted=!!e,this.engine.setVolume(this._volume,this._muted),this.events.emit("volumechange")}play(){return this.engine.play()}pause(){this.engine.pause()}load(){this._src&&this.engine.load(this._src)}getM3u8State(){return this.engine.getHlsState()}switchM3u8Quality(e){return this.engine.selectHlsQuality(e)}switchM3u8Audio(e){return this.engine.selectHlsAudio(e)}get videoWidth(){return this.engine.videoWidth}get videoHeight(){return this.engine.videoHeight}get poster(){return this.option.poster||""}set poster(e){this.option.poster=e}get autoplay(){return this.option.autoplay||!1}set autoplay(e){}get loop(){return this.option.loop||!1}set loop(e){}get controls(){return!1}set controls(e){}get playsInline(){return!0}set playsInline(e){}get crossOrigin(){return this.option.crossOrigin||""}set crossOrigin(e){}get preload(){return"auto"}set preload(e){}get defaultMuted(){return!1}set defaultMuted(e){}get defaultPlaybackRate(){return 1}set defaultPlaybackRate(e){}canPlayType(e){return"maybe"}getBoundingClientRect(){return this.canvas.getBoundingClientRect()}requestVideoFrameCallback(e){return function(e,t){const i=Pc(e);if(i.closed)return 0;const r=requestAnimationFrame(n=>{i.frames.delete(r),i.closed||t(n,{presentationTime:e.engine.currentTime,expectedDisplayTime:n+16.6,width:e.engine.videoWidth,height:e.engine.videoHeight,mediaTime:e.engine.currentTime,presentedFrames:0,processingDuration:0,captureTime:n,receiveTime:n,rtpTimestamp:0})});return i.frames.add(r),r}(this,e)}cancelVideoFrameCallback(e){!function(e,t){Pc(e).frames.delete(t),cancelAnimationFrame(t)}(this,e)}setAttribute(e,t){"src"===e?this.src=t:"autoplay"===e?this.autoplay=t:"loop"===e?this.loop=t:"muted"===e?this.muted=!0:Reflect.apply(this.canvas.setAttribute,this.canvas,[e,t])}destroy(){if(function(e){const t=Pc(e);if(t.closed)return!1;t.closed=!0;for(const i of t.frames)cancelAnimationFrame(i);return t.frames.clear(),!0}(this))try{this.engine.destroy()}finally{this.events.destroy()}}}function xc(e={}){return t=>{const i=t,{createElement:r}=i.constructor.utils,n=r("canvas"),s=new Ic({art:i,canvas:n,ctx:n.getContext("2d"),option:e}),a=function(e,t,i,r){let n,s=!1;function a(){var i;s||!(null==(i=e.template)?void 0:i.$player)||e.option.autoSize||Object.assign(t.style,{width:"100%",height:"100%",objectFit:"contain"})}function o(){s||(s=!0,ie([()=>null==n?void 0:n.destroy(),()=>{e.mediabunny===i&&delete e.mediabunny},()=>i.destroy(),()=>{var t;return null==(t=e.off)?void 0:t.call(e,"resize",a)},()=>{var t;return null==(t=e.off)?void 0:t.call(e,"video:loadedmetadata",a)},()=>{var t;return null==(t=e.off)?void 0:t.call(e,"destroy",o)}]))}return{install:function(){e.on("resize",a),e.on("video:loadedmetadata",a),n=se({art:e,shim:i,option:r}),e.on("destroy",o)},destroy:o}}(i,n,s,e);try{i.mediabunny=s,function(e,t){const i=new Map,r=e,n=t;for(const a in e)if("function"===typeof r[a]){const t=r[a];i.set(a,t.bind(e))}const s=new Set([...Object.getOwnPropertyNames(t),...Object.getOwnPropertyNames(Object.getPrototypeOf(t))]);for(const a of s)"constructor"===a||a in e||Object.defineProperty(e,a,{get(){const e=n[a];return"function"===typeof e?e.bind(t):e},set(e){n[a]=e},configurable:!0,enumerable:!0});for(const[a,o]of i)r[a]=(...e)=>o(...e)}(n,s),a.install()}catch(o){try{a.destroy()}catch(l){console.warn("MediaBunny entry setup cleanup:",l)}throw o}return n}}return Object.defineProperty(xc,"default",{value:xc,writable:!0,configurable:!0}),xc}); diff --git a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs index f6e84117c..0d30a4e5f 100644 --- a/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs +++ b/packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs @@ -21,8 +21,38 @@ var __privateWrapper = (obj, member, setter, getter) => ({ } }); var _closed, _closed2, _generation, _contexts, _nodes, _pump, _playTask, _playing, _loading, _onError, _AudioEngine_instances, load_fn, startPump_fn, play_fn, _generation2, _iteration, _loading2, _createSink, _usedSink, _destroyed, _preparing, _poster, _renderer, _onError2, _VideoEngine_instances, current_fn, context_fn, report_fn, release_fn, draw_fn, load_fn2, reset_fn, _playback; -const $audio = ''; -const $quality = ''; +function bridgeCanvas(canvas, shim) { + const methods = /* @__PURE__ */ new Map(); + const native = canvas; + const members = shim; + for (const name in canvas) { + if (typeof native[name] === "function") { + const method = native[name]; + methods.set(name, method.bind(canvas)); + } + } + const names = /* @__PURE__ */ new Set([ + ...Object.getOwnPropertyNames(shim), + ...Object.getOwnPropertyNames(Object.getPrototypeOf(shim)) + ]); + for (const name of names) { + if (name === "constructor" || name in canvas) + continue; + Object.defineProperty(canvas, name, { + get() { + const value = members[name]; + return typeof value === "function" ? value.bind(shim) : value; + }, + set(value) { + members[name] = value; + }, + configurable: true, + enumerable: true + }); + } + for (const [name, method] of methods) + native[name] = (...args) => method(...args); +} function releaseAll(actions) { const failures = []; for (const action of actions) { @@ -35,6 +65,8 @@ function releaseAll(actions) { if (failures.length) throw failures[0]; } +const $audio = ''; +const $quality = ''; function createMenu(art, name, icon) { const owned = { control: false, setting: false }; let model = null; @@ -218,12 +250,49 @@ function setupM3u8Controls({ art, shim, option }) { console.warn("MediaBunny HLS listener cleanup:", error); } } - art.on("video:loadedmetadata", refresh); - art.on("restart", refresh); - art.on("video:loadstart", invalidate); - art.on("video:error", invalidate); - art.on("destroy", destroy); - return { update }; + try { + art.on("video:loadedmetadata", refresh); + art.on("restart", refresh); + art.on("video:loadstart", invalidate); + art.on("video:error", invalidate); + art.on("destroy", destroy); + } catch (error) { + destroy(); + throw error; + } + return { update, destroy }; +} +function entryLifecycle(art, canvas, shim, option) { + let closed = false; + let controls; + function resize() { + if (closed || !art.template?.$player || art.option.autoSize) + return; + Object.assign(canvas.style, { width: "100%", height: "100%", objectFit: "contain" }); + } + function destroy() { + if (closed) + return; + closed = true; + releaseAll([ + () => controls?.destroy(), + () => { + if (art.mediabunny === shim) + delete art.mediabunny; + }, + () => shim.destroy(), + () => art.off?.("resize", resize), + () => art.off?.("video:loadedmetadata", resize), + () => art.off?.("destroy", destroy) + ]); + } + function install() { + art.on("resize", resize); + art.on("video:loadedmetadata", resize); + controls = setupM3u8Controls({ art, shim, option }); + art.on("destroy", destroy); + } + return { install, destroy }; } class EventTarget { constructor() { @@ -26143,68 +26212,28 @@ class VideoShim { } } function artplayerProxyMediabunny(option = {}) { - return (art) => { - const { constructor } = art; - const { createElement } = constructor.utils; + return (player) => { + const art = player; + const { createElement } = art.constructor.utils; const canvas = createElement("canvas"); - const ctx = canvas.getContext("2d"); - const shim = new VideoShim({ - art, - canvas, - ctx, - option - }); - art.mediabunny = shim; - const originalCanvasMethods = {}; - for (const prop in canvas) { - if (typeof canvas[prop] === "function") { - originalCanvasMethods[prop] = canvas[prop].bind(canvas); + const shim = new VideoShim({ art, canvas, ctx: canvas.getContext("2d"), option }); + const lifecycle = entryLifecycle(art, canvas, shim, option); + try { + art.mediabunny = shim; + bridgeCanvas(canvas, shim); + lifecycle.install(); + } catch (error) { + try { + lifecycle.destroy(); + } catch (failure) { + console.warn("MediaBunny entry setup cleanup:", failure); } + throw error; } - const propertyNames = /* @__PURE__ */ new Set([ - ...Object.getOwnPropertyNames(shim), - ...Object.getOwnPropertyNames(Object.getPrototypeOf(shim)) - ]); - for (const prop of propertyNames) { - if (prop === "constructor") - continue; - if (!(prop in canvas)) { - Object.defineProperty(canvas, prop, { - get() { - const value = shim[prop]; - return typeof value === "function" ? value.bind(shim) : value; - }, - set(v) { - shim[prop] = v; - }, - configurable: true, - enumerable: true - }); - } - } - for (const prop in originalCanvasMethods) { - canvas[prop] = (...args) => originalCanvasMethods[prop](...args); - } - function resize() { - const player = art.template?.$player; - if (!player || art.option.autoSize) - return; - Object.assign(canvas.style, { - width: "100%", - height: "100%", - objectFit: "contain" - }); - } - art.on("resize", resize); - art.on("video:loadedmetadata", resize); - setupM3u8Controls({ art, shim, option }); - art.on("destroy", () => { - delete art.mediabunny; - shim.destroy(); - }); return canvas; }; } +Object.defineProperty(artplayerProxyMediabunny, "default", { value: artplayerProxyMediabunny, writable: true, configurable: true }); export { artplayerProxyMediabunny as default }; diff --git a/packages/artplayer-proxy-mediabunny/package.json b/packages/artplayer-proxy-mediabunny/package.json index 85e81e67e..3744cbc50 100644 --- a/packages/artplayer-proxy-mediabunny/package.json +++ b/packages/artplayer-proxy-mediabunny/package.json @@ -19,14 +19,24 @@ ], "exports": { ".": { - "types": "./types/artplayer-proxy-mediabunny.d.ts", - "import": "./dist/artplayer-proxy-mediabunny.mjs", - "require": "./dist/artplayer-proxy-mediabunny.js" + "import": { + "types": "./types/artplayer-proxy-mediabunny.d.mts", + "default": "./dist/artplayer-proxy-mediabunny.mjs" + }, + "require": { + "types": "./types/artplayer-proxy-mediabunny.d.ts", + "default": "./dist/artplayer-proxy-mediabunny.js" + } }, "./legacy": { - "types": "./types/artplayer-proxy-mediabunny.d.ts", - "import": "./dist/artplayer-proxy-mediabunny.legacy.js", - "require": "./dist/artplayer-proxy-mediabunny.legacy.js" + "import": { + "types": "./types/artplayer-proxy-mediabunny.d.mts", + "default": "./dist/artplayer-proxy-mediabunny.legacy.js" + }, + "require": { + "types": "./types/artplayer-proxy-mediabunny.d.ts", + "default": "./dist/artplayer-proxy-mediabunny.legacy.js" + } } }, "main": "./dist/artplayer-proxy-mediabunny.js", @@ -34,6 +44,11 @@ "types": "./types/artplayer-proxy-mediabunny.d.ts", "legacy": "./dist/artplayer-proxy-mediabunny.legacy.js", "browserslist": "last 1 Chrome version", + "typesVersions": { + "*": { + "legacy": ["types/artplayer-proxy-mediabunny.d.ts"] + } + }, "dependencies": { "mediabunny": "^1.43.1" } diff --git a/packages/artplayer-proxy-mediabunny/src/VideoShim.ts b/packages/artplayer-proxy-mediabunny/src/VideoShim.ts index 46d3215e5..b203ca9be 100644 --- a/packages/artplayer-proxy-mediabunny/src/VideoShim.ts +++ b/packages/artplayer-proxy-mediabunny/src/VideoShim.ts @@ -1,3 +1,4 @@ +import type { MediaBunnyShim, SyntheticFrameCallback } from '../types/artplayer-proxy-mediabunny' import type { EngineOptions, EnginePort, ProxyOptions, ShimHost } from './engine-types' import type { MediaListener } from './EventTarget' import EventTarget from './EventTarget' @@ -5,7 +6,7 @@ import MediaBunnyEngine from './MediaBunnyEngine.js' import { cancelFrame, closeFrames, requestFrame } from './shim-frames' import { clampVolume, timeRanges } from './shim-values' -export default class VideoShim { +export default class VideoShim implements MediaBunnyShim { declare art: ShimHost declare canvas: HTMLCanvasElement declare option: ProxyOptions @@ -82,7 +83,7 @@ export default class VideoShim { } // Time - get currentTime() { + get currentTime(): number { return this.engine.currentTime } @@ -143,7 +144,7 @@ export default class VideoShim { } // Playback rate - get playbackRate() { + get playbackRate(): number { return this._playbackRate } @@ -158,7 +159,7 @@ export default class VideoShim { } // Volume - get volume() { + get volume(): number { return this._volume } @@ -169,7 +170,7 @@ export default class VideoShim { this.events.emit('volumechange') } - get muted() { + get muted(): boolean { return this._muted } @@ -223,56 +224,56 @@ export default class VideoShim { this.option.poster = v } - get autoplay() { + get autoplay(): boolean { return this.option.autoplay || false } set autoplay(v: unknown) {} - get loop() { + get loop(): boolean { return this.option.loop || false } set loop(v: unknown) {} - get controls() { + get controls(): boolean { return false } set controls(v: unknown) {} - get playsInline() { + get playsInline(): boolean { return true } set playsInline(v: unknown) {} - get crossOrigin() { + get crossOrigin(): string { return this.option.crossOrigin || '' } set crossOrigin(v: unknown) {} - get preload() { + get preload(): string { return 'auto' } set preload(v: unknown) {} - get defaultMuted() { + get defaultMuted(): boolean { return false } set defaultMuted(v: unknown) {} - get defaultPlaybackRate() { + get defaultPlaybackRate(): number { return 1 } set defaultPlaybackRate(v: unknown) {} // Methods - canPlayType(_type: string) { + canPlayType(_type: string): 'maybe' { return 'maybe' } @@ -280,7 +281,7 @@ export default class VideoShim { return this.canvas.getBoundingClientRect() } - requestVideoFrameCallback(callback: VideoFrameRequestCallback): number { + requestVideoFrameCallback(callback: SyntheticFrameCallback): number { return requestFrame(this, callback) } diff --git a/packages/artplayer-proxy-mediabunny/src/canvas-bridge.ts b/packages/artplayer-proxy-mediabunny/src/canvas-bridge.ts new file mode 100644 index 000000000..0f24aed92 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/canvas-bridge.ts @@ -0,0 +1,36 @@ +import type VideoShim from './VideoShim' + +export function bridgeCanvas(canvas: HTMLCanvasElement, shim: VideoShim): void { + const methods = new Map unknown>() + // Dynamic forwarding is intentional: own and direct-prototype members are historical API. + const native = canvas as unknown as Record + const members = shim as unknown as Record + for (const name in canvas) { + if (typeof native[name] === 'function') { + // Preserve the historical second read, including accessor side effects and binding errors. + const method = native[name] as (...args: unknown[]) => unknown + methods.set(name, method.bind(canvas)) + } + } + const names = new Set([ + ...Object.getOwnPropertyNames(shim), + ...Object.getOwnPropertyNames(Object.getPrototypeOf(shim)), + ]) + for (const name of names) { + if (name === 'constructor' || name in canvas) + continue + Object.defineProperty(canvas, name, { + get() { + const value = members[name] + return typeof value === 'function' ? value.bind(shim) : value + }, + set(value: unknown) { + members[name] = value + }, + configurable: true, + enumerable: true, + }) + } + for (const [name, method] of methods) + native[name] = (...args: unknown[]) => method(...args) +} diff --git a/packages/artplayer-proxy-mediabunny/src/cleanup.ts b/packages/artplayer-proxy-mediabunny/src/cleanup.ts new file mode 100644 index 000000000..dad4be473 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/cleanup.ts @@ -0,0 +1,11 @@ +export function releaseAll(actions: (() => void)[]): void { + const failures: unknown[] = [] + for (const action of actions) { + try { + action() + } + catch (error) { failures.push(error) } + } + if (failures.length) + throw failures[0] +} diff --git a/packages/artplayer-proxy-mediabunny/src/entry-lifecycle.ts b/packages/artplayer-proxy-mediabunny/src/entry-lifecycle.ts new file mode 100644 index 000000000..9fe6f11e7 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/entry-lifecycle.ts @@ -0,0 +1,45 @@ +import type { ProxyOptions, ShimHost } from './engine-types' +import type { MenuHost } from './m3u8-types' +import type VideoShim from './VideoShim' +import { releaseAll } from './cleanup' +import { setupM3u8Controls } from './m3u8' + +export interface EntryHost extends ShimHost, MenuHost { + constructor: ShimHost['constructor'] & { utils: { createElement: (tag: 'canvas') => HTMLCanvasElement } } + option: ShimHost['option'] & { autoSize?: boolean } + template?: { $player?: HTMLElement } + mediabunny?: unknown +} + +export function entryLifecycle(art: EntryHost, canvas: HTMLCanvasElement, shim: VideoShim, option: ProxyOptions) { + let closed = false + let controls: ReturnType + function resize(): void { + if (closed || !art.template?.$player || art.option.autoSize) + return + Object.assign(canvas.style, { width: '100%', height: '100%', objectFit: 'contain' }) + } + function destroy(): void { + if (closed) + return + closed = true + releaseAll([ + () => controls?.destroy(), + () => { + if (art.mediabunny === shim) + delete art.mediabunny + }, + () => shim.destroy(), + () => art.off?.('resize', resize), + () => art.off?.('video:loadedmetadata', resize), + () => art.off?.('destroy', destroy), + ]) + } + function install(): void { + art.on('resize', resize) + art.on('video:loadedmetadata', resize) + controls = setupM3u8Controls({ art, shim, option }) + art.on('destroy', destroy) + } + return { install, destroy } +} diff --git a/packages/artplayer-proxy-mediabunny/src/index.js b/packages/artplayer-proxy-mediabunny/src/index.js deleted file mode 100644 index 3391c4885..000000000 --- a/packages/artplayer-proxy-mediabunny/src/index.js +++ /dev/null @@ -1,89 +0,0 @@ -import { setupM3u8Controls } from './m3u8.js' -/** - * ArtPlayer MediaBunny Proxy - * Main entry point - */ -import VideoShim from './VideoShim.js' - -export default function artplayerProxyMediabunny(option = {}) { - return (art) => { - const { constructor } = art - const { createElement } = constructor.utils - - // Create canvas element - const canvas = createElement('canvas') - const ctx = canvas.getContext('2d') - - // Create video shim - const shim = new VideoShim({ - art, - canvas, - ctx, - option, - }) - art.mediabunny = shim - - // Proxy canvas methods to shim - const originalCanvasMethods = {} - for (const prop in canvas) { - if (typeof canvas[prop] === 'function') { - originalCanvasMethods[prop] = canvas[prop].bind(canvas) - } - } - - // Get all properties from shim instance and prototype - const propertyNames = new Set([ - ...Object.getOwnPropertyNames(shim), - ...Object.getOwnPropertyNames(Object.getPrototypeOf(shim)), - ]) - - // Add shim properties to canvas - for (const prop of propertyNames) { - if (prop === 'constructor') - continue - if (!(prop in canvas)) { - Object.defineProperty(canvas, prop, { - get() { - const value = shim[prop] - return typeof value === 'function' ? value.bind(shim) : value - }, - set(v) { - shim[prop] = v - }, - configurable: true, - enumerable: true, - }) - } - } - - // Restore original canvas methods - for (const prop in originalCanvasMethods) { - canvas[prop] = (...args) => originalCanvasMethods[prop](...args) - } - - // Handle resize - function resize() { - const player = art.template?.$player - if (!player || art.option.autoSize) - return - - Object.assign(canvas.style, { - width: '100%', - height: '100%', - objectFit: 'contain', - }) - } - - art.on('resize', resize) - art.on('video:loadedmetadata', resize) - setupM3u8Controls({ art, shim, option }) - - // Cleanup on destroy - art.on('destroy', () => { - delete art.mediabunny - shim.destroy() - }) - - return canvas - } -} diff --git a/packages/artplayer-proxy-mediabunny/src/index.ts b/packages/artplayer-proxy-mediabunny/src/index.ts new file mode 100644 index 000000000..bcd57ce96 --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/src/index.ts @@ -0,0 +1,33 @@ +import type Artplayer from 'artplayer' +import type { ProxyOptions } from './engine-types' +import type { EntryHost } from './entry-lifecycle' +import { bridgeCanvas } from './canvas-bridge' +import { entryLifecycle } from './entry-lifecycle' +import VideoShim from './VideoShim' + +export default function artplayerProxyMediabunny(option: ProxyOptions = {}) { + return (player: Artplayer): HTMLCanvasElement => { + // Runtime constructor utilities and the owned alias exceed the historical consumer facade. + const art = player as unknown as EntryHost + const { createElement } = art.constructor.utils + const canvas = createElement('canvas') + const shim = new VideoShim({ art, canvas, ctx: canvas.getContext('2d'), option }) + const lifecycle = entryLifecycle(art, canvas, shim, option) + try { + art.mediabunny = shim + bridgeCanvas(canvas, shim) + lifecycle.install() + } + catch (error) { + try { + lifecycle.destroy() + } + catch (failure) { console.warn('MediaBunny entry setup cleanup:', failure) } + throw error + } + return canvas + } +} + +// Restore the 1.0.0 CommonJS namespace path without changing the callable factory type. +Object.defineProperty(artplayerProxyMediabunny, 'default', { value: artplayerProxyMediabunny, writable: true, configurable: true }) diff --git a/packages/artplayer-proxy-mediabunny/src/m3u8-menu.ts b/packages/artplayer-proxy-mediabunny/src/m3u8-menu.ts index 5a9ea744e..517cc1119 100644 --- a/packages/artplayer-proxy-mediabunny/src/m3u8-menu.ts +++ b/packages/artplayer-proxy-mediabunny/src/m3u8-menu.ts @@ -1,16 +1,5 @@ import type { DisplayConfig, Label, MenuHost, MenuModel, SelectorItem } from './m3u8-types' - -export function releaseAll(actions: (() => void)[]): void { - const failures: unknown[] = [] - for (const action of actions) { - try { - action() - } - catch (error) { failures.push(error) } - } - if (failures.length) - throw failures[0] -} +import { releaseAll } from './cleanup' export default function createMenu(art: MenuHost, name: string, icon: string) { const owned = { control: false, setting: false } diff --git a/packages/artplayer-proxy-mediabunny/src/m3u8.ts b/packages/artplayer-proxy-mediabunny/src/m3u8.ts index eb203fb5a..43bf468c8 100644 --- a/packages/artplayer-proxy-mediabunny/src/m3u8.ts +++ b/packages/artplayer-proxy-mediabunny/src/m3u8.ts @@ -1,7 +1,8 @@ import type { Label, SelectorItem, SetupOptions } from './m3u8-types' import $audio from '../../artplayer-plugin-hls-control/src/audio.svg?raw' import $quality from '../../artplayer-plugin-hls-control/src/quality.svg?raw' -import createMenu, { releaseAll } from './m3u8-menu' +import { releaseAll } from './cleanup' +import createMenu from './m3u8-menu' import { audioModel, qualityModel } from './m3u8-model' export function setupM3u8Controls({ art, shim, option }: SetupOptions) { @@ -95,10 +96,16 @@ export function setupM3u8Controls({ art, shim, option }: SetupOptions) { } catch (error) { console.warn('MediaBunny HLS listener cleanup:', error) } } - art.on('video:loadedmetadata', refresh) - art.on('restart', refresh) - art.on('video:loadstart', invalidate) - art.on('video:error', invalidate) - art.on('destroy', destroy) - return { update } + try { + art.on('video:loadedmetadata', refresh) + art.on('restart', refresh) + art.on('video:loadstart', invalidate) + art.on('video:error', invalidate) + art.on('destroy', destroy) + } + catch (error) { + destroy() + throw error + } + return { update, destroy } } diff --git a/packages/artplayer-proxy-mediabunny/src/shim-frames.ts b/packages/artplayer-proxy-mediabunny/src/shim-frames.ts index 4078246e3..68f14ffae 100644 --- a/packages/artplayer-proxy-mediabunny/src/shim-frames.ts +++ b/packages/artplayer-proxy-mediabunny/src/shim-frames.ts @@ -1,3 +1,4 @@ +import type { SyntheticFrameCallback } from '../types/artplayer-proxy-mediabunny' import type { EnginePort } from './engine-types' interface FrameOwner { @@ -20,7 +21,7 @@ function state(owner: FrameOwner): FrameState { return value } -export function requestFrame(owner: FrameOwner, callback: VideoFrameRequestCallback): number { +export function requestFrame(owner: FrameOwner, callback: SyntheticFrameCallback): number { const resource = state(owner) if (resource.closed) return 0 diff --git a/packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.mts b/packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.mts new file mode 100644 index 000000000..161af110f --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.mts @@ -0,0 +1,6 @@ +import type Artplayer from 'artplayer' +import type { Option, Result } from './artplayer-proxy-mediabunny.js' + +declare const artplayerProxyMediabunny: (option?: Option) => (art: Artplayer) => Result +export default artplayerProxyMediabunny +export type { HlsAudio, HlsLevel, HlsState, MediaBunnyCanvas, MediaBunnyPlayer, MediaBunnyShim, MediaListener, Option, Result, SyntheticFrameCallback, SyntheticFrameMetadata } from './artplayer-proxy-mediabunny.js' diff --git a/packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.ts b/packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.ts index 59f257d8b..ef111a094 100644 --- a/packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.ts +++ b/packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.ts @@ -1,6 +1,6 @@ import type Artplayer from 'artplayer' -interface Option { +export interface Option { m3u8?: { quality?: { control?: boolean @@ -101,7 +101,9 @@ interface Option { crossOrigin?: string } -type Result = HTMLCanvasElement +export type Result = HTMLCanvasElement + +export type { HlsAudio, HlsLevel, HlsState, MediaBunnyCanvas, MediaBunnyPlayer, MediaBunnyShim, MediaListener, SyntheticFrameCallback, SyntheticFrameMetadata } from './media' declare const artplayerProxyMediabunny: (option?: Option) => (art: Artplayer) => Result diff --git a/packages/artplayer-proxy-mediabunny/types/media.d.ts b/packages/artplayer-proxy-mediabunny/types/media.d.ts new file mode 100644 index 000000000..b32a3b97c --- /dev/null +++ b/packages/artplayer-proxy-mediabunny/types/media.d.ts @@ -0,0 +1,107 @@ +import type Artplayer from 'artplayer' + +export interface HlsLevel { + id: number + index: number + name: string | null + height: number + bitrate: number + /** SDK object; narrow with the SDK version used by your application. */ + track: unknown +} + +export interface HlsAudio { + id: number + index: number + name: string | null + lang: string + language: string + bitrate: number + /** SDK object; narrow with the SDK version used by your application. */ + track: unknown +} + +export interface HlsState { + levels: HlsLevel[] + audios: HlsAudio[] + currentLevel: HlsLevel | null + currentAudio: HlsAudio | null + videoMode: 'auto' | 'manual' + audioMode: 'auto' | 'manual' +} + +/** Historical RAF estimates, not decoded-frame or network timing measurements. */ +export interface SyntheticFrameMetadata { + /** Historical media time in seconds, unlike the native video API. */ + presentationTime: number + expectedDisplayTime: number + width: number + height: number + mediaTime: number + presentedFrames: number + processingDuration: number + captureTime: number + receiveTime: number + rtpTimestamp: number +} + +export type SyntheticFrameCallback = (now: number, metadata: SyntheticFrameMetadata) => void +export type MediaListener = (event: Event & { detail: unknown }) => unknown + +/** Opt-in media surface of art.mediabunny; decoder internals are not part of this view. */ +export interface MediaBunnyShim { + canvas: HTMLCanvasElement + /** Runtime also accepts SDK sources; the default Option keeps its historical input union. */ + src: unknown + readonly currentSrc: unknown + currentTime: number + readonly duration: number + /** Synthetic full-duration/current-time ranges, not measured network buffers. */ + readonly buffered: TimeRanges + readonly played: TimeRanges + readonly seekable: TimeRanges + readonly paused: boolean + readonly playing: boolean + readonly ended: boolean + readonly seeking: boolean + readonly readyState: number + readonly networkState: number + readonly error: { code: number, message: string } | null + volume: number + muted: boolean + playbackRate: number + readonly videoWidth: number + readonly videoHeight: number + poster: string + /** The following setters are inert; use Option for autoplay/loop/crossOrigin. */ + autoplay: boolean + loop: boolean + controls: boolean + playsInline: boolean + crossOrigin: string + preload: string + defaultMuted: boolean + defaultPlaybackRate: number + play: () => Promise + pause: () => void + load: () => void + /** Always returns "maybe"; it does not probe codec/browser support. */ + canPlayType: (type: string) => 'maybe' + getM3u8State: () => Promise + switchM3u8Quality: (value: unknown) => Promise + switchM3u8Audio: (value: unknown) => Promise + createTimeRanges: (start: number, end: number) => TimeRanges + requestVideoFrameCallback: (callback: SyntheticFrameCallback) => number + cancelVideoFrameCallback: (id: number) => void + addEventListener: (type: string, listener: MediaListener) => void + removeEventListener: (type: string, listener: MediaListener) => void + getBoundingClientRect: () => DOMRect + setAttribute: (name: string, value: unknown) => void + destroy: () => void +} + +/** Native Canvas methods win collisions, including DOM event and attribute methods. */ +export type MediaBunnyCanvas = HTMLCanvasElement & Omit + +/** The alias is installed by the proxy and removed on player destruction. */ +export type MediaBunnyPlayer = Artplayer & { mediabunny?: MediaBunnyShim } diff --git a/refactor/baselines/mb-entry-checkpoint.json b/refactor/baselines/mb-entry-checkpoint.json new file mode 100644 index 000000000..1089b3fb5 --- /dev/null +++ b/refactor/baselines/mb-entry-checkpoint.json @@ -0,0 +1,1739 @@ +{ + "task": "PKG-MB-08", + "status": "doing", + "milestone": "Entry and optional public media types; decoder capability fallback remains incomplete", + "parentCommit": "8a2b56e829a3fa9af5e440a11cede8d1775ded10", + "sourceSha256LF": { + "packages/artplayer-proxy-mediabunny/src/audio-clock.ts": "6f11da4cfa46023bdab4f1bc3930f631f278ac562662fb0a7f908c110ea5d1a8", + "packages/artplayer-proxy-mediabunny/src/audio-context.ts": "7807a2b5343d6af5af67d23c1429a9715567c3f888fc4b5e9c9327bbb2f30332", + "packages/artplayer-proxy-mediabunny/src/audio-nodes.ts": "223e8241c7b2d8400ea25ac127ecc15dd16a687e984377b18b6891afa2fdef75", + "packages/artplayer-proxy-mediabunny/src/audio-pump.ts": "b85f086f4cae13d04d2e334e4e9fa18a6768f3e4187f6124761e3c439060cf06", + "packages/artplayer-proxy-mediabunny/src/audio-task.ts": "65d831e8455a5df3897315ee5b9ee8849a26347fee411e038860df388c1fa77b", + "packages/artplayer-proxy-mediabunny/src/AudioEngine.ts": "4d58cc30148bb4d9e384ea4716a805b00dd9633e03130ba6aeac8d431dd72c43", + "packages/artplayer-proxy-mediabunny/src/canvas-bridge.ts": "91db7cd1b637299656b374f454d7480f1712be224ae9839e9c9f5e3c69e62f06", + "packages/artplayer-proxy-mediabunny/src/cleanup.ts": "854c012384acad4d77e96928217ee16ac6b0425289a3747b331381b13b03f976", + "packages/artplayer-proxy-mediabunny/src/engine-ports.ts": "c56fad4a8f9578aa37686972d96d925012df8160c62337a53200b23a4fc3b164", + "packages/artplayer-proxy-mediabunny/src/engine-types.ts": "6714070f954f7345f33cd93655facc6aa94fd34fa1be0375361962d54fa6e180", + "packages/artplayer-proxy-mediabunny/src/entry-lifecycle.ts": "e760916318e7cc50b7a853be535dddf4911ec59f207f4706314e9d9e77c74b5d", + "packages/artplayer-proxy-mediabunny/src/EventTarget.ts": "4cea57e59b0a1118744a55b0a87c1df28cb0d69c26c50f9275039fe7540c9720", + "packages/artplayer-proxy-mediabunny/src/hls-selection.ts": "b17af12f8fe9f7054898c0cd9a12edce1fd5b58c8ad70e00bcedf098ead4b3dd", + "packages/artplayer-proxy-mediabunny/src/hls-state.ts": "ff9ffd742f9763349df1f50eac6b6bd488a80d05aaab8ca198f387f0d17d5e25", + "packages/artplayer-proxy-mediabunny/src/index.ts": "0c8f1318cf95152a4e1bcb57e60c97e2f3cb02fe6d9d4ff7dc5666159f87fbc2", + "packages/artplayer-proxy-mediabunny/src/input.ts": "d25b1c4ee4aee358c86fd8c554b8b36bfc23fdbd3c27fa21d2cd7e812c98bf9c", + "packages/artplayer-proxy-mediabunny/src/load-session.ts": "560fbd5935fc787bde5f413fcaa41b8829506179c5328ce3cb51e734bbba8cec", + "packages/artplayer-proxy-mediabunny/src/m3u8-menu.ts": "ded1f2efb5caee66a9af5b2db0207c20b4d6caaf05a2bc97df50c40bf6b389d4", + "packages/artplayer-proxy-mediabunny/src/m3u8-model.ts": "239c9da0a2cba97ef8f681ba312acc8f7ef460c3486a803340cfaf355482ddc0", + "packages/artplayer-proxy-mediabunny/src/m3u8-types.ts": "cb8ef504eb038dc48cb9ac59811962ecbe1469d8435ecf56f4fd0cd12dd0c18c", + "packages/artplayer-proxy-mediabunny/src/m3u8.ts": "b3df6a36730f4c30d61e3dc6e28b5d43201f9d264e86dc3d9f855fadf2c58e82", + "packages/artplayer-proxy-mediabunny/src/media.ts": "e745cd8e750e05d0fcfa4bc588f7eb5a5576f3be20f5e67b65b704f57d539ae9", + "packages/artplayer-proxy-mediabunny/src/MediaBunnyEngine.ts": "f8c6d96d11878712a40571961d734d4baa4e6bb5317dd32b776ea7a4795ca951", + "packages/artplayer-proxy-mediabunny/src/playback.ts": "e2a65782c89627198752ff1fe691d4eea0bef215d883a59f0bdcd3e904a4fb47", + "packages/artplayer-proxy-mediabunny/src/preflight.ts": "d296234312f23b97a1e0a054f1d7dbbc988d5240c5fd5089c36df1677c7b7348", + "packages/artplayer-proxy-mediabunny/src/readiness.ts": "9aa24b5e994006b45bda9eafad602785c3e0e334cef54ff45a4939e386c4aceb", + "packages/artplayer-proxy-mediabunny/src/shim-frames.ts": "f6959cc74c718b5adb4d2e38989f1da94a690e96b7861b2a54b0d233e8470cc0", + "packages/artplayer-proxy-mediabunny/src/shim-values.ts": "a93ee17e87cc7db24f4b02d866af8af206d3007d01def446906fb769c20de17d", + "packages/artplayer-proxy-mediabunny/src/tracks.ts": "6da68530c1fc7105ab17ed742d87d93e84447e822e84386591f9c3e6d0bec733", + "packages/artplayer-proxy-mediabunny/src/video-frames.ts": "c48b93c77d976b03d9cb828478ef3f208e35fbd78a4c6d3d6566d90bdc0fe6f2", + "packages/artplayer-proxy-mediabunny/src/video-poster.ts": "db883faea9c6b6e74535ddfba1b55011b751faf94a342d70bef532a1c96f7a46", + "packages/artplayer-proxy-mediabunny/src/video-renderer.ts": "a1fe324f2b8e4efb0cc40a6021cb85bbcc0568f53352107d63a8b9bbebe5e9b5", + "packages/artplayer-proxy-mediabunny/src/VideoEngine.ts": "1c41d43e663b51319d25dccb08a16c7450703dcdffe15d686b4fa3f0a8c7a7e6", + "packages/artplayer-proxy-mediabunny/src/VideoShim.ts": "9d04455ef9a87577a858da5d55334dab888f3fc0d8b2c913b4999382b8d01fd6", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.legacy.js": "cd2f394e9e85fc7fd8a125952cc7c1e63bea128f0b7097e37a5706400d5161ad", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.mjs": "d7e16f9604ec4721803765c88762a48fbb494af992d109579d6910791d0e46ad", + "packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.mts": "9ec22df4a90d3c791da66b07f0a5596ad68092b529f581135bd6a68d16eefa61", + "packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.ts": "1cdf3c25733c73ab3033e92f2231437fecbfa0c327d52a7270ccdfac335cc8fa", + "packages/artplayer-proxy-mediabunny/types/media.d.ts": "1aa4454b51f7c3c1b3bf4f5657e0cd34249558153775c84eff0868817668e36d", + "packages/artplayer-proxy-mediabunny/ARCHITECTURE.md": "9db9acbb2a29d10b49b1d7203c17dca033b8d85be18a7fd5297d67908ac266e8", + "packages/artplayer-proxy-mediabunny/README.md": "46b6ce5a15915e1ae74848f040498af646af751d8ba3c8a4dee4e90c347af026", + "packages/artplayer-proxy-mediabunny/.npmignore": "145c5fa0341195e21cf13df3423a057282f8ea374e9a1b3065e2280e1ce1c5c1", + "packages/artplayer-proxy-mediabunny/package.json": "9b073ac1d70be64847a7fd56d11877a7492273e03b88758296d5ce639dc151ff", + "packages/artplayer-proxy-mediabunny/tsconfig.json": "9591a5b4741c8e0b611b7166b985f5073b61ed566a4077dfa01ebc20035357ea", + "package.json": "7490311e7d611bb32967fd0940dcbc7680de9758ca499c6e0dec01ea6ec4bc5b", + "scripts/typecheck.mjs": "7d3e1f86de91e6fba55db193d0a59be2612712a55d00d58498051097d611e45f", + "test/mediabunny-entry.test.js": "b60d3715ef395fcfcf241da2a51ae9544bf49b8596ed1a11c4bc8c08770db708", + "test/mediabunny-hls.test.js": "ceba7e328f91de537054c5058ce92fc44d8d7cb534ab97509b8c2714243d8328", + "test/browser/mediabunny-entry.spec.js": "e668d573f2e4e26b3383cb0bad5fa1282aa5e7fcf1a6304cd88c657072e1cb15", + "test/types/mediabunny.ts": "c3204062858f2be13b414d2d14ce09c9e5c9778e7d3a3a0009fe1b9f8d87f454", + "refactor/scripts/mb-package-types.mjs": "2f8a5ca12ada786155621315af39c346db782f08852ab3dd4736a1bf6c002da0", + "refactor/fixtures/consumers/mediabunny-1.0.ts": "f617be83ffa972974ac11d15dadcd9b8b710f656f257d1f7caa2267216a6ca13", + "refactor/fixtures/consumers/mediabunny-published.ts": "d307c513f83393d67e5647cbee4056a3003454cb3f3107688582d8c53d2f018e" + }, + "node": { + "entry": 15, + "total": 241, + "main": 217, + "legacy": 217, + "artifactScope": "213 candidate assertions and four frozen normal controls per artifact", + "sameAssertionsOnPreviousMain": { + "passed": 6, + "failed": 9, + "log": "refactor/.cache/mb08-final-entry-frozen.log" + } + }, + "browser": { + "total": 120, + "outcomes": { + "native-audio-ownership-observed": 16, + "unsupported-capability-control": 28, + "native-canvas-entry": 12, + "native-hls-ui-and-selection-observed": 20, + "native-input-playback-and-seek": 10, + "trackless-rejected-before-decoder-setup": 3, + "native-pending-stream-cancellation": 9, + "native-synthetic-raf": 9, + "native-decoded-video-race": 10, + "native-mp4-playback-observed": 2, + "verified-unsupported-capability-control": 1 + }, + "records": [ + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "playback", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "buffer-pause", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "buffer-rate", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-pause", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-source", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-destroy", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "av-clock", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "no-track", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "playback", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "buffer-pause", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "buffer-rate", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-pause", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-source", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-destroy", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "av-clock", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "no-track", + "outcome": "native-audio-ownership-observed", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "playback", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "buffer-pause", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "buffer-rate", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-pause", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-source", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "resume-destroy", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "av-clock", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "no-track", + "outcome": "unsupported-capability-control", + "scope": "Native AudioContext, BufferSourceNodes and SDK decode. Delayed resume/buffer delivery is controlled. AV samples compare decoded canvas timestamps to the audio clock over short 1x/2x playback; acoustic output, long-run drift and physical devices remain MB-09." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "native-cleanup", + "core": "published", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.0" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "replacement", + "core": "published", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.0" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "native-cleanup", + "core": "candidate", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.1" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "replacement", + "core": "candidate", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.1" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "native-cleanup", + "core": "published", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.0" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "replacement", + "core": "published", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.0" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "native-cleanup", + "core": "candidate", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.1" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "replacement", + "core": "candidate", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.1" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "native-cleanup", + "core": "published", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.0" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "replacement", + "core": "published", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.0" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "native-cleanup", + "core": "candidate", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.1" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "replacement", + "core": "candidate", + "outcome": "native-canvas-entry", + "result": { + "before": { + "identity": true, + "context": true, + "width": 640, + "clickCount": 1, + "source": null, + "attribute": "native-only.mp4", + "volume": 0.35, + "style": "100%", + "maybe": "maybe" + }, + "cleanup": { + "released": [ + true, + true, + true + ], + "destroyed": true, + "styleAfter": "43px", + "alias": true + }, + "coreVersion": "5.4.1" + }, + "scope": "Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "menus", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "topology", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-source", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-destroy", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "latest", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "menus", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "topology", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-source", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-destroy", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "latest", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "menus", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "topology", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-source", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-destroy", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "latest", + "core": "published", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "menus", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "topology", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-source", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-destroy", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "latest", + "core": "candidate", + "outcome": "native-hls-ui-and-selection-observed", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "menus", + "core": "published", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "topology", + "core": "published", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-source", + "core": "published", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-destroy", + "core": "published", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "latest", + "core": "published", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "menus", + "core": "candidate", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "topology", + "core": "candidate", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-source", + "core": "candidate", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "stale-destroy", + "core": "candidate", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "latest", + "core": "candidate", + "outcome": "unsupported-capability-control", + "scope": "Actual old/candidate core, SDK HLS parsing and native decoding; rendered control/settings clicks, topology and controlled state/query delays. Not installed-package or long-run/device acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "webm", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "blob", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "stream", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "audio", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "hls", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "trackless", + "outcome": "trackless-rejected-before-decoder-setup", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "webm", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "blob", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "stream", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "audio", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "hls", + "outcome": "native-input-playback-and-seek", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "trackless", + "outcome": "trackless-rejected-before-decoder-setup", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "webm", + "outcome": "unsupported-capability-control", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "blob", + "outcome": "unsupported-capability-control", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "stream", + "outcome": "unsupported-capability-control", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "audio", + "outcome": "unsupported-capability-control", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "hls", + "outcome": "unsupported-capability-control", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "input": "trackless", + "outcome": "trackless-rejected-before-decoder-setup", + "scope": "Identified proxy with native browser media and controlled ArtPlayer host using actual core utilities/config; frame timestamps sampled against the SDK audio clock, not acoustic/long-run AV-sync acceptance. Cleanup checks settled playback, not pending-operation races. Candidate trackless rejection is checked separately before decoder setup; this is not full release acceptance." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "destroy", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "source", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "ending": "timeout", + "outcome": "native-pending-stream-cancellation", + "scope": "Real browser ReadableStream and actual SDK Input disposal before first media bytes; real timeout; controlled ArtPlayer host; does not assert decoder, late frame or audio-node cleanup." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "callback", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "destroy", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "independent", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "callback", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "destroy", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "independent", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "callback", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "destroy", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "independent", + "outcome": "native-synthetic-raf", + "scope": "Real browser requestAnimationFrame and actual proxy instances; synthetic metadata is preserved, no decoding or video frame accuracy is claimed." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "pause-frame", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-source", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-newer", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "timeupdate-pause", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-pool", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "pause-frame", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-source", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-newer", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "timeupdate-pause", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-pool", + "outcome": "native-decoded-video-race", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "pause-frame", + "outcome": "unsupported-capability-control", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-source", + "outcome": "unsupported-capability-control", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-newer", + "outcome": "unsupported-capability-control", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "timeupdate-pause", + "outcome": "unsupported-capability-control", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "scenario": "seek-pool", + "outcome": "unsupported-capability-control", + "scope": "Actual SDK MP4 decoding and browser clock/RAF; frame delivery or two raw VideoSample deliveries before CanvasSink conversion control interleaving. Source/seek ownership, pause and timeupdate reentry verified; not long-run AV sync or a mock codec." + }, + { + "project": "chromium", + "browser": "153.0.8010.12", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "outcome": "native-mp4-playback-observed", + "scope": "Identified published or candidate proxy with actual core5.4.0; native MP4 pixels/clock or explicitly unsupported Windows WebKit APIs. No HLS or long-run AV-sync acceptance." + }, + { + "project": "firefox", + "browser": "155.0", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "outcome": "native-mp4-playback-observed", + "scope": "Identified published or candidate proxy with actual core5.4.0; native MP4 pixels/clock or explicitly unsupported Windows WebKit APIs. No HLS or long-run AV-sync acceptance." + }, + { + "project": "webkit", + "browser": "26.6", + "platform": "win32", + "implementation": "candidate-artifact", + "sha256": "b7f4ff882a59cdff2b351d0ffcf4948dc9c06317c11dfaf6257f4865bf8c4134", + "outcome": "verified-unsupported-capability-control", + "scope": "Identified published or candidate proxy with actual core5.4.0; native MP4 pixels/clock or explicitly unsupported Windows WebKit APIs. No HLS or long-run AV-sync acceptance." + } + ], + "report": "refactor/.cache/mb08-entry-results/report.json", + "reportSha256": "5eaee5c3d4d2690d8dbfe5f410421db45277b6015eabfdf47761811e12b2519f", + "results": "refactor/.cache/mb08-entry-results/results", + "previousMain": { + "total": 12, + "passed": 0, + "failed": 12, + "report": "refactor/.cache/mb08-entry-frozen-results/report.json", + "reportSha256": "c7430214d46f15cce5e7b237d298aa33b7ec5b62ccf596286ad9d6f2094206e9", + "results": "refactor/.cache/mb08-entry-frozen-results/results" + } + }, + "installedTypes": { + "cases": 17, + "candidateCases": 7, + "invalidUsesPerCandidate": 15, + "historicalNodeNextFailures": 2, + "report": "refactor/.cache/mb-package-types-IyoaJq/report.json", + "reportSha256": "d806d41389d52f60ade7b5d0c6c0b99dd9631a37306f4f5d9214f55ac971dc2a", + "packages": [ + { + "name": "artplayer", + "sha256": "2139af017670a4f30f667bf5fdc1aa680f3e03b9c8d3cb767fc92d6345aedff5" + }, + { + "name": "artplayer-proxy-mediabunny", + "sha256": "563cdc83ea237adb77f73775eb6ea53d9a9bb5af0723b7c5cda45d5934b61d3c" + } + ] + }, + "checks": [ + { + "command": "yarn ci:check", + "result": "pass", + "tests": { + "unit": 1247, + "engineering": 14, + "baseline": 141, + "mainTotal": 1402, + "repeatedContractExecutions": 44 + }, + "strictProductionTypeScriptFiles": 324, + "log": "refactor/.cache/mb08-ci.log" + } + ], + "iterations": [ + "Explicit getter annotations prevent unknown setters widening reads; no runtime coercion change.", + "Workspace probe reproduced legacy resolution and NodeNext ESM default issues; conditional ESM declaration and typesVersions resolved them.", + "First pack rejected tsconfig leakage; .npmignore fixed and final actual installation passed.", + "First native Canvas fixture incorrectly expected final inline width after other core resize listeners; validate the actual owned callback separately. Initial report/results retained; duplicate scenarios consolidated.", + "Final runtime alias is nonenumerable but writable/configurable, preserving replacement behavior; actual old/candidate checks retained.", + "Full CI noUncheckedIndexedAccess caught unchecked first-level access in the consumer fixture; use optional access. Full CI and installed matrix rerun passed; runtime artifacts unchanged." + ], + "limitations": [ + "MB-08 stays doing for unsupported decoder fallback/readiness, including HLS replacement.", + "Twelve new browser cases use native Canvas and actual cores, with empty input; no playback claim.", + "Twenty-nine Windows WebKit capability controls are not successful decoding or general Safari evidence.", + "Long-run AV sync, physical devices and wider combinations remain MB-09.", + "Isolated type installation is not the full MB-10 distribution, source/license notice or demo gate." + ], + "nextCapabilityReproduction": { + "scope": "Actual SDK-parsed video-only MP4 in old and candidate coordinators, controlled canDecode=false and controlled AudioContext; not a native browser codec failure.", + "log": "refactor/.cache/mb08-capability-probe.log", + "sha256": "41f410796c5d9cbe8a29d724fbfe9b82dee9c693e645e1ca860b0cd76c35bfea", + "samples": [ + { + "label": "before", + "tracks": { + "video": true, + "audio": false + }, + "readyState": 4, + "error": null, + "videoSink": null, + "audioSink": null, + "events": [ + "loadedmetadata", + "loadeddata", + "canplay", + "canplaythrough" + ], + "replacement": { + "readyState": 4, + "error": null, + "events": [ + "loadedmetadata", + "loadeddata", + "canplay", + "canplaythrough" + ] + } + }, + { + "label": "candidate", + "tracks": { + "video": true, + "audio": false + }, + "readyState": 4, + "error": null, + "videoSink": null, + "audioSink": null, + "events": [ + "loadedmetadata", + "loadeddata", + "canplay", + "canplaythrough" + ], + "replacement": { + "readyState": 4, + "error": null, + "events": [ + "loadedmetadata", + "loadeddata", + "canplay", + "canplaythrough" + ] + } + } + ] + } +} diff --git a/refactor/baselines/mb-entry-source.json b/refactor/baselines/mb-entry-source.json new file mode 100644 index 000000000..3719b975a --- /dev/null +++ b/refactor/baselines/mb-entry-source.json @@ -0,0 +1,12 @@ +{ + "task": "PKG-MB-08", + "sourceCommit": "8a2b56e829a3fa9af5e440a11cede8d1775ded10", + "sourceSha256LF": { + "packages/artplayer-proxy-mediabunny/src/index.js": "4e1be8937908ff6e6ef8a4e863e22b4468312cf31d66ac299322e475757773bb", + "packages/artplayer-proxy-mediabunny/src/VideoShim.ts": "1fef3028a3937182c31503129655efdb88118ea0f6d3be96e9be99dcbcc5fdc7", + "packages/artplayer-proxy-mediabunny/src/engine-types.ts": "6714070f954f7345f33cd93655facc6aa94fd34fa1be0375361962d54fa6e180", + "packages/artplayer-proxy-mediabunny/types/artplayer-proxy-mediabunny.d.ts": "af2083224d0760752d83eb2ac86b1dea5586455b81d47e4ba70f9f6a874a75d8", + "packages/artplayer-proxy-mediabunny/package.json": "96b09ce19ea7914485aa9780329a0cfc43b18e38232ea1dd92d2e6dc27310055", + "packages/artplayer-proxy-mediabunny/dist/artplayer-proxy-mediabunny.js": "303b1a5d71b661c7d973c52850f5e68766990c86c59fe438f0070bd38edbfb0e" + } +} diff --git a/refactor/changes/2026-09-12-PKG-MB-08-entry-checkpoint.md b/refactor/changes/2026-09-12-PKG-MB-08-entry-checkpoint.md new file mode 100644 index 000000000..90709c0e7 --- /dev/null +++ b/refactor/changes/2026-09-12-PKG-MB-08-entry-checkpoint.md @@ -0,0 +1,66 @@ +# PKG-MB-08 检查点:入口、Canvas 转发与公开声明 + +任务保持doing。本包自有源码已全部迁移为34个strict TS模块,但不可解码轨道的回退与 +就绪能力审查尚未完成;不能据此把整个MB-08标done。进入本轮的源码/产物冻结于 +[入口基线](../baselines/mb-entry-source.json),对应8a2b56e8。 + +## 实现与兼容边界 + +入口从index.js迁至index.ts,Canvas转发、入口生命周期和通用清理分别进入 +canvas-bridge.ts、entry-lifecycle.ts、cleanup.ts。后者从HLS菜单层下移,避免入口依赖 +UI层的通用释放实现。HLS初始化支持部分注册失败时撤销,返回内部destroy供入口回滚。 + +保留createElement脱离receiver调用、原生可枚举方法getter读取两次、Canvas原生方法优先、 +shim own/直接prototype转发、每次读取绑定方法、getter-only写入TypeError等旧行为。 +资源状态不增加Canvas公开字段。销毁取消入口resize/metadata/destroy监听,已保存回调失效; +只删除仍属于当前shim的art.mediabunny,保留调用方替换的别名。一个清理步骤抛错仍尝试其余步骤, +setup失败保留原始异常。缺少off的历史自定义host仍可用,残留回调在销毁后保持无副作用。 + +公开默认工厂继续是可选Option到同步initializer、精确HTMLCanvasElement的签名;不将Result +缩窄成Canvas与shim交叉类型,不增加强制default属性,也不全局增强Artplayer。 +新增type-only Option/Result、MediaBunnyShim、MediaBunnyCanvas、MediaBunnyPlayer、HLS状态和 +SyntheticFrameCallback等。MediaBunnyPlayer的别名可缺省;Canvas视图明确原生DOM方法优先。 +VideoShim实际implements媒体视图,getter显式返回类型防止unknown setter污染读取推导。 + +声明不引入MediaBunny SDK的现代DOM/Disposable依赖;track对象保持unknown,由消费者按 +自用SDK缩窄。SyntheticFrameMetadata保留历史估算语义,尤其presentationTime是媒体秒数。 +canPlayType仍恒为maybe,TimeRanges不代表真实网络缓冲;新类型不制造能力承诺。 + +新增.d.mts及条件types路由修正NodeNext ESM不可调用问题,typesVersions补齐经典解析的legacy。 +CommonJS继续保留旧default声明门面;运行时直接工厂增加不可枚举、可写、可配置的default自身别名, +同时支持1.0.0的namespace.default和1.2.0的直接调用。整工厂双向赋值使用实际两个npm冻结声明检查。 + +## 验证与迭代 + +15条入口断言在旧main上6通过/9失败;候选包专项241通过,main/legacy各217通过,其中 +各213条候选断言和4条冻结正常控制。HLS测试将清理断言限定为其自己拥有的5个listener; +新增入口断言单独检查额外3个listener,不再错误假设resize回调应一直残留。 + +新增12浏览器用例使用真实Canvas与发布版/候选核心,覆盖方法receiver、DOM事件/属性优先、 +清理和替换别名。旧main同12项全部复现缺陷;候选通过。首轮夹具错误地把后续核心尺寸处理后的 +inline style当作入口独占结果,现单独调用已注册入口resize callback验证其行为;首轮18份失败 +report/results保留,并合并了两组重复场景。未增加重试或放宽超时。最终8个MediaBunny浏览器文件 +共120通过:新增12项为Canvas/生命周期检查,原有29项为Windows WebKit能力对照,均不冒充播放。 + +新增yarn test:mediabunny-types-package:实际pack核心与代理,在工作区外安装两个冻结发布包及 +候选,offline/frozen重装、锁文件和安装文件哈希检查。17组编译/导出矩阵通过;候选7组各拒绝 +15条非法用法,并验证原始两份声明的整工厂双向赋值。保留旧版NodeNext ESM的准确诊断作为负例。 +最初pack发现tsconfig泄漏,补入.npmignore后修复。旧TS不读取SDK声明,所有解析文件限于安装 +目录或编译器标准库。该检查并非MB-10完整分发/许可验收。 + +最终源码、打包安装、构建与浏览器证据见[检查点记录](../baselines/mb-entry-checkpoint.json)。 +完整CI1402项(1247单元+14工程+141基线)通过,另44重复契约,324生产TS。 +首轮全局noUncheckedIndexedAccess发现消费者夹具直接读取空数组首项,改为可选访问后 +完整CI和17组实际安装矩阵重跑通过;运行时产物未变化。本轮未添加依赖,Yarn和SDK锁版本不变。 + +## 立即接续 + +继续检查已有track但codec/canDecode不可用时,VideoEngine/AudioEngine的历史空轨道回退。 +必须保留有效audio-only/video-only播放,阻止没有可用解码器时假就绪,并覆盖加载、HLS替换、 +晚能力查询、pause/source/destroy和错误事件顺序。不要仅凭新增接口或现有WebKit负例宣布修复。 +长播放/AV sync/设备及组合由MB-09,示例、安装分发及MPL/source notice由MB-10继续。 +本检查点独立本地提交,回退该提交即可恢复本轮前状态;冻结历史输入保持不变,不推送或发布。 + +接续缺陷已用实际SDK解析的video-only MP4复现:受控canDecode=false与AudioContext下, +旧/候选均为videoSink=null、audioSink=null,却readyState=4并发loadedmetadata/data/canplay/through; +replaceTracks后同样假就绪。该受控复现见检查点记录,不能当作真实浏览器解码结果。 diff --git a/refactor/fixtures/consumers/mediabunny-1.0.ts b/refactor/fixtures/consumers/mediabunny-1.0.ts new file mode 100644 index 000000000..f9a98a15c --- /dev/null +++ b/refactor/fixtures/consumers/mediabunny-1.0.ts @@ -0,0 +1,11 @@ +import Artplayer from 'artplayer' +import factory from 'artplayer-proxy-mediabunny' + +type Option = Parameters[0] +const art = new Artplayer({ container: '#player', url: 'movie.mp4', proxy: factory() }) +const replacement: typeof factory = (_option?: Option) => (_art: Artplayer) => document.createElement('canvas') +const canvas: ReturnType> = document.createElement('canvas') +factory() +factory(undefined) +factory({ volume: 0.7, source: new Blob([]), loadTimeout: 1000 })(art) +void [replacement, canvas] diff --git a/refactor/fixtures/consumers/mediabunny-published.ts b/refactor/fixtures/consumers/mediabunny-published.ts new file mode 100644 index 000000000..1d98dd1b0 --- /dev/null +++ b/refactor/fixtures/consumers/mediabunny-published.ts @@ -0,0 +1,34 @@ +import Artplayer from 'artplayer' +import factory from 'artplayer-proxy-mediabunny' + +const art = new Artplayer({ container: '#player', url: 'movie.mp4', proxy: factory() }) +type Option = NonNullable[0]> +type HistoricalFactory = (option?: Option) => (art: Artplayer) => HTMLCanvasElement +const assignOld: HistoricalFactory = factory +const assignNew: typeof factory = (_option?: Option) => (_art: Artplayer) => document.createElement('canvas') +const initializer: ReturnType = () => document.createElement('canvas') +const canvas: ReturnType> = document.createElement('canvas') +const options: Option = { + source: new ReadableStream(), + loadTimeout: 1000, + timeupdateInterval: 250, + avSyncTolerance: 0.12, + dropLateFrames: false, + poster: 'poster.jpg', + preflightRange: false, + volume: 0.7, + muted: false, + autoplay: false, + loop: false, + crossOrigin: 'anonymous', + m3u8: { + quality: { control: true, setting: true, title: 'Quality', auto: 'Auto', getName: level => `${level.id}/${level.index}/${level.name}/${level.height}/${level.bitrate}` }, + audio: { control: true, setting: true, title: 'Audio', auto: 'Auto', getName: track => `${track.id}/${track.index}/${track.name}/${track.lang}/${track.language}/${track.bitrate}` }, + }, +} +factory() +factory(undefined) +factory(options)(art).getContext('2d') +factory({ source: new Blob([]) }) +factory({ source: 'movie.mp4' }) +void [assignOld, assignNew, initializer, canvas] diff --git a/refactor/mb-validation.md b/refactor/mb-validation.md index 792d35366..259b025c5 100644 --- a/refactor/mb-validation.md +++ b/refactor/mb-validation.md @@ -80,3 +80,14 @@ main/legacy各159通过。最终78浏览器含16新增原生音频场景及8新 11通过/32失败,候选专项226及main/legacy各202通过。最终108浏览器含20新增原生HLS 新旧核心/UI/SDK场景与10新增能力对照。旧main同30项14通过/16失败,未把能力缺失计作播放。 全部报告/results已归档;完整CI1387项及44重复契约通过,320生产TS;完成后立即专用提交,MB-LIFE-01剩余组合/长播范围仍open。 + +## PKG-MB-08 入口与声明检查点(doing) + +index实际迁移,入口/Canvas桥/生命周期/清理拆为四模块,全包34生产TS。 +精确默认Canvas和整工厂保留;可选shim/HLS/RAF视图、ESM声明及旧legacy解析已验证。 +15条新断言旧main6通过/9失败,候选专项241及main/legacy各217通过。新增12真实Canvas/ +新旧核心场景通过,旧main同12项失败;最终8文件120浏览器通过,其中29能力对照不计作播放。 +实际打包安装17类型矩阵通过,候选7组各拒绝15非法用法;旧NodeNext失败保留负例。 +见[变更](changes/2026-09-12-PKG-MB-08-entry-checkpoint.md)和[证据](baselines/mb-entry-checkpoint.json)。 +完整CI1402项及44重复契约通过,324生产TS。受控canDecode=false已复现旧/候选 +video-only输入及替换无sink仍readyState=4;任务保持doing,下一步修复该能力边界。 diff --git a/refactor/plan.md b/refactor/plan.md index 5bd010185..ab9ca191d 100644 --- a/refactor/plan.md +++ b/refactor/plan.md @@ -4,7 +4,7 @@ 基线:`40fcda6a37d0049d42e49c1e64e70d4fd9ba5f7f`。总任务 222 项,范围 22 个包及工作区/示例。 -状态:todo 111 / doing 7 / blocked 0 / done 104 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。 +状态:todo 110 / doing 8 / blocked 0 / done 104 / deferred 0。风险 L/M/H 表示兼容风险,不表示工期。 前置依赖是启动条件;验收是完成条件。任务可以继续拆分,但不能复用或悄悄删除旧 ID。 @@ -336,7 +336,7 @@ | PKG-MB-05 | artplayer-proxy-mediabunny
整理视频解码、seek 和帧释放 | PKG-MB-04 | VideoEngine 调度、队列、晚帧处理和资源释放 | 暂停/seek/切源无旧帧覆盖,默认丢帧策略不变 | H | done | | PKG-MB-06 | artplayer-proxy-mediabunny
整理音频解码、时钟与同步 | PKG-MB-04 | AudioEngine 时钟、缓冲和 AudioContext 归属 | AV sync、倍速、无音轨、静音/音量和暂停恢复通过 | H | done | | PKG-MB-07 | artplayer-proxy-mediabunny
整理 HLS 配对轨道与 selector | PKG-MB-05, PKG-MB-06, CORE-14 | m3u8 配对、质量/音频选择及拓扑清理 | 实际选择高亮、切到无轨道来源清理、无重复 readiness | H | done | -| PKG-MB-08 | artplayer-proxy-mediabunny
完成 TS 与媒体能力声明 | PKG-MB-07, ENG-04, ENG-06 | 8 个自有 JS 模块迁移与 Result/shim 类型 | 解码器/Stream/DOM 类型清楚,旧 Option 和 art.mediabunny 使用保持 | H | todo | +| PKG-MB-08 | artplayer-proxy-mediabunny
完成 TS 与媒体能力声明 | PKG-MB-07, ENG-04, ENG-06 | 8 个自有 JS 模块迁移与 Result/shim 类型 | 解码器/Stream/DOM 类型清楚,旧 Option 和 art.mediabunny 使用保持 | H | doing | | PKG-MB-09 | artplayer-proxy-mediabunny
完成新旧核心和真实媒体组合 | PKG-MB-08, CORE-22 | 跨浏览器能力、长播放、DPiP、HLS 音轨/质量报告 | 资源释放、事件顺序、AV sync 与支持范围满足基线 | H | todo | | PKG-MB-10 | artplayer-proxy-mediabunny
完成分发和文档 | PKG-MB-09, ENG-07 | mediabunny.js、README、依赖版本、三产物和许可 | tarball 可消费、无意外依赖升级、旧调用与回退可用 | H | todo | @@ -527,4 +527,5 @@ - PKG-MB-05: [记录](baselines/mb-video-source.json) [记录](changes/2026-09-12-PKG-MB-05-video.md) [记录](baselines/mb-video-validation.json) - PKG-MB-06: [记录](baselines/mb-audio-source.json) [记录](changes/2026-09-12-PKG-MB-06-audio.md) [记录](baselines/mb-audio-validation.json) - PKG-MB-07: [记录](baselines/mb-hls-source.json) [记录](changes/2026-09-12-PKG-MB-07-hls.md) [记录](baselines/mb-hls-validation.json) +- PKG-MB-08: [记录](baselines/mb-entry-source.json) [记录](changes/2026-09-12-PKG-MB-08-entry-checkpoint.md) [记录](baselines/mb-entry-checkpoint.json) - PKG-FACTORY-01: [记录](baselines/factory-assignment-gaps.json) [记录](baselines/factory-compatibility-proposals.json) [记录](factory-compatibility-decision.md) [记录](changes/2026-09-12-PKG-FACTORY-01-decision.md) diff --git a/refactor/progress.md b/refactor/progress.md index 2bb64dacd..4d682511b 100644 --- a/refactor/progress.md +++ b/refactor/progress.md @@ -1,5 +1,18 @@ # 进度与证据 +## PKG-MB-08检查点:入口TS与兼容媒体声明(doing) + +全包34个自有生产模块已转TS,入口/Canvas桥/生命周期/清理分离。默认工厂仍可选Option、 +同步初始化与精确Canvas结果;新增可选媒体/HLS/RAF类型,修复旧legacy及NodeNext ESM解析。 +15条入口断言旧main6通过/9失败,候选专项241及main/legacy各217通过。最终120浏览器 +全部通过,含12原生Canvas/新旧核心场景及29能力对照;旧main相同12入口场景全部失败。 +实际安装17组类型/导出矩阵通过,候选7组各拒绝15非法用法;整工厂按冻结声明双向赋值。 +完整CI1402项及44重复契约通过,324生产TS。源码/产物/浏览器/安装包哈希已核验。 +见[变更](changes/2026-09-12-PKG-MB-08-entry-checkpoint.md)与[证据](baselines/mb-entry-checkpoint.json)。 +222项:104 done、8 doing、110 todo。本地检查点提交,不计任务完成。 +下一步:修复受控canDecode=false时video-only输入及替换无可用sink却发布就绪; +该问题旧/候选均已复现。MB-08、能力风险及后续分发/许可/设备门槛仍未关闭。 + ## PKG-MB-07完成:HLS配对、选择意图与UI拓扑 m3u8实际迁移为四个TS模块,包内30生产TS,仅剩index.js待MB-08。 diff --git a/refactor/risks.json b/refactor/risks.json index 1712e3aea..1797d9c4c 100644 --- a/refactor/risks.json +++ b/refactor/risks.json @@ -3679,13 +3679,15 @@ "PKG-MB-08", "PKG-MB-10" ], - "compatibleResolution": "Preserve optional whole-factory and exact Canvas assignment, model explicit shim capabilities separately and verify historical default namespace and callable consumers.", + "compatibleResolution": "Preserve optional whole-factory and exact Canvas assignment, model explicit shim capabilities separately and verify historical default namespace and callable consumers. MB-08 entry checkpoint preserves exact optional factory/Canvas assignment, adds opt-in checked media types without SDK imports, and fixes classic legacy/NodeNext ESM resolution. Seventeen installed compiler cases plus runtime exports passed against two frozen releases and candidate; seven candidate cases reject fifteen invalid uses each. Type facade/runtime export part is verified; final MB-08 capability and MB-10 distribution gates remain open.", "closureCriteria": "Actual installed old/candidate compiler and runtime export matrices pass with negative controls; any incompatible declaration generation requires an explicit decision.", "status": "open", "evidence": [ "refactor/baselines/mb-release.json", "refactor/baselines/mb-contract.md", - "refactor/changes/2026-09-12-PKG-MB-01-contract.md" + "refactor/changes/2026-09-12-PKG-MB-01-contract.md", + "refactor/changes/2026-09-12-PKG-MB-08-entry-checkpoint.md", + "refactor/baselines/mb-entry-checkpoint.json" ] }, { @@ -3715,13 +3717,14 @@ "PKG-MB-04", "PKG-MB-09" ], - "compatibleResolution": "Use explicit coordinated readiness and failure state, preserving valid event order while preventing duplicate or stale callbacks; evaluate trackless behavior separately from normal media. MB-04 coordinates metadata once, suppresses stale readiness and rejects trackless input before decoder setup. Existing-track unsupported-codec behavior and full native combinations remain MB-05/06/09; risk stays open.", + "compatibleResolution": "Use explicit coordinated readiness and failure state, preserving valid event order while preventing duplicate or stale callbacks; evaluate trackless behavior separately from normal media. MB-04 coordinates metadata once, suppresses stale readiness and rejects trackless input before decoder setup. Existing-track unsupported-codec behavior and full native combinations remain MB-05/06/09; risk stays open. MB-08 entry checkpoint reproduces remaining false readiness in both previous and candidate builds: actual SDK-parsed video-only MP4 with controlled canDecode=false and AudioContext yields null audio/video sinks but readyState 4 and all readiness events, including replaceTracks. Keep open for the next MB-08 capability implementation; this controlled case is not native decoding evidence.", "closureCriteria": "Candidate metadata/data/canplay ordering and counts pass normal, absent-track and failure interleavings in native browsers and controlled race tests.", "evidence": [ "refactor/changes/2026-09-12-PKG-MB-02-baseline.md", "refactor/baselines/mb-behavior-validation.json", "refactor/changes/2026-09-12-PKG-MB-04-coordination.md", - "refactor/baselines/mb-coordination-validation.json" + "refactor/baselines/mb-coordination-validation.json", + "refactor/baselines/mb-entry-checkpoint.json" ] } ] diff --git a/refactor/scripts/mb-package-types.mjs b/refactor/scripts/mb-package-types.mjs new file mode 100644 index 000000000..c4452e220 --- /dev/null +++ b/refactor/scripts/mb-package-types.mjs @@ -0,0 +1,138 @@ +import assert from 'node:assert/strict' +import fs from 'node:fs' +import path from 'node:path' +import process from 'node:process' +import ts from 'typescript' +import compat from 'typescript-compat' +import { checkFiles, packedFiles } from '../../scripts/package-check.mjs' +import { consumerDirectory, removeConsumer, run, workspace, writeJson } from '../../scripts/package-consumer.mjs' +import { verifyMbContract } from './mb-contract.mjs' +import { hash, readMember } from './releases.mjs' + +async function main() { + assert.equal(process.env.npm_config_user_agent?.split(' ')[0], 'yarn/1.22.22', 'Use yarn test:mediabunny-types-package') + const yarn = process.env.npm_execpath + assert(yarn && fs.existsSync(yarn)) + const output = fs.mkdtempSync(path.join(workspace, 'refactor/.cache/mb-package-types-')) + console.log(`MediaBunny isolated package evidence: ${output}`) + const contract = await verifyMbContract() + const packages = [] + for (const name of ['artplayer', 'artplayer-proxy-mediabunny']) { + const archive = path.join(output, `${name}.tgz`) + fs.writeFileSync(path.join(output, `${name}-pack.log`), run([yarn, 'pack', '--filename', archive], path.join(workspace, 'packages', name))) + const manifest = JSON.parse(readMember(archive, 'package/package.json')) + const files = packedFiles(archive) + checkFiles(manifest, files, name === contract.baseline.release.name ? Object.keys(contract.baseline.release.files) : []) + packages.push({ name, archive, sha256: hash(fs.readFileSync(archive)), files: Object.fromEntries(files.map(member => [member, hash(readMember(archive, member))])) }) + } + const matrix = [] + const core = packages[0] + const candidates = [ + ...contract.baseline.previous.concat(contract.baseline.release).map(release => ({ ...release, archive: contract.archives.get(release.version), label: `published-${release.version}` })), + { ...packages[1], label: 'candidate' }, + ] + for (const plugin of candidates) { + const consumer = consumerDirectory() + try { + writeJson(path.join(consumer, 'package.json'), { name: 'mediabunny-isolated-consumer', private: true, dependencies: Object.fromEntries([core, plugin].map(pkg => [pkg.name, `file:${pkg.archive.replaceAll('\\', '/')}`])) }) + fs.copyFileSync(path.join(workspace, 'yarn.lock'), path.join(consumer, 'yarn.lock')) + fs.writeFileSync(path.join(output, `${plugin.label}-install.log`), run([yarn, 'install', '--offline', '--ignore-scripts', '--non-interactive'], consumer)) + const lock = fs.readFileSync(path.join(consumer, 'yarn.lock')) + fs.writeFileSync(path.join(output, `${plugin.label}-frozen-install.log`), run([yarn, 'install', '--offline', '--frozen-lockfile', '--ignore-scripts', '--non-interactive'], consumer)) + assert.deepEqual(fs.readFileSync(path.join(consumer, 'yarn.lock')), lock) + fs.writeFileSync(path.join(output, `${plugin.label}-yarn.lock`), lock) + for (const pkg of [core, plugin]) { + const root = path.join(consumer, 'node_modules', pkg.name) + assert.equal(fs.realpathSync(root), root, 'Installed package must not be a workspace link') + for (const [member, expected] of Object.entries(pkg.files)) + assert.equal(hash(fs.readFileSync(path.join(root, member.slice(8)))), expected, `Installed bytes differ: ${member}`) + } + const runtimeFile = path.join(consumer, 'exports.cjs') + fs.writeFileSync(runtimeFile, `const assert = require('node:assert/strict'); +for (const name of ['artplayer-proxy-mediabunny', 'artplayer-proxy-mediabunny/legacy']) { + const value = require(name); + assert.equal(typeof value, '${plugin.version === '1.0.0' ? 'object' : 'function'}'); + assert.equal(typeof (value.default || value)(), 'function'); + ${plugin.label === 'candidate' ? 'assert.equal(value.default, value); assert.equal(typeof value.default(), "function"); assert.deepEqual(Object.keys(value), []);' : plugin.version === '1.2.0' ? 'assert.equal(value.default, undefined);' : 'assert.equal(typeof value.default, "function");'} +} +Promise.all(['artplayer-proxy-mediabunny', 'artplayer-proxy-mediabunny/legacy'].map(async name => { + const module = await import(name); + const value = module.default; + assert.equal(typeof (value.default || value)(), 'function'); + if (name === 'artplayer-proxy-mediabunny') assert.deepEqual(Object.keys(module), ['default']); +})).catch(error => { console.error(error); process.exitCode = 1; });`) + fs.writeFileSync(path.join(output, `${plugin.label}-runtime.log`), run([runtimeFile], consumer)) + const modes = [[ts, 'node10-commonjs'], [ts, 'nodenext-cjs'], [ts, 'nodenext-esm'], [ts, 'bundler-esm'], [compat, 'node10-commonjs']] + if (plugin.label === 'candidate') + modes.push([ts, 'node10-commonjs-no-interop'], [compat, 'node10-commonjs-no-interop']) + for (const [compiler, mode] of modes) { + const next = mode.startsWith('nodenext') + const extension = next ? mode.endsWith('-cjs') ? 'cts' : 'mts' : 'ts' + const fixture = plugin.label === 'candidate' ? 'test/types/mediabunny.ts' : plugin.version === '1.0.0' ? 'refactor/fixtures/consumers/mediabunny-1.0.ts' : 'refactor/fixtures/consumers/mediabunny-published.ts' + const source = fs.readFileSync(path.join(workspace, fixture), 'utf8') + const filename = path.join(consumer, `consumer.${extension}`) + const files = [filename] + if (plugin.label === 'candidate') { + for (const generation of ['1.0', 'published']) { + const historical = path.join(consumer, `historical-${generation}.${extension}`) + fs.copyFileSync(path.join(workspace, `refactor/fixtures/consumers/mediabunny-${generation}.ts`), historical) + files.push(historical) + } + // Compare complete factories against the actual frozen declaration bytes. + for (const release of contract.baseline.previous.concat(contract.baseline.release)) { + const name = `frozen-${release.version}` + fs.writeFileSync(path.join(consumer, `${name}.d.ts`), readMember(contract.archives.get(release.version), `package/${release.manifest.types.replace(/^\.\//, '')}`)) + const assignment = path.join(consumer, `${name}-assignment.cts`) + fs.writeFileSync(assignment, `import current from 'artplayer-proxy-mediabunny'; import frozen from './${name}'; const forward: typeof frozen = current; const backward: typeof current = frozen; void [forward, backward];`) + // TS 4.3 predates .cts. Use an ordinary .ts for classic resolution. + const actual = next ? assignment : assignment.replace(/\.cts$/, '.ts') + if (actual !== assignment) + fs.renameSync(assignment, actual) + files.push(actual) + } + if (mode === 'nodenext-cjs') { + const commonjs = path.join(consumer, 'commonjs.cts') + fs.writeFileSync(commonjs, `import factory = require('artplayer-proxy-mediabunny'); import legacy = require('artplayer-proxy-mediabunny/legacy'); factory.default(); legacy.default({ volume: 0.5 });`) + files.push(commonjs) + } + } + const options = { strict: true, noEmit: true, skipLibCheck: false, types: [], esModuleInterop: !mode.endsWith('-no-interop'), target: compiler.ScriptTarget.ES2020, lib: ['lib.es2020.d.ts', 'lib.dom.d.ts'], module: next ? compiler.ModuleKind.NodeNext : mode === 'bundler-esm' ? compiler.ModuleKind.ESNext : compiler.ModuleKind.CommonJS, moduleResolution: next ? compiler.ModuleResolutionKind.NodeNext : mode === 'bundler-esm' ? compiler.ModuleResolutionKind.Bundler : compiler.ModuleResolutionKind.NodeJs } + function compile(code) { + fs.writeFileSync(filename, code) + const program = compiler.createProgram(files, options) + for (const file of program.getSourceFiles()) { + const actual = fs.realpathSync(file.fileName) + assert(actual.startsWith(fs.realpathSync(consumer) + path.sep) || (program.isSourceFileDefaultLibrary(file) && path.dirname(actual) === fs.realpathSync(path.dirname(compiler.sys.getExecutingFilePath()))), `Types escaped installed consumer: ${actual}`) + assert(!/[\\/]node_modules[\\/]mediabunny[\\/]/.test(actual), 'Public declarations must not pull modern SDK types into older compilers') + } + return compiler.getPreEmitDiagnostics(program).map(item => ({ code: item.code, message: compiler.flattenDiagnosticMessageText(item.messageText, '\n') })) + } + const diagnostics = compile(source) + const historicalFailure = plugin.label !== 'candidate' && mode === 'nodenext-esm' + writeJson(path.join(output, `${plugin.label}-${compiler.version}-${mode}-diagnostics.json`), { diagnostics, historicalFailure }) + if (historicalFailure) { + assert.deepEqual(diagnostics.map(item => item.code), plugin.version === '1.0.0' + ? [2344, 2349, 2322, 2344, 2349, 2349, 2349] + : [2349, 2344, 2322, 2322, 2344, 2344, 2322, 7006, 7006, 2349, 2349, 2349, 2349, 2349], 'Unexpected historical NodeNext failure') + } + else { + assert.deepEqual(diagnostics, [], `${plugin.label} ${compiler.version} ${mode}`) + } + const invalid = plugin.label === 'candidate' ? compile(source.replaceAll(/\/\/ @ts-expect-error[^\n]*\n/g, '')) : [] + if (plugin.label === 'candidate') + assert.equal(invalid.length, 15, 'Installed declarations must reject all invalid uses') + matrix.push({ plugin: plugin.label, compiler: compiler.version, mode, historicalFailure, diagnostics, invalid }) + } + } + finally { + removeConsumer(consumer) + } + } + writeJson(path.join(output, 'report.json'), { suite: 'mediabunny-isolated-package-types', introducedBy: 'PKG-MB-08', scope: 'Two frozen published packages and packed candidate with packed candidate core, installed outside workspace; offline/frozen reinstall, exact bytes, default/legacy CJS/ESM runtime and compiler matrices. Exact optional whole-factory assignments checked against actual historical declaration bytes. New shim types are opt-in, without SDK declaration leakage. Historical NodeNext ESM failures remain explicit negative controls. Not native decoding, old-core runtime combinations or full distribution/license acceptance.', packages, published: candidates.slice(0, 2).map(pkg => ({ label: pkg.label, archive: pkg.archive, sha256: hash(fs.readFileSync(pkg.archive)) })), matrix }) + console.log(`MediaBunny installed types passed: ${matrix.length} cases; ${output}`) +} + +main().catch((error) => { + console.error(error) + process.exitCode = 1 +}) diff --git a/refactor/tasks.json b/refactor/tasks.json index bafa52c63..755979633 100644 --- a/refactor/tasks.json +++ b/refactor/tasks.json @@ -3546,11 +3546,15 @@ "ENG-04", "ENG-06" ], - "status": "todo", + "status": "doing", "risk": "H", "deliverable": "8 个自有 JS 模块迁移与 Result/shim 类型", "acceptance": "解码器/Stream/DOM 类型清楚,旧 Option 和 art.mediabunny 使用保持", - "evidence": [] + "evidence": [ + "baselines/mb-entry-source.json", + "changes/2026-09-12-PKG-MB-08-entry-checkpoint.md", + "baselines/mb-entry-checkpoint.json" + ] }, { "id": "PKG-MB-09", diff --git a/scripts/typecheck.mjs b/scripts/typecheck.mjs index 7275ab82f..3767c6c25 100644 --- a/scripts/typecheck.mjs +++ b/scripts/typecheck.mjs @@ -76,7 +76,7 @@ export function runTypechecks() { for (const fixture of ['test/types/public.ts', 'test/types/declaration-inputs.ts', 'test/types/declaration-legacy.ts', 'test/types/plugins-public.ts', 'test/types/playback-public.ts', 'test/types/chapter-options.ts', 'test/types/chapter-exports.ts', 'test/types/hls-control.ts', 'test/types/dash-control.ts', 'test/types/ads.ts', 'refactor/fixtures/consumers/ads-published.ts', 'refactor/fixtures/consumers/ads-workspace.ts', 'refactor/fixtures/consumers/dash-control-legacy.ts', 'test/types/audio-track.ts', 'test/types/language-value.ts', 'refactor/fixtures/consumers/language.ts', 'refactor/fixtures/consumers/legacy-plugin.ts']) { assert.deepEqual(checkConsumer(compiler, mode, fs.readFileSync(path.join(root, fixture), 'utf8')), [], `Consumer failed: TS ${compiler.version} ${mode} ${fixture}`) } - for (const fixture of ['test/types/ambilight.ts', 'refactor/fixtures/consumers/ambilight-published.ts', 'test/types/canvas.ts', 'refactor/fixtures/consumers/canvas-published.ts', 'test/types/dpip.ts', 'refactor/fixtures/consumers/dpip-published.ts']) + for (const fixture of ['test/types/ambilight.ts', 'refactor/fixtures/consumers/ambilight-published.ts', 'test/types/canvas.ts', 'refactor/fixtures/consumers/canvas-published.ts', 'test/types/mediabunny.ts', 'refactor/fixtures/consumers/mediabunny-1.0.ts', 'refactor/fixtures/consumers/mediabunny-published.ts', 'test/types/dpip.ts', 'refactor/fixtures/consumers/dpip-published.ts']) assert.deepEqual(checkConsumer(compiler, mode, fs.readFileSync(path.join(root, fixture), 'utf8')), [], `Consumer failed: TS ${compiler.version} ${mode} ${fixture}`) if (mode === 'nodenext-cjs') assert.deepEqual(checkConsumer(compiler, mode, fs.readFileSync(path.join(root, 'test/types/commonjs.cts'), 'utf8')), [], 'CommonJS export assignment consumer failed') diff --git a/test/browser/mediabunny-entry.spec.js b/test/browser/mediabunny-entry.spec.js new file mode 100644 index 000000000..1bab0ca7b --- /dev/null +++ b/test/browser/mediabunny-entry.spec.js @@ -0,0 +1,72 @@ +import { hash } from '../../refactor/scripts/releases.mjs' +import { mbCandidate } from '../helpers/mediabunny.js' +import { expect, test } from './fixtures.js' + +const implementation = await mbCandidate() +for (const core of ['published', 'candidate']) { + for (const scenario of ['native-cleanup', 'replacement']) { + test(`MediaBunny ${implementation.name}: ${core} core native Canvas entry ${scenario}`, async ({ page }, testInfo) => { + await page.goto(`/test/player.html?core=${core}`) + await page.addScriptTag({ content: `(() => { const module = { exports: {} }; const exports = module.exports; + ${implementation.code}; window.mbFactory = module.exports.default || module.exports; })();` }) + const result = await page.evaluate((scenario) => { + const registered = [] + const removed = [] + const art = new window.Artplayer({ + container: '.player', + url: '', + proxy(player) { + const on = player.on + const off = player.off + player.on = function (name, callback) { + registered.push({ name, callback }) + return on.call(this, name, callback) + } + player.off = function (name, callback) { + removed.push({ name, callback }) + return off.call(this, name, callback) + } + return window.mbFactory()(player) + }, + }) + const canvas = art.video + const shim = art.mediabunny + const resize = registered.find(item => item.name === 'resize') + const metadata = registered.find(item => item.name === 'video:loadedmetadata') + const destroy = registered.find(item => item.name === 'destroy') + const receiver = canvas.getContext + const bounds = canvas.getBoundingClientRect + const attributes = canvas.setAttribute + const identity = canvas instanceof HTMLCanvasElement && shim.canvas === canvas + const context = receiver('2d')?.canvas === canvas + const width = bounds().width + let clickCount = 0 + canvas.addEventListener('click', () => clickCount++) + canvas.dispatchEvent(new MouseEvent('click')) + attributes('src', 'native-only.mp4') + canvas.volume = 0.35 + art.emit('resize') + // Core sizing listeners may reset inline styles after proxy resize; isolate its callback. + resize.callback() + const before = { identity, context, width, clickCount, source: shim.src, attribute: canvas.getAttribute('src'), volume: shim.volume, style: canvas.style.width, maybe: canvas.canPlayType('video/unknown') } + const marker = { owner: 'replacement' } + if (scenario === 'replacement') + art.mediabunny = marker + art.destroy(false) + canvas.style.width = '43px' + resize.callback() + metadata.callback() + const cleanup = { + released: [resize, metadata, destroy].map(item => removed.some(entry => entry.name === item.name && entry.callback === item.callback)), + destroyed: shim.engine.destroyed, + styleAfter: canvas.style.width, + alias: scenario === 'replacement' ? art.mediabunny === marker : !Object.hasOwn(art, 'mediabunny'), + } + return { before, cleanup, coreVersion: window.Artplayer.version } + }, scenario) + expect(result.before).toEqual({ identity: true, context: true, width: 640, clickCount: 1, source: null, attribute: 'native-only.mp4', volume: 0.35, style: '100%', maybe: 'maybe' }) + expect(result.cleanup).toEqual({ released: [true, true, true], destroyed: true, styleAfter: '43px', alias: true }) + await testInfo.attach('mediabunny-entry', { contentType: 'application/json', body: JSON.stringify({ implementation: implementation.name, sha256: hash(implementation.code), core, scenario, result, scope: 'Actual browser Canvas descriptors and published/candidate core lifecycle. Empty source deliberately excludes decoding; existing media suites cover playback separately.' }) }) + }) + } +} diff --git a/test/mediabunny-entry.test.js b/test/mediabunny-entry.test.js new file mode 100644 index 000000000..4ee35c766 --- /dev/null +++ b/test/mediabunny-entry.test.js @@ -0,0 +1,229 @@ +import assert from 'node:assert/strict' +// eslint-disable-next-line test/no-import-node-test -- Actual entry bridge and lifecycle with controlled native-like Canvas descriptors. +import test from 'node:test' +import { mbCandidate, mbEnvironment } from './helpers/mediabunny.js' + +const implementation = await mbCandidate() +function environment() { + const env = mbEnvironment(implementation) + env.art.off = (name, callback) => { + env.handlers.set(name, (env.handlers.get(name) || []).filter(item => item !== callback)) + } + return env +} + +test('MediaBunny entry keeps a callable factory and a writable historical default alias', () => { + const env = environment() + assert.equal(typeof env.exported, 'function') + assert.equal(env.exported.default, env.exported) + assert.equal(typeof env.exported.default(), 'function') + assert.deepEqual(Object.keys(env.exported), []) + const replacement = () => {} + env.exported.default = replacement + assert.equal(env.exported.default, replacement) + assert.equal(typeof env.exported(), 'function') +}) + +test('MediaBunny entry preserves canvas identity, native receiver and shim binding', async () => { + const env = environment() + const canvas = env.factory()(env.art) + assert.equal(canvas, env.canvas) + assert.equal(canvas.canvas, canvas) + assert.equal(canvas.art, env.art) + assert.equal(env.art.mediabunny.engine, canvas.engine) + assert.notEqual(canvas.play, canvas.play) + const pause = canvas.pause + assert.equal(pause(), undefined) + canvas.getContext('2d') + assert.equal(env.nativeCalls.at(-1)[2], true) + const pending = Promise.resolve() + canvas.engine.play = () => pending + assert.equal(canvas.play(), pending) + env.art.emit('destroy') +}) + +test('MediaBunny entry preserves enumerable forwarding and readonly setter failure', () => { + const env = environment() + const canvas = env.factory()(env.art) + const descriptor = Object.getOwnPropertyDescriptor(canvas, 'duration') + assert.equal(descriptor.enumerable, true) + assert.equal(descriptor.configurable, true) + assert.equal(typeof descriptor.get, 'function') + assert.equal(typeof descriptor.set, 'function') + assert.throws(() => { + canvas.duration = 4 + }, { name: 'TypeError' }) + env.art.emit('destroy') +}) + +test('MediaBunny entry preserves native collisions and direct-prototype forwarding boundary', () => { + const env = environment() + env.canvas.currentTime = 13 + const native = env.canvas.setAttribute + const canvas = env.factory()(env.art) + assert.equal(canvas.currentTime, 13) + assert.notEqual(canvas.setAttribute, native) + canvas.setAttribute('src', 'native-only.mp4') + assert.equal(env.art.mediabunny.src, null) + assert.equal(Object.hasOwn(canvas, 'toString'), false) + assert.equal(Object.hasOwn(canvas, 'constructor'), false) + env.art.emit('destroy') +}) + +test('MediaBunny resize preserves default styling and autoSize behavior', () => { + const env = environment() + const canvas = env.factory()(env.art) + assert.deepEqual(canvas.style, {}) + env.art.emit('resize') + assert.deepEqual(canvas.style, { width: '100%', height: '100%', objectFit: 'contain' }) + canvas.style.width = '42px' + env.art.option.autoSize = true + env.art.emit('video:loadedmetadata') + assert.equal(canvas.style.width, '42px') + env.art.emit('destroy') +}) + +test('MediaBunny entry destruction unregisters its resize and metadata callbacks', () => { + const env = environment() + const canvas = env.factory()(env.art) + env.art.emit('destroy') + assert.equal(env.handlers.get('resize')?.length || 0, 0) + assert.equal(env.handlers.get('video:loadedmetadata')?.length || 0, 0) + assert.equal(env.handlers.get('destroy')?.length || 0, 0) + assert.equal(canvas.engine.destroyed, true) +}) + +test('MediaBunny saved resize callback cannot write after destruction', () => { + const env = environment() + const canvas = env.factory()(env.art) + const callback = env.handlers.get('resize')[0] + env.art.emit('destroy') + canvas.style.width = '42px' + callback() + assert.equal(canvas.style.width, '42px') +}) + +test('MediaBunny destruction preserves a replacement art.mediabunny alias', () => { + const env = environment() + const canvas = env.factory()(env.art) + const replacement = {} + env.art.mediabunny = replacement + env.art.emit('destroy') + assert.equal(env.art.mediabunny, replacement) + assert.equal(canvas.engine.destroyed, true) +}) + +test('MediaBunny entry attempts listener cleanup even when engine destroy throws', () => { + const env = environment() + const canvas = env.factory()(env.art) + const failure = new Error('engine cleanup failed') + canvas.engine.destroy = () => { + throw failure + } + assert.throws(() => env.art.emit('destroy'), error => error === failure) + assert.equal(env.art.mediabunny, undefined) + assert.equal(env.handlers.get('resize')?.length || 0, 0) + assert.equal(env.handlers.get('destroy')?.length || 0, 0) + assert.doesNotThrow(() => env.art.emit('destroy')) +}) + +test('MediaBunny entry attempts all cleanup after one listener removal fails', () => { + const env = environment() + const canvas = env.factory()(env.art) + const off = env.art.off + const removed = [] + const failure = new Error('off failed') + env.art.off = (name, callback) => { + removed.push(name) + off(name, callback) + if (name === 'resize') + throw failure + } + assert.throws(() => env.art.emit('destroy'), error => error === failure) + assert.deepEqual(removed, ['resize', 'video:loadedmetadata', 'destroy']) + assert.equal(canvas.engine.destroyed, true) + assert.equal(env.art.mediabunny, undefined) +}) + +test('MediaBunny entry keeps legacy host adapters without off usable and callbacks inert after destroy', () => { + const env = environment() + delete env.art.off + const canvas = env.factory()(env.art) + env.art.emit('destroy') + canvas.style.width = '42px' + env.art.emit('resize') + assert.equal(canvas.style.width, '42px') +}) + +test('MediaBunny bridge setup failure releases the assigned shim and preserves the original failure', () => { + const env = environment() + Object.preventExtensions(env.canvas) + let captured + Object.defineProperty(env.art, 'mediabunny', { + configurable: true, + get() { return captured }, + set(value) { captured = value }, + }) + assert.throws(() => env.factory()(env.art), { name: 'TypeError' }) + assert.equal(captured.engine.destroyed, true) + assert.equal(env.art.mediabunny, undefined) + assert.equal(env.handlers.get('resize')?.length || 0, 0) +}) + +test('MediaBunny entry calls createElement with the historical detached receiver', () => { + const env = environment() + let receiver = 'unset' + env.art.constructor.utils.createElement = function () { + receiver = this + return env.canvas + } + env.factory()(env.art) + assert.equal(receiver, undefined) + env.art.emit('destroy') +}) + +test('MediaBunny bridge preserves the two native method getter reads and bound invocation', () => { + const env = environment() + let reads = 0 + const receivers = [] + Object.defineProperty(env.canvas, 'probe', { + enumerable: true, + configurable: true, + get() { + reads++ + return function () { + receivers.push(this) + } + }, + set(value) { + Object.defineProperty(env.canvas, 'probe', { value, configurable: true }) + }, + }) + env.factory()(env.art) + assert.equal(reads, 2) + const probe = env.canvas.probe + probe() + assert.equal(receivers[0], env.canvas) + env.art.emit('destroy') +}) + +test('MediaBunny partial HLS registration failure cleans the entry, shim and installed callbacks', () => { + const env = environment() + const failure = new Error('registration failed') + const on = env.art.on + env.art.on = (name, callback) => { + on(name, callback) + if (name === 'restart') + throw failure + } + let shim + Object.defineProperty(env.art, 'mediabunny', { + configurable: true, + get() { return shim }, + set(value) { shim = value }, + }) + assert.throws(() => env.factory({ m3u8: {} })(env.art), error => error === failure) + assert.equal(shim.engine.destroyed, true) + assert.equal(env.art.mediabunny, undefined) + assert.equal([...env.handlers.values()].flat().length, 0) +}) diff --git a/test/mediabunny-hls.test.js b/test/mediabunny-hls.test.js index 29e2ae95b..d04efe2cd 100644 --- a/test/mediabunny-hls.test.js +++ b/test/mediabunny-hls.test.js @@ -257,11 +257,11 @@ test('MediaBunny HLS control update reentry cannot write later settings or audio test('MediaBunny HLS destruction removes its refresh listeners and preserves proxy teardown', async () => { const env = environment() await env.refresh() - const metadataBefore = env.handlers.get('video:loadedmetadata').length + const metadataListener = env.handlers.get('video:loadedmetadata').at(-1) env.art.emit('destroy') assert.equal(env.canvas.engine.destroyed, true) assert.equal(env.art.mediabunny, undefined) - assert.equal(env.handlers.get('video:loadedmetadata').length, metadataBefore - 1) + assert.equal(env.handlers.get('video:loadedmetadata').includes(metadataListener), false) assert.equal(env.handlers.get('restart')?.length || 0, 0) }) @@ -402,7 +402,7 @@ test('MediaBunny HLS failing listener removal still attempts remaining removals throw new Error('off failed') } env.art.emit('destroy') - assert.equal(removed.length, 5) + assert.deepEqual(removed.slice(0, 5), ['video:loadedmetadata', 'restart', 'video:loadstart', 'video:error', 'destroy']) assert.equal(env.canvas.engine.destroyed, true) assert.equal(env.warnings.length, 1) }) diff --git a/test/types/mediabunny.ts b/test/types/mediabunny.ts new file mode 100644 index 000000000..7ef281def --- /dev/null +++ b/test/types/mediabunny.ts @@ -0,0 +1,82 @@ +import type { HlsState, MediaBunnyCanvas, MediaBunnyPlayer, MediaBunnyShim, Option, Result, SyntheticFrameCallback } from 'artplayer-proxy-mediabunny' +import Artplayer from 'artplayer' +import factory from 'artplayer-proxy-mediabunny' +import legacy from 'artplayer-proxy-mediabunny/legacy' + +type Equal = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? true : false +type Assert = T +type ExactFactory = Assert (art: Artplayer) => HTMLCanvasElement>> +type ExactParameters = Assert, [option?: Option]>> +type ExactResult = Assert>, HTMLCanvasElement>> +type ExactResultAlias = Assert> +type NativeAttributes = Assert> +type NativeEvents = Assert> + +const art: MediaBunnyPlayer = new Artplayer({ container: '#player', url: 'movie.mp4', proxy: factory() }) +const replacement: typeof factory = (_option?: Option) => (_art: Artplayer) => document.createElement('canvas') +const canvas: Result = factory(undefined)(art) +const fromLegacy: typeof factory = legacy +const toLegacy: typeof legacy = factory +declare const shim: MediaBunnyShim +const playing: Promise = shim.play() +const paused: void = shim.pause() +const loading: void = shim.load() +const state: Promise = shim.getM3u8State() +const source: unknown = shim.currentSrc +shim.src = new Blob([]) +shim.currentTime = 2 +shim.volume = 0.5 +shim.muted = false +const callback: SyntheticFrameCallback = (now, metadata) => { + const values: number[] = [now, metadata.presentationTime, metadata.expectedDisplayTime, metadata.width, metadata.height, metadata.mediaTime, metadata.presentedFrames, metadata.processingDuration, metadata.captureTime, metadata.receiveTime, metadata.rtpTimestamp] + void values +} +shim.cancelVideoFrameCallback(shim.requestVideoFrameCallback(callback)) +const maybe: 'maybe' = shim.canPlayType('video/mp4') +art.mediabunny?.pause() +delete art.mediabunny +declare const extended: MediaBunnyCanvas +const native: HTMLCanvasElement = extended +extended.play() +extended.addEventListener('click', event => event.clientX) +extended.setAttribute('src', 'native-attribute-only') +state.then((value) => { + if (!value) + return + const height: number | undefined = value.currentLevel?.height + const language: string | undefined = value.currentAudio?.language + const track: unknown = value.levels[0]?.track + // @ts-expect-error SDK internals require explicit narrowing, not ambient SDK declarations. + track.decode() + void [height, language] +}) +// @ts-expect-error The default factory does not promise shim members on a replacement canvas. +canvas.play() +// @ts-expect-error The default result is the historical exact DOM Canvas. +const requiredShim: MediaBunnyCanvas = canvas +// @ts-expect-error Alias does not exist before initialization or after destroy. +art.mediabunny.play() +// @ts-expect-error Factory options are optional but not null. +factory(null) +// @ts-expect-error Volume remains numeric. +factory({ volume: '0.7' }) +// @ts-expect-error Historical Option does not widen arbitrary SDK objects. +factory({ source: {} }) +// @ts-expect-error Option stream remains byte-oriented. +factory({ source: new ReadableStream() }) +// @ts-expect-error Unknown options remain errors. +factory({ arbitrary: true }) +// @ts-expect-error The initializer still requires its host. +factory()() +// @ts-expect-error Synchronous registration remains synchronous. +const promise: Promise = factory()(art) +// @ts-expect-error Computed duration has no writable setter. +shim.duration = 10 +// @ts-expect-error Synchronous load does not falsely promise awaitable completion. +const loaded: Promise = shim.load() +// @ts-expect-error Canvas retains its native string attribute API. +extended.setAttribute('src', new Blob([])) +// @ts-expect-error Manual/auto are the only track modes. +const mode: NonNullable['videoMode'] = 'adaptive' +void [replacement, fromLegacy, toLegacy, playing, paused, loading, state, source, maybe, native, requiredShim, promise, loaded, mode] +export type { ExactFactory, ExactParameters, ExactResult, ExactResultAlias, NativeAttributes, NativeEvents }